2016-04-14 28 views
0

我是新兴的swing编程。我创建了Jtabbedpane并添加了4个jpanel。如何在swing中使用多个jpanel选项卡时组织代码

4个jpanel中的所有按钮和标签都在相同的java类中,并且开始显得杂乱无章。我正在使用Intellij。如果我可以将与一个面板相关的所有项目和事件放入其自己的类中,那么将会很好,因此4个面板的4个类以及对主框架中这些类的引用。不知道如何做到这一点,因为大部分代码都是由IDE生成的。

如果有办法做到这一点或做这个,请让我知道的教程。

+0

我不会建议使用的IntelliJ的自动化Swing GUI的发电机,如果你正在构建一个复杂的GUI。该代码不可读且不可维护,也不允许您更改Swing中通常可编辑的组件的许多属性。我的建议是你编写你自己的图形用户界面,而不需要Intellij的自动代码生成器。 –

回答

0

是的,你可以很容易地打破这一点。任何地方代码生成一个新的面板,可能作为一个“构建”方法,你可以把它拉出来,并在另一个类的结构中创建。一个例子是这个样子:

// 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 :) 
} 

然后使用该面板在主JFrame中,你可以聚合这样的:

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); 
相关问题