程序如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CelsiusConverter extends JFrame {
JPanel pane;
JButton button;
JTextField txt;
JLabel a,b;
public CelsiusConverter() {
//constructor
super("Change a to b " );
}
public Component creatComponent() {
//creat the component that will be used.
pane =new JPanel(new GridLayout(2,2));
button = new JButton("Convert");
txt = new JTextField();
a = new JLabel("a");
b = new JLabel("b");
button.addActionListener(buttonL);
pane.add(txt);
pane.add(a);
pane.add(button);
pane.add(b);
return pane;
}
public int convert() {
//convert a to b.如果用户输入的不是int型,我想弹出一个消息框来提醒出错,怎么做?
return Integer.parseInt(txt.getText())*10;
}
ActionListener buttonL =new ActionListener() {
//button actinlistener
public void actionPerformed(ActionEvent e) {
b.setText("b is " +convert());
}
};
public void creatAndShowGUI() {
//creat and show the GUI.
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(creatComponent());
setSize(200,100);
setVisible(true);
}
public static void main(String args[]) {
//main method.
new CelsiusConverter().creatAndShowGUI();
}
}