【发布时间】:2017-08-27 13:04:03
【问题描述】:
我想计算从 10 x 10 JButton 网格中被点击的 JButton 的数量。
无论如何,我不知道如何计算点击了多少 JButton。我想过制作 100 个 JButton,但这似乎很愚蠢。
还有如何防止超过 14 个按钮被点击?
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
button.setEnabled( false );
}
};
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
button.addActionListener( al );
panel_1.add(button);
}
}
这是我的 forLoops,用于制作 100 个按钮并为每个按钮提供一个 actionListener,因此当单击 JButton 时,它变得不可单击。
ActionListener al = new ActionListener()
{
int clicked = 0;
public void actionPerformed(ActionEvent e)
{
button = (JButton)e.getSource();
if(clicked != 14)
{
clicked++;
}
else
button = (JButton)e.getSource();
button.setEnabled( false );
}
};
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
button.addActionListener( al );
panel_1.add(button);
}
}
我试过设置一个柜台,但显然不正确。我什至可以将 e.getSource() 与 int 或其他东西进行比较吗?
【问题讨论】:
-
你可以使用根据GUI增加的静态int
-
为什么不只存储每个按钮的状态?
-
@ΦXocę웃Пepeúpaツ 你的意思是像一个int计数器?我如何将 (JButton).e.getSource() 与 int 计数器进行比较?
-
@gooroo7 你是什么意思存储状态?按钮是否被按下?我不明白你的意思
-
不像counter那么简单,但是思路是类似的,每次设置一个按钮时增加全局计数器,设置一个按钮时减少计数器...并且您需要检查计数器是否永远不会超过 14..
标签: java user-interface jbutton