Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

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();
}
}
question from:https://stackoverflow.com/questions/65902297/error-with-drawing-rectangle-in-java-swing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...