代码如下:
package org.Picture;
import javax.swing.;
import java.awt.;
public class Plot extends JPanel {
private int x;
private int y;
private int width;
private int height;
private Color color;
private static final long serialVersionUID = 1L;
public Plot(int x,int y,int width,int height,Color color){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.color = color;
}
//绘制方法
public void paint(Graphics g){
super.paint(g);
g.setColor(color);
g.fillRect(x,y,width,height);
}
public static void main(String[] args) {
Frame frame = new Frame("窗口");
frame.setSize(800,600);
Plot plot1 = new Plot(100,10,150,100,Color.cyan);
Plot plot2 = new Plot(300,10,150,100,Color.red);
frame.add(plot1);
frame.add(plot2);
frame.setVisible(true);
}
}
我希望两个矩形都出现,但是只会刷新出现后面生成的矩形对象,要如何修改呢?
你好,要解决你的问题,你需要将绘制的多个矩形对象添加到一个容器中,然后将容器添加到JFrame中,而不是直接将多个矩形对象添加到JFrame中。
这里可以使用JPanel来作为容器,将绘制矩形的类Plot添加到JPanel中,并将多个JPanel添加到JFrame中。
修改代码如下:
arduino
import javax.swing.;
import java.awt.;
public class Plot extends JPanel {
private int x;
private int y;
private int width;
private int height;
private Color color;
private static final long serialVersionUID = 1L;
public Plot(int x, int y, int width, int height, Color color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
// 绘制方法
public void paint(Graphics g) {
super.paint(g);
g.setColor(color);
g.fillRect(x, y, width, height);
}
public static void main(String[] args) {
JFrame frame = new JFrame("窗口");
frame.setSize(800, 600);
JPanel panel = new JPanel(); // 容器
Plot plot1 = new Plot(100, 10, 150, 100, Color.cyan);
Plot plot2 = new Plot(300, 10, 150, 100, Color.red);
panel.add(plot1); // 将多个Plot对象添加到容器中
panel.add(plot2);
frame.add(panel); // 将容器添加到JFrame中
frame.setVisible(true);
}
}
这样就可以将多个矩形对象都显示出来了。