我想要一個帶有按鈕的JFrame,當我點擊它時,球會出現在左上角。然後,如果我再次點擊它,x,y位置會發生變化,並且會移動。問題是我似乎無法讓球在JFrame上出現後,我點擊按鈕。只有按鈕出現。Java Paint和JButton
我的源代碼:
package prac;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Prac extends JComponent {
private int x = 0;
private int y = 0;
private void moveBall() {
x = x + 1;
y = y + 1;
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 50, 50);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Sample Frame");
JPanel buttonPanel = new JPanel();
JButton moves = new JButton("Click to move ball");
Prac game = new Prac();
buttonPanel.add(moves);
frame.setSize(500, 500);
frame.add(game);
frame.add(buttonPanel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
moves.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent action) {
game.moveBall();
game.repaint();
}
});
}
}
感謝
謝謝,Gosu。 ^。^ – Denominator
@Denominator沒問題:) – Gosu