[英]How to check if any button in JPanel is clicked by a user
我一直在做巴士預訂項目,並且已經在預訂頁面。
JPanel
名為PanelSeat
,它的內部包含按鈕(大約36個按鈕)。
我想檢查是否單擊了JPanel
任何按鈕,然后禁用該按鈕,最后,如果用戶單擊util 3按鈕,它將停止,或者用戶無法再單擊它。
這是我到目前為止編寫的代碼:
private void CountTicket() {
try {
int count = 3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
if (((JButton) components[i]).isSelected()) { // I wanna check if any button is clicked by a user
if (JOptionPane.showConfirmDialog(this, "Seat Confirmation") == JOptionPane.YES_OPTION) { // confirm message
((JButton) components[i]).setEnabled(false); // disable the button
count--;
System.out.println("Your ramaining seat : " + count);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
如何檢查按鈕是否被單擊?
由於您想計算按鈕被按下的次數,然后在涉及到計數的情況下將其禁用,因此建議您包裝Jbutton類以使執行這些任務更容易, 因此此解決方案通常更好
class JbuttonWrapper extends JButton {
int count=0;
public void increment()
{
count++;
if (count==numberOfclicksToDisable)
{
this.setEnabled(false);
}
}
}
//then you can simply do the following.
JbuttonWrapper [] buttons= new JbuttonWrapper [NumbersOfButtonsYouHave];
for (int i=0; i<=NumbersOfButtonsYouHave;i++)
{
buttons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttons[i].increment(); } });
}
這個解決方案是基於你的代碼
static int count=3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
{
components[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count--;
}
});
}
將ActionListener添加到JButton
,請在此處查看示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.