In: Computer Science
Give an example of a program in java that creates a GUI with at least one button and several textfields. Some of the textfields should be for input and others for output. Make the output textfields uneditable. When the button is clicked, the input fields should be read, some calculation performed and the result displayed in the output textfield(s).
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalcVolCube extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
GridLayout layout = new GridLayout(9, 0);
JLabel len = new JLabel(" Length:");
JLabel wid = new JLabel(" Width:");
JLabel hgt = new JLabel(" Height:");
JLabel ansl = new JLabel(" Volume of Cube: ");
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(30);
JTextField t3 = new JTextField(30);
JTextField ansf = new JTextField(30);
JButton calc = new JButton(" Calculate ");
Float ans;
/**
*
*/
public CalcVolCube() {
super("Cube Volume Calculator");
setSize(300, 300);
add(len);
add(t1);
add(wid);
add(t2);
add(hgt);
add(t3);
add(ansl);
add(ansf);
add(calc);
ansf.setEditable(false);
setLayout(layout);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calc.addActionListener(this);
setVisible(true);
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
String n1 = t1.getText();
String n2 = t2.getText();
String n3 = t3.getText();
Float num1 = Float.parseFloat(n1);
Float num2 = Float.parseFloat(n2);
Float num3 = Float.parseFloat(n3);
Object clicked = e.getSource();
if (calc == clicked) {
ansf.setText(String.valueOf(num1*num2*num3));
}
ansf.setEditable(false);
}
/**
* @param args
*/
public static void main(String[] args) {
CalcVolCube calc = new CalcVolCube();
calc.setVisible(true);
}
}
Output: