我之所以这样问是因为,当我开始学习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();
创建它。
看起来不错。
Java类名称应以大写字母开头。Frame是Java类,因此您应该将您的类称为MyFrame(或Frame以外的任何其他类)。
您需要将您的类放在事件分发线程(EDT)上。您将使用以下代码执行此操作:
。
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyFrame();
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句