我在Java代码中存在一个常量问题。 每当我尝试在我的程序上使用我的按钮他们不工作,我认为问题是在event.getSource(),但我找不到它。 这里是我的完整代码:ActionListener和event.getSource()
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Safe extends JFrame implements ActionListener{
private JButton b1, b2, b3;
private JTextField display;
private JLabel displayLabel;
private int[] pass = new int[5];
private int hits = 0;
public static void main(String[] args){
Safe frame = new Safe();
frame.setSize(250, 100);
frame.createGUI();
frame.setVisible(true);
}
private void createGUI(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
b1 = new JButton("1");
window.add(b1);
b1.addActionListener(this);
b2 = new JButton("2");
window.add(b2);
b2.addActionListener(this);
b3 = new JButton("3");
window.add(b3);
b3.addActionListener(this);
displayLabel = new JLabel("Enter 6 digit combination:");
window.add(displayLabel);
display = new JTextField(6);
window.add(display);
}
public void actionPerformed(ActionEvent event){
int i;
int[] user = new int[5];
if(hits == 0){
pass[0] = 1;
pass[1] = 1;
pass[2] = 1;
pass[3] = 1;
pass[4] = 1;
pass[5] = 2;
}
for(i=0;i<5;i++){
if(event.getSource() == b1){
display.setText("1");
user[i] = 1;
}
else if(event.getSource() == b2){
display.setText("2");
user[i] = 2;
}
else if(event.getSource() == b3){
display.setText("3");
user[i] = 3;
}
}
i = -1;
do{
i++;
if(pass[i] != user[i]){
JOptionPane.showMessageDialog(null,"Incorrect Code! Try Again!");
}
if(i == 5){
JOptionPane.showMessageDialog(null,"Correct Code!");
}
}while(pass[i] == user[i]);
}
}
错误接收
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 5
at Safe.actionPerformed(Safe.java:53)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
当你运行它时会发生什么? – Reimeus
有没有错误?预期的行为是什么?实际是什么? – Ish
它在运行时出现此错误(并非所有错误)线程“AWT-EventQueue-0”中的@Reimeus异常java.lang.ArrayIndexOutOfBoundsException:5 at Safe.actionPerformed(Safe.java:53) at javax .swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton $ Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) –