Java 如何在swing中使用多个jpanel选项卡时组织代码

Java 如何在swing中使用多个jpanel选项卡时组织代码,java,swing,intellij-idea,Java,Swing,Intellij Idea,我不熟悉swing编程。我创建了一个Jtabbedpane,并向其中添加了4个jpanel 4JPanel中的所有按钮和标签都在同一个java类中,并且开始显得杂乱无章。我正在使用Intellij。如果我能将与一个面板相关的所有项目和事件放在它自己的类中,那么4个面板对应4个类,并且只在主框架中引用这些类,那就太好了。由于大部分代码是由IDE生成的,因此不确定如何执行此操作 如果有一种方法可以做到这一点,或者有一个教程可以做到这一点,请让我知道。是的,您可以很容易地将其分解。在代码生成新面板的任

我不熟悉swing编程。我创建了一个Jtabbedpane,并向其中添加了4个jpanel

4JPanel中的所有按钮和标签都在同一个java类中,并且开始显得杂乱无章。我正在使用Intellij。如果我能将与一个面板相关的所有项目和事件放在它自己的类中,那么4个面板对应4个类,并且只在主框架中引用这些类,那就太好了。由于大部分代码是由IDE生成的,因此不确定如何执行此操作


如果有一种方法可以做到这一点,或者有一个教程可以做到这一点,请让我知道。

是的,您可以很容易地将其分解。在代码生成新面板的任何地方,可能作为“build”方法,您都可以将其拉出并在另一个类中的结构中生成。示例如下所示:

// New class file named testPanel.java
public class testPanel extends JPanel{
    // Constructor
    public textPanel(){
        // Add an example button
        JButton btn_exit = new JButton("Exit");
        btn_exit.addActionListener(new ExitButtonListener());
        buttons.add(btn_exit);
    }

    // Private inner class which does event handling for our example button
    private class ExitButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.exit(0);
        }
    }

   // Add whatever other code you like here or above or anywhere else :)
}
private testPanel pnl_test  = new textPanel();
// You can place this in the constructor 
// for your JFrame without the "MyJFrame."
// But for demonstration purposes I will include it
MyJFrame.add(pnl_test);
// Or if you were placing a panel inside of another panel,
// you can use the same method associated with a JPanel object
MyJPanel.add(pnl_test);
然后,要在主JFrame中使用该面板,可以按如下方式进行聚合:

// New class file named testPanel.java
public class testPanel extends JPanel{
    // Constructor
    public textPanel(){
        // Add an example button
        JButton btn_exit = new JButton("Exit");
        btn_exit.addActionListener(new ExitButtonListener());
        buttons.add(btn_exit);
    }

    // Private inner class which does event handling for our example button
    private class ExitButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.exit(0);
        }
    }

   // Add whatever other code you like here or above or anywhere else :)
}
private testPanel pnl_test  = new textPanel();
// You can place this in the constructor 
// for your JFrame without the "MyJFrame."
// But for demonstration purposes I will include it
MyJFrame.add(pnl_test);
// Or if you were placing a panel inside of another panel,
// you can use the same method associated with a JPanel object
MyJPanel.add(pnl_test);

如果您正在构建复杂的GUI,我不建议您使用Intellij的自动Swing GUI生成器。该代码不可读且不可维护,而且它不允许您更改通常在Swing中可编辑的组件的许多属性。我的建议是,在没有Intellij自动代码生成器的情况下编写自己的GUI。