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