已解决忘记实例化我的菜单栏...
我扩展了类 JMenuBar
和类 JFrame
。但是,当我 setJMenuBar(menubar)
时,测试时 MenuBar 不会出现在 Frame
中。
这是我的代码:
类框架:
import javax.swing.JFrame;
public class Frame extends JFrame{
public static MenuBar menubar;
public Frame(){
setTitle("LoL Teamcomps");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setJMenuBar(menubar);
}
}
菜单栏类:
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import com.lolteamcomps.code.components.MenuItem;
public class MenuBar extends JMenuBar{
public MenuBar(){
JMenuItem players = new JMenuItem("Players");
JMenuItem champions = new JMenuItem("Champions");
JMenuItem newPlayer = new JMenuItem("Add new");
JMenuItem newChampion = new JMenuItem("Add new");
players.add(newPlayer);
champions.add(newChampion);
add(players);
add(champions);
}
}
在我的 main 中调用的函数中:
private static Frame frame = new Frame();
public static void CreateWindow(){
frame.pack();
frame.setVisible(true);
}
只出现一个空的框架
,里面什么也没有。我做错了什么?
编辑:我自己的想法是 setJMenuBar(menubar)
不起作用,因为 menubar
不是 JMenuBar
,而是 MenuBar 扩展了 JMenuBar
,所以实际上它是一个 JMenuBar
,对吗?另外,我在这一行没有收到错误,所以我认为情况并非如此。只是一个想法。
最佳答案
举个简单的例子,人们经常使用继承(即:extends
)来减少人们必须阅读的代码量;然而,除非绝对有意义,否则使用继承并不是一个好的做法。在 Java 中,您只能使用继承一次,因此,您应该仔细考虑是否适合扩展 JFrame 或扩展 JMenu。您是否真正扩展了 JFrame 或 JMenu 的功能?如果答案是否定的,那么您应该使用实例变量并在构造函数中实例化它。
例如:
public class MyApplication {
private JFrame frame;
private JMenuBar menuBar;
private JMenu menu;
public MyApplication() {
frame = new JFrame();
... // setup JFrame with layout and other elements
menuBar = new JMenuBar();
menu = new JMenu("File");
menuBar.add(menu);
... // other setup
frame.setVisible(true);
}
关于java - JMenuBar 未出现在 JFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020700/