所以,我有類Square的多個對象,它是JButton的子類。我有一個班級委員會的實例,其中包含Square的幾個實例。我想要做的是當我按下其中一個按鈕(正方形)時,在其上繪製一個形狀(一個圓形)。爲此,我在Square類中有一個布爾變量,即isClicked,它基本上決定了paintComponent方法中必須繪製的內容。在多個JButton上繪圖
問題是,當我有幾個按鈕時,按鈕開始表現得很怪異。令人驚訝的是,如果只有其中一個,那完全沒有問題。起初,我認爲這個問題可能與線程有關,但是,我把主代碼放到了invokeLater方法中,並且根本沒有任何幫助。
我看到了一個使用BufferedImage的解決方案,但我想看看是否有任何可能性來解決這個問題。
對不起,可能不完美的英語。
Square類:
public class Square extends JButton implements ActionListener {
private int number;
private boolean isClicked;
public Square(int x) {
number = x;
isClicked = false;
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (!isClicked) {
super.paintComponent(g);
} else {
System.out.println("EXECUTED for: " + number);
g2d.drawOval(this.getX(), this.getY(), 100, 100);
}
}
@Override
public void actionPerformed(ActionEvent e) {
isClicked = !isClicked;
System.out.println(isClicked + " " + number);
repaint();
}
}
板類:
public class Board extends JPanel {
private static final int BOARD_WIDTH = (int) (TicTacToe.WIDTH * 0.7);
private static final int VERTICAL_LINE_LENGTH = (int) (TicTacToe.WIDTH * 0.5);
private static final int HORIZONTAL_LINE_LENGTH = (int) (TicTacToe.HEIGHT * 0.8);
private static final int STROKE_WIDTH = 5;
private Square[] squares;
public Board() {
}
public void addButtons() {
squares = new Square[9];
for (int i = 0; i < 3; i++) {
Square square = new Square(i);
square.setPreferredSize(new Dimension(30, 30));
square.addActionListener(square);
this.add(square);
squares[i] = square;
((GridLayout)this.getLayout()).setHgap(30);
((GridLayout)this.getLayout()).setVgap(30);
}
}
public Square[] getButtons() {
return squares;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(STROKE_WIDTH));
// Horiztontal lines
g2d.drawLine(0, TicTacToe.HEIGHT/3,
BOARD_WIDTH, TicTacToe.HEIGHT/3);
g2d.drawLine(0, 2 * TicTacToe.HEIGHT/3,
BOARD_WIDTH, 2 * TicTacToe.HEIGHT/3);
// Vertical lines
g2d.drawLine(BOARD_WIDTH/3, 0, BOARD_WIDTH/3,
TicTacToe.HEIGHT);
g2d.drawLine(2 * BOARD_WIDTH/3, 0, 2 * BOARD_WIDTH/3,
TicTacToe.HEIGHT);
}
}
主要方法:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Board board = new Board();
board.setPreferredSize(new Dimension((int) (WIDTH * 0.7), HEIGHT));
board.setLayout(new GridLayout(3, 3));
board.addButtons();
GameOptions opt = new GameOptions();
opt.setPreferredSize(new Dimension((int) (WIDTH * 0.3), HEIGHT));
JFrame frame = new JFrame("Tic Tac Toe");
frame.setLayout(new FlowLayout());
frame.add(board);
frame.add(opt);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
所以你基本上只是說我應該創建ImageIcon並將它傳遞給一個按鈕?這聽起來太簡單了......:D – Mantas
@Mantas:我編輯了代碼來向你展示我的意思。 –