【问题标题】:Java Swing app - Arraylist with circleobjects, how to draw them in a Jpanel inside a jframe?Java Swing 应用程序 - 带有圆形对象的 Arraylist,如何在 jframe 内的 Jpanel 中绘制它们?
【发布时间】:2016-01-05 15:07:59
【问题描述】:

我正在制作一个简单的应用程序,它允许您显示不同的圆形对象,通过按钮浏览它们。

问题是我不知道如何将我的 circleobjects 打印到 jPanel 中。 当您第一次运行程序时,第一个 circleobject 应该出现在 jPanel 中。这是我的circleclass:

public class Circle {
private int height;
private int width;
private Color color;


public Circle (int height, int width, Color color){
this.height = height;
this.width = height;
this.color = color;
}
public int getHeight() {
    return height;
}
public void setHeight(int height) {
    this.height = height;
}
public Color getColor() {
    return color;
}
public void setColor(Color color) {
    this.color = color;
}
public int getWidth() {
    return width;
}
public void setWidth(int width) {
    this.width = width;
}
}

这是 GUI 代码的第一部分。我在数组列表中创建了 5 个圆形对象。

public class CircleGUI extends javax.swing.JFrame{

public ArrayList<Circle> circles = new ArrayList<Circle>();

public CircleGUI(){
    initComponents();
    circles.add(new Circle(15, 15, Color.blue));
    circles.add(new Circle(20, 15, Color.black));
    circles.add(new Circle(30, 10, Color.green));
    circles.add(new Circle(20, 10, Color.orange));
    circles.add(new Circle(35, 35, Color.red));     
    }

现在,我如何让我的第一个对象出现在屏幕截图上标记的 jPanel 中?

【问题讨论】:

    标签: java swing arraylist


    【解决方案1】:

    您必须覆盖 JPanel 的 paintComponent(Graphics) 方法。

    然后根据当前 Circle 对象包含的数据在 Graphics 对象上进行绘图。

    【讨论】:

    • 在代码的什么地方添加paintcomponent方法?
    • 创建一个扩展 JPanel 的新类,在那里覆盖paintComponent,并使用此类的实例而不是您的 JPanel。
    • 我创建了一个名为 draw 的新类,扩展了 jPanel,带有@override,然后我有了: public void paintComponent(Graphics.g){ super.paintComponent(g);现在,我已经尝试了从 jPanel.getGraphics 到 jPanel.paintComponent 的所有方法,但我无法弄清楚。
    【解决方案2】:

    查看Custom Painting Approaches。它完全符合您的要求(除了绘制矩形)。

    它实际上展示了两种方法:

    1. 从 ArrayList 绘制对象(这是您想要的)
    2. 在 BufferedImage 上绘制对象

    在你的情况下的基本绘画代码是:

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
    
        //  Custom code to paint all the Rectangles from the List
    
        for (DrawingArea.ColoredRectangle cr : coloredRectangles)
        {
            g.setColor( cr.getForeground() );
            Rectangle r = cr.getRectangle();
            g.drawRect(r.x, r.y, r.width, r.height);
        }
    }
    

    当然你会画椭圆并使用你的 Circle 类

    【讨论】:

    • 我应该在新班级里这样做吗?另外,drawingArea是我的jpanel,ColoredRectangle是类?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多