Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

java - How to work private void when using graphics?

So I've been trying to figure this out, and I'm not sure how... I've been working on this piece of code here:

public class Main extends JPanel {


public void paintComponent(Graphics g) {
    super.paintComponent(g);
    drawGrass(g);
    drawFlowers(g);
    
}

private void drawGrass(Graphics g) {
    super.paintComponent(g);

    Color brightGreen= new Color(60,176,31);
    g.setColor(brightGreen);
  
    g.setColor(brightGreen);
    g.fillRect(0,300,500,500); 
}

 private void drawFlowers(Graphics g) {
    super.paintComponent(g);
    Color pinkFlower = new Color(225,153,153);
    g.setColor(pinkFlower);
    g.fillRect(25,320,8,8);
    g.fillRect(320,380,8,8);
    g.fillRect(110,355,8,8);

}

I figured out that it will only draw the flowers because it overrides over the drawGrass. How would I make it so it doesn't override my other code?

question from:https://stackoverflow.com/questions/65890790/how-to-work-private-void-when-using-graphics

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Start simpler. If you only use one method, it should work fine.

public class Main extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // draw grass
        Color brightGreen= new Color(60,176,31);
        ...
        // draw flower
        Color pinkFlower = new Color(225,153,153);
        ...
    }

}

So if you want to extract the two colors and drawings into methods, you only need to copy those exact lines between the comments (you can even use your IDE features to "Extract Method"), not add another super.paintComponent(g) (which is what is clearing the panel)

Regarding the question title, private void isn't the issue or related to the solution, really.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...