I just recently started learning Java.
Playing around with graphics I wrote the test code below which at program start should display a frame with a central panel for graphics and an upper panel with a menu. However, an empty frame is shown instead. Then, as soon as the user mouse clicks on the frame everything shows up as intended.
What am I doing wrong?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Demo {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
theFrame f = new theFrame("Learning practice",50,50,600,400);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
class theFrame extends JFrame {
private boolean gridIsOn;
private Point point;
private int myWidth,myHeight;
public theFrame(String title,int left,int top,int width,int height) {
gridIsOn=false;
myWidth=width;
myHeight=height;
setTitle(title);
setLocation(left,top);
setSize(width,height);
upperPanel up=new upperPanel();
add (up, BorderLayout.NORTH);
centralPanel cp=new centralPanel();
cp.setBackground(Color.LIGHT_GRAY);
add(cp,BorderLayout.CENTER);
}
class upperPanel extends JPanel {
public upperPanel() {
setLayout(new FlowLayout(FlowLayout.LEFT));
JMenuBar myMenuBar=new JMenuBar();
JMenu tools=new JMenu("Tools");
JMenuItem grid=new JMenuItem("Toggle grid");
grid.addActionListener(new MenuActList());
myMenuBar.add(tools);
tools.add(grid);
add(myMenuBar);
}
}
class MenuActList implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand()=="Toggle grid") {
gridIsOn=!gridIsOn;
repaint();
}
}
}
class centralPanel extends JPanel {
public centralPanel() {
staticMouse Jerry=new staticMouse();
addMouseListener(Jerry);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(gridIsOn) {
g2.setColor(Color.BLUE);
for(int i=0;i<myWidth;i+=10) {
g2.drawLine(i, 0, i, myHeight);
}
for(int i=0;i<myHeight;i+=10) {
g2.drawLine(0, i, myWidth, i);
}
}
g2.setColor(Color.RED);
g2.drawRect(point.x-25,point.y-25,50,50);
}
}
class staticMouse implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
point = e.getPoint();
repaint();
}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
}
}