Question

I am writing a basic timer program with Java, and in the program I would like to have a menu bar at the top. 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.

Was it helpful?

Solution

It is not a good idea to paint the JFrame directly. It may be less troublesome to extend a JComponent, override its paintComponent() to do your custom painting, and add it to the JFrame. This way the JMenuBar goes on the JFrame and everything works fine.

   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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top