在java中按下按钮后添加选项卡

问题描述:

我正在使用java swing,并且我想在用户从JMenuBar选择“新建”后添加3个选项卡。在java中按下按钮后添加选项卡

当应用程序启动时,选项卡将不存在。这些将在选择“新建”后才会显示。

我该怎么办?我需要将这些添加到“新”的actionListener?如何添加?

+0

我是ActionListener的内加入insertTab的。但它显示的方法没有找到。 – 2012-07-13 07:01:46

既然你用JTabbedPane标记了这个问题,我假定你正在使用的组件。您可以使用addTabinsertTab方法添加选项卡。

如果你想在按钮按下的反应中做到这一点,把这些电话放在ActionListener确实是一个有效的解决方案。

添加ActionListenerJButton这样的:

final JTabbedPane tabbedPane = new JTabbedPane(); 
    JButton addButton = new JButton("new"); 
    addButton.addActionListener(new ActionListener() { 
     //will be called if the button gets clicked 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      JPanel panel = new JPanel();//will be displayed in the Tab 
      tabbedPane.add("title", panel); 
      //.add() is the easier way for tabbedPane.insertTab(many arguments here) 
      //add what ever you like(repeat three times) 
     } 
    }); 
+1

+1让我看看tabbedPane.add(..)的来源 - 令人惊讶的是,它真的被覆盖委托给addTab(对于组件!= UIResource :-) – kleopatra 2012-07-13 10:00:35

+0

@kleopatra看文档就足够了。 Javadoc提到'insertTab的封面方法'。' – Robin 2012-07-13 10:23:49

+0

@Robin - true,虽然我习惯于不完全依赖文档,但我自己是一个懒惰的文档编写者:-)另外它没有提到UIResource的东西:对应用程序代码不重要,对框架代码不重要少...) – kleopatra 2012-07-13 10:49:51