我有一个代码:这是我需要一个项目具有红色,蓝色值的矩阵。我需要单击某个按钮,然后单击邻居,它们的值应该交换(红色为键1,蓝色为键2),依此类推。我想我应该以某种方式通过线程创建它(抱歉,不准确),但是据我所知,应该单击一个按钮(启动新线程),单击第二个按钮(线程停止,进行交换)并更改值。
我了解,我的问题可以是一些“教程”或基本知识,但这对我来说很复杂,我很长一段时间都找不到答案。谢谢您的任何建议或示例。
public class ButtonsMatrix extends JButton {
private int[][] fModel;
private int fX;
private int fY;
public ButtonsMatrix( int x, int y, int[][] model) {
fX= x;
fY= y;
fModel= model;
/*addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Update();
}
});*/
updateNameFromModel();
}
private void updateNameFromModel() {
fModel[fX][fY] = (int)(Math.random()*2);
setText(String.valueOf(fModel[fX][fY]));
if(fModel[fX][fY] == 1){
setText("Red");
} else {
setText("Blue");
}
}
public static void main(String[] args) {
int dim=7;
int matrix[][] = new int[7][7];
JFrame f = new JFrame("Window containing a matrix");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
JPanel extra = new JPanel(new CardLayout(290,300));
TextField tf = new TextField();
tf.setBounds(800,20,20,20);
f.add(tf);
p.setLayout(new GridLayout(dim, dim));
for( int r = 0; r < dim; r++){
for( int c = 0; c < dim; c++){
ButtonsMatrix button= new ButtonsMatrix(r, c, matrix);
p.add(button);
}
}
extra.add(p);
f.setLocation(350, 100);
f.add(extra);
f.pack();
f.setVisible(true);
}
}
最佳答案
不需要每个按钮都了解其他任何按钮。
只需创建按钮矩阵,然后向每个按钮添加一个ActionListener即可。第一次单击时,只需保存该按钮参考即可。下次单击时,将两个按钮的信息互换并将已保存的ID设置为null。大纲:
public class MyClass {
private JButton clicked = null;
public void main( String[] args ) {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource();
if ( clicked == null ) {
clicked = b;
} else {
if ( b != clicked) {
// swap info between b and clicked
}
clicked = null;
}
}
};
// create matrix here, adding the above listener to each button.
...
}
}