iT邦幫忙

0

JAVA SWING 多個按鈕執行問題

小弟想要針對fromA的176個按鈕,點選每個按鈕都能跳出fromB,fromB的按鈕按下會修改fromA剛剛按下的按鈕圖片,小弟按 1 按鈕,成功改變圖示,小弟接著按 2 按紐,雖然成功改變,但他會執行 1 和 2 的按鈕改變,小弟想要一個鈕只做一次,不要每多按一個就多執行一次要如何改呢?

public static class MyActionListener implements ActionListener { //座位擺設按鈕事件

    public void actionPerformed(ActionEvent e) {
	    
        String get = e.getActionCommand();
        int getint = Integer.parseInt(get);
        System.out.println(get);
    	b1[getint].setIcon(buttoning);//按鈕設定中圖示
    	frame.setEnabled(false);//將使用者可用的基本菜單禁用,使得無法點擊
 	    frames.setVisible(true);
	    frames.addWindowListener(new WindowAdapter() //設定選單的取消事件
	    {
	        public void windowClosing(WindowEvent event) {
	     	 frame.setEnabled(true); 
	     	 b1[getint].setIcon(floor);
	     }});
	    c1[0].addActionListener(new ActionListener() //設定為座位的按鈕事件
	    {
	        public void actionPerformed(ActionEvent e) {
	        	frame.setAlwaysOnTop(false);
	        	System.out.println(get);
	     int n = JOptionPane.showConfirmDialog(null, "確定設定為餐桌", "設定確認",JOptionPane.YES_NO_OPTION); //返回值為0或1
	          if(n==0){
	           frame.setAlwaysOnTop(true);
	           frames.setVisible(false);
	           frame.setEnabled(true);
	          b1[getint].setIcon(table);
	                  }
	     }});
	    c1[1].addActionListener(new ActionListener() //設定為取消的按鈕事件
	    {
	        public void actionPerformed(ActionEvent e) {
	           frames.setVisible(false);
	           frame.setEnabled(true);
	          b1[getint].setIcon(floor);
	     }});
                        
 	    }

    
    }
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2019-12-13 10:16:23

你的程式中
b1 有用getActionCommand取得目前按的是那一個按鈕
而 c1 則是加上這次按的 b1 的按鈕的處理事件
造成
按1號按鈕->c1 就加處理 b1[1] 事件
按2號按鈕->c1 就加處理 b1[2] 事件
按3號按鈕->c1 就加處理 b1[3] 事件
自然在處理 c1 事件時
會作用在 b1[1],b1[2],b1[3] 身上

修改方法是
1.加上這次按的 b1 的按鈕的處理事件每點按鈕做一次改成從頭到尾只做一次
把下面這段搬到 MyActionListener 的外面去

c1[0].addActionListener(new ActionListener() //設定為座位的按鈕事件
	    {
	        public void actionPerformed(ActionEvent e) {
	        	frame.setAlwaysOnTop(false);
	        	System.out.println(get);
	     int n = JOptionPane.showConfirmDialog(null, "確定設定為餐桌", "設定確認",JOptionPane.YES_NO_OPTION); //返回值為0或1
	          if(n==0){
	           frame.setAlwaysOnTop(true);
	           frames.setVisible(false);
	           frame.setEnabled(true);
	          b1[getint].setIcon(table);
	                  }
	     }});
	    c1[1].addActionListener(new ActionListener() //設定為取消的按鈕事件
	    {
	        public void actionPerformed(ActionEvent e) {
	           frames.setVisible(false);
	           frame.setEnabled(true);
	          b1[getint].setIcon(floor);
	     }});
                        
 	    }

2.原先 int getint = Integer.parseInt(get);
要負責把 getint 「傳給上面的 c1 那段程式碼」
3.c1 那段程式碼
原先的 b1[getint].setIcon(table);
改由步驟 2 傳過來的 getint

選我最佳解答

我要發表回答

立即登入回答