【发布时间】:2017-06-13 21:06:35
【问题描述】:
所以情况是我正在制作一个充满 8*8 按钮的面板,就像一个矩阵,我将不得不根据单击按钮的位置更改特定的按钮文本。制作我自己的 JButton 似乎是个好主意,我可以在其中为按钮分配 x 和 y 索引,这样我就可以轻松检查索引单击了哪个按钮。 这是代码:
import javax.swing.JButton;
public class MatrixButton extends JButton {
private int x;
private int y;
public MatrixButton(int x, int y, String text){
super(text);
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
它确实解决了任务,但是这些矩阵按钮在我将鼠标悬停在它们上方之前不想出现。可能是什么问题?
这是包含这些按钮并处理它们的操作的面板的代码:
public class PlayField extends JPanel implements ActionListener {
private MatrixButton[][] button = new MatrixButton[8][8];
public PlayField(){
Random rand = new Random();
setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; ++i){
for (int j = 0; j < 8; ++j){
button[i][j] = new MatrixButton(j, i, "" + rand.nextInt(80));
button[i][j].addActionListener(this);
add(button[i][j]);
}
}
}
private String incrementText(MatrixButton mb){
return "" + (Integer.parseInt(mb.getText()) + 1);
}
@Override
public void actionPerformed(ActionEvent e){
MatrixButton mb = (MatrixButton)e.getSource();
for (int i = mb.getY(); i >= 0; --i){
button[i][mb.getX()].setText(incrementText(button[i][mb.getX()]));
}
for (int i = 0; i < 8; ++i){
if (i != mb.getX())
button[mb.getY()][i].setText(incrementText(button[mb.getY()][i]));
}
}
}
PS:如果我用普通的 JButtons 填充,它们会显示为应有的样子。这就是为什么我很困惑,因为我对 JButton 扩展没有太大的改变,只是增加了 2 个变量。
【问题讨论】: