我问这个是因为当我开始学习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();
创建它。
答案 0 :(得分:2)
看起来很好。
Java类名称应以大写字母开头。 Frame是一个Java类,因此您应该调用MyFrame类(或Frame以外的任何类)。
您需要将课程放在Event Dispatch thread(EDT)上。您可以使用以下代码执行此操作:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyFrame();
}
});