我有 2 个框架。其中一个包含对数据执行适当操作的按钮。第二帧包含选项卡 View 中的数据。 现在我必须通过单击此按钮在第一帧中添加一个按钮,应在第二帧上添加新选项卡。我怎样才能做到这一点?
最佳答案
使第二帧的 JTabbedPane
在第一帧中可访问,然后只需调用 JTabbedPane
的 add()
方法即可添加新的其中的选项卡。
以下是示例代码:
第一帧:-
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250,250);
JButton button = new JButton("Add tab to another frame.");
button.addActionListener(this);
frame.add(button);
frame.setVisible(true);
第二帧:-
装饰tabbedPane的全局变量
JTabbedPane tabs;
int i = 0; // just a tab counter. You might not need this.
初始化代码
JFrame frame2 = new JFrame("Demo 2");
frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame2.setSize(250,250);
tabs = new JTabbedPane();
frame2.add(tabs);
frame2.setVisible(true);
第一帧中按钮单击的操作:-
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.add(new JLabel("tab number "+i));
tabs.add((i++)+"",panel); //--access tabbedPane of second frame here.
}
关于java - 在单击按钮的框架以外的框架中打开新选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6895302/