我想沿着x轴向右或向左移动一个球,具体取决于用户点击的JButton。单击任一JButton时,球不会移动。
我已经使用System.out.println()来尝试找出错误,并且程序正在检测JButtons上的点击并更改必须更改的变量(int horizontal)以移动球。
MoveBallPanel类:
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MoveBallPanel extends JPanel implements ActionListener {
// declarations
private JButton moveLeft;
private JButton moveRight;
private int center;
private int horizontal;
public MoveBallPanel() {
// make elements
moveLeft = new JButton("To the left");
moveLeft.addActionListener(this);
moveRight = new JButton("To the right");
moveRight.addActionListener(this);
// add to panel
add(moveLeft);
add(moveRight);
}
// to do when JButton is clicked
@Override
public void actionPerformed(ActionEvent e) {
final int MOVE = 50;
if (e.getSource() == moveLeft) {
horizontal -= MOVE;
// System.out.println("moveLeft JButton has been clicked");
// System.out.println(horizontal);
} else {
horizontal += MOVE;
// System.out.println("moveRight button has been clicked");
// System.out.println(horizontal);
}
repaint();
}
// draw ball
@Override
public void paintComponent(Graphics g) {
final int DIAMETER = 100;
final int VERTICAL = (getHeight() / 2) - (DIAMETER / 2);
center = getWidth() / 2;
horizontal = center - DIAMETER / 2;
super.paintComponents(g);
g.setColor(Color.ORANGE);
g.fillOval(horizontal, VERTICAL, DIAMETER, DIAMETER);
g.setColor(Color.BLACK);
g.drawOval(horizontal, VERTICAL, DIAMETER, DIAMETER);
g.drawOval(horizontal + DIAMETER / 4, VERTICAL, DIAMETER / 2, DIAMETER);
}
}
MoveBall类:
package test;
import javax.swing.*;
public class MoveBall extends JFrame {
public MoveBall() {
// JFrame object
JFrame frame = new JFrame();
// JFrame properties
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Move ball");
frame.add(new MoveBallPanel());
frame.setVisible(true);
}
public static void main(String[] args) {
new MoveBall();
}
}
答案 0 :(得分:3)
看看你的两段代码......
@Override
public void actionPerformed(ActionEvent e) {
final int MOVE = 50;
if (e.getSource() == moveLeft) {
horizontal -= MOVE;
} else {
horizontal += MOVE;
}
repaint();
}
在actionPerformed
方法中,您正在更新horizontal
值,这听起来很合理,但在您的paintComponent
方法中,您正在使用其他内容重新分配值,从而覆盖{ {1}}方法确实......
actionPerformed
首先看一下Performing Custom Painting和Painting in AWT and Swing,了解绘画如何在Swing中发挥作用。
你需要做的是创建某种标志,可用于告诉public void paintComponent(Graphics g) {
//...
horizontal = center - DIAMETER / 2;
//...
}
方法将paintComponent
初始化为默认位置,然后让程序更新那里...