首页 新闻 会员 周边

你好,在java中用Japanel绘图,之前生成的对象会被后面生成的覆盖,怎么解决呢?

0
悬赏园豆:20 [待解决问题]

代码如下:
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);

}

}

我希望两个矩形都出现,但是只会刷新出现后面生成的矩形对象,要如何修改呢?

mountain_city_boy的主页 mountain_city_boy | 初学一级 | 园豆:141
提问于:2023-03-31 16:20
< >
分享
所有回答(1)
0

你好,要解决你的问题,你需要将绘制的多个矩形对象添加到一个容器中,然后将容器添加到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);
}

}
这样就可以将多个矩形对象都显示出来了。

Technologyforgood | 园豆:5718 (大侠五级) | 2023-04-07 21:58
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册