将矩形添加到JPanel

问题描述

因此,基本上,我正在尝试向JPanel添加一些矩形。此特定的Rectangle也具有更改可见性和颜色的方法。但是当添加这些矩形时,什么也没发生。

这是矩形的课程:

import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;

public class Rectangle extends JPanel {

    private int x;
    private int y;

    private static int Width = 30;
    private static int Height = 30;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(new java.awt.Color(0,102,0));
        g.drawRect(x,y,Width,Height);
    }

    public Rectangle(int x,int y) {
        this.x = x;
        this.y = y;
    }

    public void changeColor() {
        setBackground(new java.awt.Color(0,0));
        repaint();
    }

    public void changeVisibility() {
        setVisible(false);
    }
}

这是将Recangles添加到Frame类中的JPanel的方法

 public void placeRectangle(int x,int y) {
     Rectangle newRect = new Rectangle(x,y);
     panel.add(newRasenblock);
     newRect.setVisible(true);
 }

我之前已经使用矩形(没有changeColorchangeVisibility)对这种方法进行了测试,并在那里工作,但是在这里使用类似的代码却突然没有了。

解决方法

这是添加到JFrame的简单示例。除非您计划制作更多图形,否则您实际上不需要重写paintComponent。

注意:此处未使用x和y。我建议您依靠布局管理器来定位矩形,而不是绝对定位。

我不了解JPanel提供什么子类,而不是仅使用JPanel本身?

public class RectangleDemo {
    
    JFrame f = new JFrame();
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new RectangleDemo().start());
    }
    
    public void start() {
        f.setPreferredSize(new Dimension(400,400));
        f.pack();
        f.setLayout(new FlowLayout());
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        placeRectangle(10,10);
    }
    
    public void placeRectangle(int x,int y) {
        Rectangle newRect = new Rectangle(x,y);
        f.add(newRect);
        
        newRect.setVisible(true);
        f.repaint();
    }
}

class Rectangle extends JPanel {
    
    private int x;
    private int y;
    
    private static int Width = 100;
    private static int Height = 100;
    
    
    public Dimension getPreferredSize() {
        return new Dimension(Width,Height);
    }
    public Rectangle(int x,int y) {
        this.x = x;
        this.y = y;
        setPreferredSize(getPreferredSize());
        changeColor();
    }
    
    public void changeColor() {
        setBackground(Color.WHITE);
        setBorder(new LineBorder(new Color(0,102,0),2));
        repaint();
    }
    
    public void changeVisibility() {
        setVisible(false);
    }
}