代码之家  ›  专栏  ›  技术社区  ›  John Smith

如何将鼠标单击的标签中的值引用到actionperformed。(Java、NetBeans)

  •  0
  • John Smith  · 技术社区  · 8 年前

    https://imgur.com/a/26VvY

    所以我一直在尝试用java编程这个老虎机游戏,最近我在尝试解决这个问题的方法上遇到了问题。该游戏的工作原理如下:每次单击名为x1的标签,您就可以投资1个比特币,并且有更高的机会赢取1个比特币。单击标签x3,您获得中等获胜机会(您赢得3枚比特币),如果单击标签x5,您获得5枚比特币的最低获胜机会。1单击这些标签可启用按钮“GO WIN!”,稍后您必须单击它才能运行所有内容。目前,我不反对通过编程让你在一定的机会内只赢得1枚比特币,尽管其他两种标签是问题所在。有什么建议吗?

    我知道jframe看起来很糟糕,但这只是我的练习:)

    迄今为止的代码:

       // TODO add your handling code here:
        btnWinLose.setEnabled(false);
        int slot1 = (int)(4*Math.random()+0);
        int slot2 = (int)(4*Math.random()+0); 
        int slot3 = (int)(4*Math.random()+0);
    
        lbl_1.setText(String.valueOf(slot1));
        lbl_2.setText(String.valueOf(slot2));
        lbl_3.setText(String.valueOf(slot3));
    
        if(slot1 == slot2 ){
            start = start +1;
            lbl_Coin.setText(start + " COINS");
        }
        else{
        start = start - 1;
        lbl_Coin.setText(start + " COINS");
        }
        if(start == 0){
            int n = JOptionPane.showConfirmDialog(
                    this, 
                    "No coins left, start again?"+  
                    JOptionPane.YES_NO_OPTION);
         if(n == 0){
             start=10;
             lbl_Coin.setText(String.valueOf(start + " COINS"));
    
         }
         else{
             System.exit(0);
         }
        }   
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   TM00    8 年前

    确定单击了哪个标签的一种方法是使用 MouseListener 在每个标签上。看见 this question 作为参考。因此,让您的GUI类实现 鼠标定位器 并执行以下操作:

    public class myGUI extends JFrame implements ActionListener, MouseListener{
    
     private JLabel x1,x2,x3;
    
     public myGUI(){
       // do constructor stuff
       x1 = new JLabel("x1");
       x2 = new JLabel("x2");
       x3 = new JLabel("x3");
    
      x1.addMouseListener(this);
      x2.addMouseListener(this);
      x3.addMouseListener(this);
    
     }
    
      // other methods
    
      @Override
      public void mouseClicked(MouseEvent e) {
            if(e.getSource().equals(x1)){
              // do x1 stuff
            }
            else if(e.getSource().equals(x2)){
              // do x2 stuff
            }
            else if(e.getSource().equals(x3)){
              // do x3 stuff
            }
    
      }
    
    }