나는 사각형을 그려서 화면을 가로 질러 움직이는 paint
방법을 가지고 있습니다. 사각형을 화면 밖으로 옮길 때 화면에서 벗어나기를 원합니다. JFrame의 시작 부분으로 돌아갑니다. 나는 그것이 if(rectangle.isoffthescreen){ put it back on the screen }
과 같을 것이라고 추측하지만 나는 그것을 어떻게하는지 모른다. 또한, 직사각형에 대해 JFrame frame = new JFrame();
과 같은 것을 할 수 있는지 알고 싶지만 사각형에 대해서는 분명합니다. 혼란스러워서 미안해. 지금까지Graphics2D의 무언가가 프레임에서 벗어나는 지 확인하는 방법
public class main extends JPanel {
public static int place = -350;
public Rectangle rect;
public int xDelta;
public main() {
rect = new Rectangle(0, 75, 50, 50);
xDelta = 4;
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
rect.x += xDelta;
if (rect.x + rect.width > getWidth() - 1) {
rect.x = getWidth() - rect.width;
xDelta *= -1;
} else if (rect.x < 0) {
rect.x = 0;
xDelta *= -1;
}
repaint();
}
});
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g.create();
Random r = new Random();
int r1;
r1 = r.nextInt(5);
if (r1 == 0) {
g2d.setColor(Color.WHITE);
} else if (r1 == 1) {
g2d.setColor(Color.BLUE);
} else if (r1 == 2) {
g2d.setColor(Color.RED);
} else if (r1 == 3) {
g2d.setColor(Color.GREEN);
} else if (r1 == 4) {
g2d.setColor(Color.PINK);
} else {
g2d.setColor(Color.CYAN);
}
place += 50;
rect = new Rectangle(place, 100, 300, 200);
g2d.draw(rect);
g2d.fill(rect);
g2d.dispose();
try {
Thread.sleep(400);
} catch (Exception e) {
}
repaint();
}
}
및
public class frame {
public static JFrame frame;
public static void main(String args[]){
frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
main m = new main();
m.setBackground(Color.BLACK);
frame.add(m);
}
}
에서 나는 내가 여전히 동작하지 않습니다 수있는 다음
@MadProgrammer이다.
를 기반으로 업데이트되었습니다. '페인트 '를 사용하는 것은 나쁜 일입니다. –
if 문에서 사각형을 뒤로 이동시키기 위해 실제로 무엇을 넣어야합니까? –
@DilanHanrahan 최상위 컨테이너에는'paintComponent' 메소드가 없기 때문입니다. 최상위 컨테이너도 이중 버퍼링되지 않습니다. 또한 예제를 보았습니까? – MadProgrammer