java - 影院座位选择和取消选择在 JButton 中不起作用?

标签 java swing

当我执行这段代码时,它会显示一个按钮网格,其中只有位于网格底角的按钮有效,而其他按钮则无效。当你点击一个按钮时,它会变成绿色,意味着它被选中,如果你再次点击它,它会变成白色,意味着取消选择。我想制作一个电影院座位预订系统,用户可以在其中选择自己的座位。我不明白为什么其他人不工作。

谁能帮帮我?

    import javax.swing.*;
    import java.io.IOException;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Color;
    import javax.swing.border.LineBorder;
    import javax.swing.border.Border;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import java.io.File;
    class cinemaSeats extends JFrame implements ActionListener { 
    private JButton[] bt = new JButton[1]; 

    static int c=4;
    static int k=5;
      public cinemaSeats() throws IOException{ 
      this.setSize(100, 100); 


      this.setLayout(null); 
     for(int s=0;s<=10;s++,k+=30)
      {
       c=4;
         for(int j=1;j<=10;j++,c+=30)
           {
              for (int i = 0; i < bt.length; i++) { 
              bt[i] = new JButton(""); 
              this.add(bt[i]); 

              bt[i].setBackground(Color.WHITE);
              bt[i].addActionListener(this); 
              bt[i].setBounds(c,k,30,30);
   } 
  }
 }
    this.setVisible(true); 
    this.pack();
    this.setSize(new Dimension(3400,735));
} 

    public void actionPerformed(ActionEvent e) { 
     for (int i = 0; i < bt.length; i++) { 
       if (e.getSource() == bt[i]) { 
       if(bt[i].getBackground() == Color.GREEN){ 
       bt[i].setBackground(Color.WHITE); 
       }else if(bt[i].getBackground() == Color.WHITE){ 
       bt[i].setBackground(Color.GREEN); 
       }else{ 
       bt[i].setBackground(Color.WHITE); 
      } 
     } 
    } 
   }
  }

    public class cinemaSeat1 { 
     public static void main()throws IOException { 
     cinemaSeats bcts = new cinemaSeats(); 
   } 
  } 

最佳答案

您的bt 数组的长度为1。即使您正在创建多个 JButton,您也只保留对其中一个(最后创建的)的引用。 因此,当您到达 actionPerformed 时,if (e.getSource() == bt[i]) 条件将仅为 true当按下最后创建的按钮时。

您必须保留对所有按钮的引用,否则您可以这样做:

public void actionPerformed(ActionEvent e) {
    JButton pressedButton = (JButton)e.getSource();
    if(pressedButton.getBackground() == Color.GREEN){ 
       pressedButton.setBackground(Color.WHITE); 
    }else if(pressedButton.getBackground() == Color.WHITE){ 
       pressedButton.setBackground(Color.GREEN); 
    }else{ 
       pressedButton.setBackground(Color.WHITE); 
    } 
}

关于java - 影院座位选择和取消选择在 JButton 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43932097/

相关文章:

java - 在服务器上运行 Shell 脚本

java - 如何向 JTextPane 添加方法

Java线程: Pause/Resume Thread vs Terminiate/Start New Thread

java - Java中的鼠标监听器

java - Android 虚拟设备配置

java - android.widget.Button 没有 setOnClickListener 方法

java - 如何创建一个新的 JFrame,其位置设置为另一个 JFrame 的中间?

java - 为面板制作背景图像时遇到问题

java - 将数据库字段值加载到 JCombobox

java - 将任务从 EDT 分派(dispatch)到 main?