[英]How to add swing components that are outside of main file?
Example of my problem: 我的问题的例子:
I have a main file: 我有一个主文件:
public class APP extends JFrame
{
private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
public APP()
{
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setJMenuBar(new MenuBar());
JPanel content = new JPanel(new GridLayout(0, 8, 2, 2));
add(new JScrollPane(content, 22, 32), BorderLayout.CENTER);
pack();
setLocationByPlatform(true);
setResizable(false);
setVisible(true);
}
public Dimension getPreferredSize()
{
return new Dimension(screen.width / 10 * 7, screen.height / 10 * 6);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
APP program = new APP();
}
});
}
}
And I have an external object that I'm trying to add as a JMenuBar: 我有一个外部对象,我试图添加为JMenuBar:
public class MenuBar extends JMenuBar
{
public MenuBar()
{
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
add(file);
JMenuItem item;
item = new JMenuItem("Add New");
item.setMnemonic(KeyEvent.VK_N);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
ActionEvent.ALT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//createThumb();
}
});
file.add(item);
}
}
However, my menu bar doesn't show up at all. 但是,我的菜单栏根本没有显示。 When I create a JMenuBar function inside the main file, such as... createMenuBar() and have the same exact code within it, it shows up when I add it to the frame, but when I have it as an external object, it doesn't. 当我在主文件中创建一个JMenuBar函数,例如... createMenuBar()并且在其中具有相同的确切代码时,它会在我将其添加到框架时显示,但是当我将它作为外部对象时,它会显示没有。
What am I doing wrong? 我究竟做错了什么?
EDIT: Fixed the error. 编辑:修正了错误。 Refer to the code above. 请参阅上面的代码。
You accidentily defined your constructor as a method. 您意外地将构造函数定义为方法。 Change the signature to public MenuBar()
(without return value) and it should work. 将签名更改为public MenuBar()
(没有返回值),它应该工作。
public class MenuBar extends JMenuBar
{
public MenuBar()
{
// constructor code
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.