我想通过添加 ActionPerformed 从弹出菜单中单击“重命名”项来更改选项卡名称,然后直接在选项卡上键入新名称。
我找到了这个jTabbedPane.setTitleAt(count, "string here");
但这不是我想要的,这只是设置作为参数传递的字符串。
谢谢
最佳答案
通过添加JPopupMenu
,可以从JTabbedPane
确定index
和getTitleAt()
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);
}
});
}
}
关于java - 更改选项卡名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9699974/