I have a sample code that is simply to build a JFrame with a rectangle and a few buttons. I completed building the rectangles and now i'm onto placing two buttons, one start - top and one stop - bottom.
I have everything working, at least the science of it. However when i'm trying to set the start button to run the code nothing happens. I tried to see if there was an error by creating a JFrame and the code was successful. The JFrame is supposed to open with a start button that initiates the paintComponent()
and the stop terminates the entire thing.
Is there anyone who could possible provide abit of guidance, i havn't slept for days trying to figure this outt.
public static void main (String[] args){
TwoButtonsRandomRec two = new TwoButtonsRandomRec();
two.go();
}
public void go(){
JPanel pan = new JPanel(new GridBagLayout());
START = new JButton("START");
START.addActionListener(new StartListener());
STOP = new JButton("STOP");
STOP.addActionListener(new StopListener());
pan.add(START);
pan.add(STOP);
frame = new JFrame();
frame.getContentPane().add(BorderLayout.NORTH, START);
frame.getContentPane().add(BorderLayout.SOUTH, STOP);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void GUI(){
JFrame frame2 = new JFrame();
frame2.setSize(500,500);
frame2.setVisible(true);
}
class StartListener implements ActionListener{
public void actionPerformed(ActionEvent e){
//frame.getContentPane().add(new DrawPanel());
//System.exit(0);
//
DrawPanel panel = new DrawPanel();
}
}
class StopListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
/*
* Panel created
* rectangle drawn to random sizes
*/
class DrawPanel extends JPanel{
public void paintComponent(Graphics g){
ran = new Random();
g.setColor(new Color(ran.nextInt(255),+
ran.nextInt(255),ran.nextInt(255)));
height = ran.nextInt(getHeight());
width = ran.nextInt(getWidth());
x = ran.nextInt(getWidth()-width);
y = ran.nextInt(getHeight()-height);
g.fillRect(x,y,width,height);
//repaint();
try{
Thread.sleep(240);
}catch(InterruptedException ie){
}
repaint();
}
}
}