我将按钮变为黑色并打印Hello以确保它何时有效。什么都没有被打印,甚至颜色不会改变,但没有错误。
我需要的3个课程以下任何帮助表示赞赏。我是Java swing的新手,欢迎任何提示。
按钮类
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class RedSpace implements Space, ActionListener {
private int x;
private boolean isPressed;
private int y;
private JButton button;
public RedSpace(int x, int y){
button = new JButton();
button.setBackground(Color.RED);
this.x = x;
this.y = y;
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public JButton getButton() {
return button;
}
@Override
public boolean getIsPressed() {
return isPressed;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(button)) {
System.out.println("Hello");
isPressed = true;
button.setBackground(Color.BLACK);
}
}
空间接口
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JToggleButton;
public interface Space extends ActionListener {
int x = 0;
int y = 0;
JButton button = new JButton();
boolean isPressed = false;
int getX();
int getY();
JButton getButton();
boolean getIsPressed();
}
董事会成员
public class Board {
private static int x;
private static int y;
private static JFrame frame;
private static JPanel pane;
static ArrayList<ArrayList<Space>> buttons = new ArrayList<ArrayList<Space>>();
static ArrayList<Space> buttonsRow;
public Board(int x, int y){
this.x = x;
this.y = y;
}
public static void printBoard(){
frame = new JFrame();
frame.setTitle("GameBoard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new CardLayout());
pane = new JPanel();
pane.setLayout(new GridLayout(8,8));
frame.add(pane);
for(int i = 0; i < x;i++){
buttonsRow = new ArrayList<Space>();
for(int ii = 0; ii<y;ii++){
if(i == 0 && ((ii-1)%2 != 0))
buttonsRow.add(new BlueSpace(i,ii));
else if(i == 1 && ((ii-1)%2 == 0))
buttonsRow.add(new BlueSpace(i,ii));
else if(i == 6 && ((ii-1)%2 != 0))
buttonsRow.add(new RedSpace(i,ii));
else if(i == 7 && ((ii-1)%2 == 0))
buttonsRow.add(new RedSpace(i,ii));
else buttonsRow.add(new WhiteSpace(i,ii));
pane.add(buttonsRow.get(ii).getButton());
}
buttons.add(buttonsRow);
}
frame.setSize(new Dimension(900,900));
pane.setSize(new Dimension(900,900));
frame.setVisible(true);
}
}
答案 0 :(得分:3)
没有任何内容正在打印或更改颜色没有错误。
您需要将ActionListener
添加到按钮。
button = new JButton();
button.addActionListener( this );