I ran the following code 10 times. Of the 10 runs, 3 showed both the menu bar and the rectangle, 3 showed only the rectangle, and 4 showed nothing at all. What am I doing wrong?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static java.awt.Color.*;
import java.awt.image.*;
public class GUI extends JFrame implements KeyListener, ActionListener
{
int x, y;
public static void main(String[] args)
{
new GUI();
}
public GUI()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e)
{
e.printStackTrace();
}
frameInit();
setSize(1024,768);
setDefaultCloseOperation(EXIT_ON_CLOSE);;
setVisible(true);
setJMenuBar(createMenuBar());
addKeyListener(this);
createBufferStrategy(2);
x = 0;
y = 49;
}
public void paint(Graphics gm)
{
BufferStrategy bs = getBufferStrategy();
try
{
Graphics g = bs.getDrawGraphics();
super.paint(g);
g.setColor(WHITE);
g.drawRect(0,0,1024,768);
g.setColor(BLACK);
g.fillRect(x,y,100,100);
bs.show();
}catch(Exception e)
{
}
}
public JMenuBar createMenuBar()
{
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem save = new JMenuItem("Save");
save.setMnemonic(KeyEvent.VK_S);
save.addActionListener(this);
JMenuItem load = new JMenuItem("Load");
load.setMnemonic(KeyEvent.VK_L);
load.addActionListener(this);
JMenuItem quit = new JMenuItem("Quit");
quit.setMnemonic(KeyEvent.VK_Q);
quit.addActionListener(this);
fileMenu.add(save);
fileMenu.add(load);
fileMenu.addSeparator();
fileMenu.add(quit);
JMenu editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
JMenuItem undo = new JMenuItem("Undo");
undo.setMnemonic(KeyEvent.VK_U);
undo.addActionListener(this);
JMenuItem redo = new JMenuItem("Redo");
redo.setMnemonic(KeyEvent.VK_R);
redo.addActionListener(this);
editMenu.add(undo);
editMenu.add(redo);
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
JMenuItem controls = new JMenuItem("Controls");
controls.setMnemonic(KeyEvent.VK_C);
controls.addActionListener(this);
JMenuItem about = new JMenuItem("About");
about.setMnemonic(KeyEvent.VK_A);
about.addActionListener(this);
helpMenu.add(controls);
helpMenu.addSeparator();
helpMenu.add(about);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
menuBar.setLocation(0,23);
return menuBar;
}
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand());
repaint();
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_UP)
{
y-=10;
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
y+=10;
}
if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
x-=10;
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
x+=10;
}
repaint();
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}