-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVG.java
More file actions
87 lines (70 loc) · 2.55 KB
/
VG.java
File metadata and controls
87 lines (70 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class VG implements ActionListener {
// textfields are made global variables to allow the button actionEvent method to pull their text
JTextField distanceField = new JTextField(10);
JTextField timeField = new JTextField(10);
JTextField resultField = new JTextField(5);
// constructor - good practice to include rather than loading up the main method
public VG() {
GUISetup();
}
public String calculate(String distanceString, String timeString) {
double distance = Double.parseDouble(distanceString);
double time = Double.parseDouble(timeString);
double speed = distance/time;
return Double.toString(speed);
}
public void GUISetup() {
JFrame frame = new JFrame("Velocity");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
//Jcomponents (incl gridbagcontraints)
GridBagConstraints dgbc = new GridBagConstraints();
dgbc.gridx = 1;
dgbc.gridy = 0;
panel.add(distanceField, dgbc);
JLabel distanceLabel = new JLabel("Distance: ");
dgbc.gridx = 0;
dgbc.gridy = 0;
panel.add(distanceLabel, dgbc);
dgbc.gridx = 1;
dgbc.gridy = 1;
panel.add(timeField, dgbc);
JLabel timeLabel = new JLabel("Time: ");
dgbc.gridx = 0;
dgbc.gridy = 1;
panel.add(timeLabel, dgbc);
//add button to perform calculation
JButton calculateButton = new JButton("Calculate");
dgbc.gridx = 1;
dgbc.gridy = 2;
panel.add(calculateButton, dgbc);
calculateButton.addActionListener(this);
//add output field
dgbc.gridx = 1;
dgbc.gridy = 3;
panel.add(resultField, dgbc);
JLabel resultLabel = new JLabel("Result: ");
dgbc.gridx = 0;
dgbc.gridy = 3;
panel.add(resultLabel, dgbc);
frame.getContentPane().add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String distanceString = distanceField.getText();
String timeString = timeField.getText();
try{
String resultString = calculate(distanceString, timeString);
resultField.setText(resultString);
} catch (NumberFormatException exeception) {
resultField.setText("Invalid Input");
}
}
public static void main(String[] args){
new VG();
}
}