我之所以问这个问题,是因为当我开始学习GUI时,我并不太喜欢其他人使用的方法,所以我自己创造了这种方法。下面的代码是创建框架的类。
class Frame{
private JFrame frm;
private JLabel desc;
private JTextField username;
private JPasswordField password;
Frame(){
//Creating and setting the frame
frm = new JFrame();
frm.setLayout(new FlowLayout());
frm.setDefaultCloseOperation(frm.EXIT_ON_CLOSE);
frm.setResizable(true);
frm.setSize(300, 300);
frm.setLocationRelativeTo(null);
frm.setTitle("Default title");
//Initializing variables
desc = new JLabel("This is the description");
username = new JTextField("Username");
password = new JPasswordField("Password");
EventHandler handler = new EventHandler();
//Adding components to the frame
frm.add(desc);
frm.add(username);
frm.add(password);
//Handling the components
username.addActionListener(handler);
password.addActionListener(handler);
//Showing the frame
frm.setVisible(true);
}
class EventHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource() == username){
JOptionPane.showMessageDialog(null, "You typed \"" + username.getText() + "\" inside the username box.");
} else if(event.getSource() == password){
JOptionPane.showMessageDialog(null, "You typed \"" + password.getText() + "\" inside the password box.");
}
}
}
}
在主类中只需简单地放置如下内容:
Frame frm = new Frame();
创建它。