IntelliJ IDEA中的自定义视图类

时间:2017-03-09 14:49:50

标签: java swing intellij-idea

所以我使用布局管理器GridLayoutManager(IntelliJ)在IntelliJ IDEA中构建Swing布局。

它没问题,我可以布局我所有的东西等但是所有内容都在同一个代码文件中,并且考虑到我使用带有JTabbedPane的JPanel,我希望选项卡式窗格的每个窗格都可以表示一个单独的课程。

这怎么可能?

1 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点,要么扩展JPanel,要么创建另一个包含JPanel

的类

基于继承的解决方案

public class MyCustomPanel extends JPanel {

    // implement your custom behavior in here
}

然后在你创建JTabbedPane的地方,你有这样的事情:

private void init() {
    JTabbedPane jtp = new JTabbedPane();
    JPanel jp = new MyCustomPanel();
    jtp.add(jp);
}

虽然这有效,但从长远来看,延长JPanel可能会引起头痛。另一个有利于composition over inheritance的方法可能看起来像这样:

基于成分的解决方案

public class MyCustomPanel {
    private JPanel myPanel = new JPanel();

    public MyCustomPanel() {
        // add your customizations to myPanel
    }

    public JPanel getPanel() {
        return myPanel;
    }
}

然后在哪里创建JTabbedPane

private void init() {
    JTabbedPane jtp = new JTabbedPane();
    MyCustomPanel mp = new MyCustomPanel();
    jtp.add(mp.getPanel());
}