gpt4 book ai didi

java - ActionListener 和 event.getSource()

转载 作者:行者123 更新时间:2023-11-30 03:13:01 32 4
gpt4 key购买 nike

我在 Java 代码中经常遇到问题。每当我尝试在程序上使用按钮时,它们都不起作用,我认为问题出在 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)

最佳答案

int[] user = new int[5];
...
//pass[5] = 2;

数组索引是从 0 开始的,因此索引 5 实际上是不存在的第 6 个条目。因此,删除该声明。

关于java - ActionListener 和 event.getSource(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245766/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com