The program compiles but I can't see the rectangle on the window, Can someone help me, I am new to this. My goal is just to draw three rectangles on the window. for a traffic light program.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.Color;
import java.awt.Canvas;
import java.lang.String;
import java.awt.Graphics;
class traffic extends Canvas implements ActionListener{
static JRadioButton b1,b2,b3;
static JPanel jp = new JPanel();
static JFrame win= new JFrame("Traffic light");
traffic(){
b1= new JRadioButton("red");
b2= new JRadioButton("green");
b3= new JRadioButton("yellow");
jp.add(b1);
jp.add(b2);
jp.add(b3);
win.add(jp);
win.setLayout(new FlowLayout());
win.setSize(500,500);
win.setVisible(true);
win.setDefaultCloseOperation(win.DISPOSE_ON_CLOSE);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent e) throws ArithmeticException
{ }
public void paint(Graphics g){
g.setColor(Color.RED);
g.fillRect(130, 30,100, 80);
}
public static void main(String[] args)
{ traffic tr= new traffic();
tr.repaint();
}
}
Canvas
(or even use it), but do extend JPanel
.JPanel
to the JFrame
- (win.add(this)
)JPanel
just using add(b1)
etcpaint
, but do override paintComponent
. And do it as follows:@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// your stuff here
JFrame
. Set the size of the JPanel
. Otherwise your JFrame
border absorbs some of the size, making your panel smaller than you may want. Do it as follows.@Override
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
You still have other logic to work out but this should get you started.
Style corrections
These are not critical to the execution of your code but important to learn.
win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);