JFrame中的setColor不起作用

时间:2013-06-21 00:01:58

标签: java swing drawing jframe

我的问题如下。我有一个触摸传感器,想要在显示器上绘制它。 它给了我三个值:x坐标,y坐标和印刷机的力。 我的应用程序到目前为止它绘制了一个椭圆形(或更好地表示几个椭圆形看起来像线条),这个椭圆形根据力量大不相同。但是根据力量,我想要不同的颜色。

所以这是我的代码。将“颜色”设置为橙色的线条目前无效。 我希望注释掉的部分也可以工作。

 import java.awt.Color;
 import java.awt.Dimension;
 import java.awt.Graphics;
 import javax.swing.JFrame;

public class GUI2 extends JFrame {

public GUI2() {
    this.setPreferredSize(new Dimension(1200, 1000));
    this.pack();
    this.setLocation(300, 50); // x, y
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

@Override
public void paint(Graphics g) {
    super.paint(g);
}

public void drawPoint (int x, int y, int force){
    int width = (force*2)/1000;
    /*
    if (force < 3000){
        this.getGraphics().setColor(Color.YELLOW);
    }
    else if (force < 6000){
        this.getGraphics().setColor(Color.ORANGE);
    }
    else if (force < 9000){
        this.getGraphics().setColor(Color.RED);
    }
    else {
        this.getGraphics().setColor(Color.BLUE);
    }
    */

        this.getGraphics().setColor(Color.ORANGE); // <- no effect
        System.out.println("COLOR: " + this.getGraphics().getColor().toString() );

    this.getGraphics().fillOval(x, y, width, width); // <- works
}
}

1 个答案:

答案 0 :(得分:2)

以下是Swing tutorial的链接。您应该首先阅读Custom Painting部分。

要回答你的问题,我猜想每次调用方法时,getGraphics()方法都会返回一个新对象。所以你的代码应该是:

Graphics g = getGraphics();
g.setColor(...);
g.drawOval(...);

同样,你不应该使用这种方法来进行自定义绘画,但我想提一下问题的答案,因为这通常是一种更好的编码风格。那就是不要多次调用同一个方法。而是调用方法一次并将其分配给变量。这样您就可以确定在同一个对象上调用方法。