简体   繁体   中英

setColor in JFrame does not work

My problem is the following. I have a touch sensor and want to draw with it on the display. It gives me three values: x coordinate, y coordinate and force of the press. My application works so far that it draws an oval (or better said several ovals appearing as lines) and this oval is different big according to the force. But I want different color according to the force.

So here is my code. The line setting the Color to orange has currently no effect. I would like the commented out part to work, too.

 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
}
}

Here is a link to the Swing tutorial . You should start by reading the section on Custom Painting .

To answer your question, I would guess the the getGraphics() method returns a new object every time you invoke the method. So your code should be:

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

Again, you should not be using this approach to do custom painting, but I wanted to mention the answer to the question because this is generally a better style for coding. That is don't invoke the same method multiple times. Instead invoke the method once and assign it to a variable. This way you know for sure that you are invoking methods on the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM