【问题标题】:Drawing graphics with paintComponent with color as parameter以颜色为参数使用paintComponent绘制图形
【发布时间】:2016-10-13 08:20:14
【问题描述】:

我必须多次绘制两个圆圈,每次都使用不同的颜色。所以我想将颜色作为参数传递给 paintComponent 方法。但如果我这样做,超类 JPanel 的方法将不会被覆盖。我该怎么办?这是我的代码:

public class Test extends JPanel{

    Ellipse2D oval;

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;

        oval = new Ellipse2D.Double(137, 0, 40, 40);
        g2.setPaint(Color.black);    //color I want to pass as argument
        g2.fill(oval);

        oval = new Ellipse2D.Double(420, 0, 40, 40);
        g2.setPaint(Color.red);    //color I want to pass as argument
        g2.fill(oval);
    }
}

我想在调用构造函数时传递颜色:

public class MyFrame extends JFrame {
    Test t1, t2;

    public MyFrame(){
        //setSize, setTitle...

        t1 = new Test();  // would pass the colors in here
        t2 = new Test();  // would pass the colors in here

        add(t1);
        add(t2);
        setVisible(true);
    }
}

【问题讨论】:

  • 如何将两种颜色作为变量存储在测试中。然后通过构造函数来设置颜色。
  • 顺便说一句,您可能希望保存 Graphics 对象的初始颜色,然后将其更改为您想要的颜色,最后在完成后将其重置。只是一个习惯,我不必对绘制的颜色感到惊讶

标签: java swing graphics colors paintcomponent


【解决方案1】:

在构造函数中传递颜色并将它们保存在类成员变量中。然后重写paint组件以使用这些颜色来绘制你的圆圈

所以在 Test 类中添加这段代码

private java.awt.Color insideColor;
private java.awt. Color outsideColor;

public class Test (java.awt.Color inside, java.awt.Color outside){
    this.insideColor = inside;
    this.outsideColor = outside; 
}

【讨论】:

    猜你喜欢
    • 2019-03-23
    • 2021-09-28
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多