[英]How to draw a JMenuBar on top of a graphics
I am writing a basic timer program with Java, and in the program I would like to have a menu bar at the top. 我正在用Java编写一个基本的计时器程序,并且在该程序的顶部我希望有一个菜单栏。 The code I have as of now is:
到目前为止,我拥有的代码是:
public Main() {
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu menu = new JMenu("Test");
menubar.add(menu);
JMenuItem menuitem = new JMenuItem("Item");
menu.add(menuitem);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setTitle(Namer.name);
new Timer(delay, timer).start();
new Timer(1, new Refresher()).start();
setResizable(false);
setVisible(true);
}
public void paint(Graphics g) {
Graphics buffer = unscreen.getGraphics();
buffer.setColor(Color.white);
buffer.fillRect(0, 0, 500, 500);
buffer.setColor(Color.black);
buffer.setFont(new Font("Times New Roman", Font.PLAIN, 25));
// buffer.drawString("hours:minutes:seconds: ", 25, 100);
buffer.drawString(hourss + numhours + ":" + minutess + numminutes + ":"
+ secondss + numseconds, 100, 100);
g.drawImage(unscreen, 0, 0, null);
}
When I run this code, I get everything I would expect, which is some numbers showing how long the program has been up and a menu bar at the top of the screen, except the menu bar. 当我运行这段代码时,我得到了我期望的一切,这是一些数字,表示程序已经运行了多长时间,并且屏幕顶部的菜单栏(菜单栏除外)。 I have tried commenting out the paint method, and when i do that it works.
我尝试注释掉绘画方法,当我这样做时它起作用了。 Is there a better way to do what I am doing or a different solution to my problem?
是否有更好的方式来做我正在做的事情或对我的问题有不同的解决方案? Also, I don't need to have the paint method there if there is a better way to print stuff on the window.
另外,如果有更好的方法在窗口上打印内容,则无需在这里使用paint方法。
It is not a good idea to paint the JFrame directly. 直接绘制JFrame不是一个好主意。 It may be less troublesome to extend a JComponent, override its paintComponent() to do your custom painting, and add it to the JFrame.
扩展JComponent,重写其paintComponent()进行自定义绘制,然后将其添加到JFrame,可能不会那么麻烦。 This way the JMenuBar goes on the JFrame and everything works fine.
这样,JMenuBar就可以在JFrame上运行,并且一切正常。
public class DrawingSurface extends JComponent{
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics buffer = unscreen.getGraphics();
buffer.setColor(Color.white);
buffer.fillRect(0, 0, 500, 500);
buffer.setColor(Color.black);
buffer.setFont(new Font("Times New Roman", Font.PLAIN, 25));
// buffer.drawString("hours:minutes:seconds: ", 25, 100);
buffer.drawString(hourss + numhours + ":" + minutess + numminutes + ":"
+ secondss + numseconds, 100, 100);
g.drawImage(unscreen, 0, 0, null);
}
}
Now you add an instance of DrawingSurface to the JFrame. 现在,您将DrawingSurface实例添加到JFrame。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.