Search code examples
javaswingjframeawtpaint

error with drawing rectangle in java swing


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();
}
}

Solution

    • Don't extend Canvas (or even use it), but do extend JPanel.
    • add the JPanel to the JFrame - (win.add(this))
    • Your button's are filling the panel, hiding the background. Give them a size
    • Add them to the JPanel just using add(b1) etc
    • Don't override paint, but do override paintComponent. And do it as follows:
    @Override
    public void paintComponent(Graphics g) {
       super.paintComponent(g);
       // your stuff here
    
    • Don't set the size of the 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.

    • By convention, classes begin with an upper case character.
    • Use the class name, not an instance when referring to static values.
    win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);