我想将我的 GUI 代码放在单独的文件中。我的程序已达到 1000 行,这很有压力,因为我的所有代码都在一个文件中
长话短说,我正在从事一个大型项目,所以我将举一个例子来向您展示我需要什么。
首先:这是示例代码:
public class world extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
world frame = new world();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public world() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(0, 0, 427, 89);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(5, 137, 422, 111);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String s = textField.getText();
JOptionPane.showMessageDialog(null, s);
}
});
contentPane.add(btnNewButton);
}
}
第二:正如您可以在一个文件中看到所有方法和所有内容,但这不适合我。
第三:我希望这段代码脱离父类(主类),我不知道如何,有没有办法继承,或者创建一个新类,或者一个接口(interface)类我需要一种方法来我的main 方法之外的函数或数学。
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String s = textField.getText();
JOptionPane.showMessageDialog(null, s);
}
});
如果您回答我的问题,请提供书面代码,因为我很沮丧。我问了又问,但我得到的答案与我需要的完全不同。
最佳答案
你的主类看起来像这样
public class MyMainClass{
public static void main(String[] args){
MyClass myclass = new MyClass();
myclass.doSomething();
}
}
你的其他类(class)看起来像这样
public class MyClass{
public void doSomething()
{
//do something
}
}
}
这篇文章也很好读http://www.javapractices.com/topic/TopicAction.do?Id=205
关于java - 如何在单独的文件中制作 GUI 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21474749/