gpt4 book ai didi

JAVA移动球

转载 作者:行者123 更新时间:2023-12-01 17:32:20 25 4
gpt4 key购买 nike

我尝试编写一个程序,让屏幕上的球会自行移动。但问题是它不执行 repaint();

有什么解决办法吗?

(主类)Main.java:

import javax.swing.*;
import java.awt.*;

public class Main extends JFrame{
static int x = 10;


public static void main(String[] args){
JFrame f = new JFrame("title");
f.setVisible(true);
f.setSize(300,250);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sekon m = new sekon();
f.add(m);

antr t = new antr();
Thread th = new Thread(t);
th.start();
}
}

(第二课)sekon.java:

import javax.swing.*;
import java.awt.*;

public class sekon extends JPanel{
int xiu = 10;

public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(xiu, 10, 20, 20);

}


public void changeX(int b){
this.xiu = b;
}



}

class antr extends JPanel implements Runnable{
int xi = 10;
sekon s = new sekon();
public void run(){

xi += 1;
s.changeX(xi);
JPanel p = new JPanel();
p.repaint();

try{
Thread.sleep(5);
}catch(Exception e){}
}
}

最佳答案

1) 代码中的 repaint() 被代码行 Thread.sleep(5);

阻止

2)您的代码不起作用,因为错过了...,在屏幕上移动 Oval 的所有坐标

3) 对于 Swing 容器,仅使用 Swing JComponent Swing Timer用于处理、移动、重新喷漆,

使用Runnable#Thread当然可以,但不是这样,

关于Swing Timer的示例

    import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AnimationJPanel extends JPanel {

private static final long serialVersionUID = 1L;
private int cx = 0;
private int cy = 150;
private int cw = 20;
private int ch = 20;
private int xinc = 1;
private int yinc = 1;

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
AnimationJPanel panel = new AnimationJPanel();
panel.setPreferredSize(new Dimension(400, 300));
panel.animate();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public AnimationJPanel() {
setLayout(new BorderLayout());
JLabel label = new JLabel("This is an AnimationJPanel");
label.setForeground(Color.RED);
label.setHorizontalAlignment(SwingConstants.CENTER);
add(label);
setBackground(Color.BLACK);
setForeground(Color.RED);
setOpaque(true);
}

public void animate() {
new Timer(15, new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
Rectangle oldCircle = new Rectangle(cx - 1, cy - 1, cw + 2, ch + 2);
cx += xinc;
cy += yinc;
if (cx >= getWidth() - cw || cx <= 0) {
xinc *= -1;
}
if (cy >= getHeight() - ch || cy <= 0) {
yinc *= -1;
}
repaint(oldCircle);
repaint(cx - 1, cy - 1, cw + 2, ch + 2);
}
}).start();
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(cx, cy, cw, ch);
}
}

关于JAVA移动球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9760944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com