我最近重写了很多我的应用程序,在我这样做之前,我试图完成的工作很好。我试图通过 a in a隐藏JTabbedPane
按需。JCheckBoxMenuItem
JMenuBar
我之前所做的似乎完全一样,尽管这次它不起作用。我试过使用invokeLater(...)
但无济于事。
这是我正在使用的基本示例:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class ToolkitFrame extends JFrame {
private static final long serialVersionUID = -6757985823719418526L;
public static void main(String[] args) {
new ToolkitFrame().construct();
}
private UtilityTabs utilityTabs;
public UtilityTabs getUtilityTabs() {
if (utilityTabs == null) {
utilityTabs = new UtilityTabs();
}
return new UtilityTabs();
}
public ToolkitFrame() {
super();
}
public void construct() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(getGameScreen(), BorderLayout.CENTER);
add(getUtilityTabs().getTabs(), BorderLayout.EAST);
setJMenuBar(getJMenuBar());
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public JMenuBar getJMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu viewMenu = new JMenu("View");
final JCheckBoxMenuItem checkbox = new JCheckBoxMenuItem("Show Utilities");
checkbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
getUtilityTabs().getTabs().setVisible(checkbox.isSelected());
System.out.println("Tabs should be: " + (checkbox.isSelected() ? "visible" : "hidden"));
}
});
checkbox.setSelected(true);
viewMenu.add(checkbox);
menuBar.add(viewMenu);
return menuBar;
}
public JPanel getGameScreen() {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(765, 503));
panel.setBackground(Color.BLACK);
return panel;
}
class UtilityTabs {
private JTabbedPane tabs;
public JTabbedPane getTabs() {
return tabs;
}
private Tab tab;
public Tab getTab() {
if (tab == null) {
tab = new Tab();
}
return tab;
}
public UtilityTabs() {
tabs = new JTabbedPane(JTabbedPane.TOP);
tabs.setPreferredSize(new Dimension(275, 503));
tabs.add("FooBar", getTab());
tabs.setVisible(true);
}
class Tab extends JPanel {
private static final long serialVersionUID = 677183279827434278L;
private DefaultListModel<String> listModel;
private JList<String> list;
public Tab() {
construct();
}
public void construct() {
listModel = new DefaultListModel<String>();
for (String name : new String[] { "foo", "bar" }) {
listModel.addElement(name);
}
list = new JList<String>(listModel);
add(new JScrollPane(list));
}
}
}
}
谁能告诉我我做错了什么?我基本上希望根据用户设置显示或隐藏游戏的实用程序(无需重新启动)。
使用setVisible(false)
不会显示它们,但如果我希望它在不重新启动应用程序的情况下完成,那将无济于事。