我正在寻找一个例子,点击不同的按钮时应打开不同的标签,结果/输出应写入其中的文本面板。
文本面板应嵌入选项卡内。
我正在寻找示例而不是完整的解决方案
答案 0 :(得分:1)
您应该在按钮侦听器中调用JTabbedPane.setSelectedIndex
,请尝试以下示例:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main
{
private static int numberOfTabs = 1;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
UIManager.setLookAndFeel(
"javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e)
{
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 400, 500);
JButton addNewTab = new JButton("Add new Tab");
JTabbedPane tab = new JTabbedPane();
addNewTab.addActionListener(e -> {
tab.add(new JLabel("new tab " + numberOfTabs + " created."),
"tab " + numberOfTabs);
tab.setSelectedIndex(numberOfTabs - 1);
numberOfTabs++;
});
frame.add(addNewTab, BorderLayout.NORTH);
frame.add(tab, BorderLayout.CENTER);
frame.setVisible(true);
}
});
}
}