简体   繁体   中英

Adding JMenuBar and JPanel to a JFrame

I am having some trouble with adding a JMenuBar and a JPanel to a JFrame, here is my Main Method:

public static Timer timer = new Timer(100, ActionListener.repaint);


public static void main(String[] args) {
    Insets in;
    frame.setSize(600, 500);
    frame.pack();
    in = frame.getInsets();
    frame.setSize(600 + (in.left + in.right) - 10, 500 + (in.top + in.bottom) - 10);
    frame.setResizable(false);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    add.addActionListener(new ActionListener());
    frame.setJMenuBar(menuBar);


    menuBar.add(file);
    file.add(add);
    file.add(sub);

    frame.add(gui);
    timer.start();

    frame.setVisible(true);
}

The field 'gui' is my JPanel class:

@Override
public void paintComponent(Graphics g) {


}

Here is my repaint Timer:

public static java.awt.event.ActionListener repaint = new java.awt.event.ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        GUI.gui.repaint();
    }
};

here is the output:

您可以看到它重复了我的JMenuBar

See how it duplicated the JMenuBar? It does that for anything painted onto that JPanel. Any solutions?

Any solutions?

Yes. Dont call Thread.sleep in the paintComponent method. In fact dont call Thread.sleep anywhere in a Swing application. For periodic delays use a Swing Timer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM