I'm writing a program which will draw a line, then copy it, rotate it around 90 degrees, and do the same with the whole picture over and over again. My problem is, that the JFrame I'm using sometimes wont draw the first line and, instead, make the complete Frame white. I can't find a reason for this, sometimes it workes, sometimes it wont, it's completely random. Maybe I didn't really get how the paint() method works. Here's the part of my code that doesn't work:

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

public class WeirdThing extends JFrame {
static final int winWidth = 800;
static final int winHeight = 600;
boolean start;

public WeirdThing() {
    super("WeirdThing");
    start = true;
}

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    if (start) {
        g2.setColor(Color.BLACK);
        g2.drawLine(winWidth / 2, winHeight / 2, winWidth / 2 + 5, winHeight / 2);
        start = false;
    }
    repaint();
}

public static void main(String[] args) {
    WeirdThing a = new WeirdThing();
    a.setDefaultCloseOperation(EXIT_ON_CLOSE);
    a.setSize(winWidth, winHeight);
    a.setVisible(true);
}

}

And here are pictures of the two results I get: Wanted Result | Result I don't want

有帮助吗?

解决方案

You've created a a cyclic dependency between the paint and repaint methods which is preventing Swing from updating the UI - remove the repaint method


Custom painting in Swing is done by overriding paintComponent rather than paint. Remember to invoke super.paintComponent(g).

其他提示

Never use repaint() in paint() method, becouse repaint() call paint(). Try this code:

public void paint(Graphics g) {
   Graphics2D g2 = (Graphics2D) g;
   System.out.println(start);
   if (start) {
       g2.setColor(Color.BLACK);
       g2.drawLine(winWidth / 2, winHeight / 2, winWidth / 2 + 5, winHeight / 2);

       start = false;
   } else {
       g2.drawLine(100, 100, 200, 200);
   }

   //    repaint();
}

You can see life cycle of start variable. I think you just need something like that:

public void paint(Graphics g) {
    super.paintComponents(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.BLACK);
    g2.drawLine(winWidth / 2, winHeight / 2, winWidth / 2 + 5, winHeight / 2);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top