更改选项卡名称

时间:2012-03-14 10:19:42

标签: java swing jtabbedpane

enter image description here

我想通过添加ActionPerformed来单击弹出菜单中的“重命名”项来更改选项卡名称,并直接在选项卡上键入新名称。

我找到了这个jTabbedPane.setTitleAt(count, "string here");

但它不是我想要的,这只是将字符串设置为参数传递。

由于

1 个答案:

答案 0 :(得分:4)

通过添加JPopupMenu可以确定index

中的getTitleAt()JTabbedPane
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public class TabPopupDemo extends JFrame {

    private static final long serialVersionUID = 1L;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JMenuItem jMenuItem1;
    private JPopupMenu jPopupMenu1;
    private JTabbedPane jTabbedPane1;

    public TabPopupDemo() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(400, 300);
        setLocationRelativeTo(null);
        jPopupMenu1 = new JPopupMenu();
        jMenuItem1 = new JMenuItem("jMenuItem1");
        jTabbedPane1 = new JTabbedPane();
        jLabel1 = new JLabel("jLabel1");
        jLabel2 = new JLabel("jLabel2");
        jPopupMenu1.add(jMenuItem1);
        jTabbedPane1.addTab(null, jLabel1);
        jTabbedPane1.addTab(null, jLabel2);
        getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
        int tabCount = jTabbedPane1.getTabCount();
        for (int i = 0; i < tabCount; i++) {
            JLabel jLabel = new JLabel("Testing the tab" + (i + 1));
            jTabbedPane1.setTabComponentAt(i, jLabel);
            jLabel.setName(String.valueOf(i));
            jLabel.setComponentPopupMenu(jPopupMenu1);
        }
        jPopupMenu1.addPopupMenuListener(new PopupMenuListener() {

            @Override
            public void popupMenuCanceled(final PopupMenuEvent evt) {
            }

            @Override
            public void popupMenuWillBecomeInvisible(final PopupMenuEvent evt) {
            }

            @Override
            public void popupMenuWillBecomeVisible(final PopupMenuEvent evt) {
                JPopupMenu source = (JPopupMenu) evt.getSource();
                JLabel invoker = (JLabel) source.getInvoker();
                JLabel component = (JLabel) jTabbedPane1.getComponentAt(Integer.parseInt(invoker.getName()));
                jMenuItem1.setText(invoker.getText() + ":  " + component.getText());
            }
        });
    }

    public static void main(final String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TabPopupDemo().setVisible(true);
            }
        });
    }
}