英文:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 12
问题
在将记录追加到文本文件之前,一切都正常,但是当我将记录追加到文本文件时,在运行程序时会出现错误。我现在不知道出了什么问题。
第一个错误
javaapplication1.LoginWindow.actionPerformed(LoginWindow.java:102)
属于以下代码行 Dashboard d = new Dashboard();
第二个错误
javaapplication1.Dashboard.<init>(Dashboard.java:200)
属于以下代码行 data[i][12] = "" + std.getAcdmcq1();
输出图片。 此图片显示追加到文本文件的记录的输出。
以下是显示的错误信息:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 12
at javaapplication1.Dashboard.<init>(Dashboard.java:200)
at javaapplication1.LoginWindow.actionPerformed(LoginWindow.java:102)
...
这是 LoginWindow.java 文件:
// ...(代码省略)
这是 Dashboard.java 文件:
// ...(代码省略)
英文:
Before I append the record into the textfile, it's all ok, but when I append the record into textfile, it start to have error when i run the program. I now no idea where got wrong
first error
javaapplication1.LoginWindow.actionPerformed(LoginWindow.java:102)
belongs to this line of code Dashboard d = new Dashboard();
second error
javaapplication1.Dashboard.<init>(Dashboard.java:200)
belongs to this line of code data[i][12] = "" + std.getAcdmcq1();
Output Photo. This picture show the output of record that I append to the textfile
Below are the error shown
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 12
at javaapplication1.Dashboard.<init>(Dashboard.java:200)
at javaapplication1.LoginWindow.actionPerformed(LoginWindow.java:102)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
This is LoginWindow.java:
package javaapplication1;
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoginWindow extends JFrame implements ActionListener,ItemListener,MouseListener{
private JLabel userName_label;
private JTextField userName;
private JLabel password_label;
private JPasswordField password;
private JButton loginButton;
private JPanel panel;
private JCheckBox display_pswrd;
private JLabel noAccount;
private JLabel role;
private JComboBox roleCmb;
public LoginWindow(){
final int win_width = 300; //window width in pixels
final int win_height = 250; //window height in pixels
setTitle("Login"); //set this window's title
setSize(win_width,win_height); //set the size of this window
//Create the components here
userName_label = new JLabel("Username: ");
userName_label.setBounds(10,20,80,25);
userName = new JTextField(15);
userName.setBounds(100,20,165,25);
password_label = new JLabel("Password: ");
password_label.setBounds(10,50,80,25);
password = new JPasswordField(15);
password.setBounds(100,50,165,25);
loginButton = new JButton("Login");
loginButton.setBounds(80,140,80,25);
loginButton.addActionListener(this);
role = new JLabel("Role: ");
role.setBounds(10,80,80,25);
String []roleList = {"","Admin","Lecturer"};
roleCmb = new JComboBox(roleList);
roleCmb.setBounds(100, 80, 165, 25);
display_pswrd = new JCheckBox("Show password");
display_pswrd.setBounds(100,110,165,25);
display_pswrd.addItemListener(this);
noAccount = new JLabel("Didn't have account ?");
noAccount.setBounds(70,170,165,25);
//set text color
noAccount.setForeground(Color.BLUE); //set text color
noAccount.addMouseListener(this);
panel = new JPanel();
//Set layout of the component which the component in the panel will align vertically
panel.setLayout(null);
panel.add(userName_label);
panel.add(userName);
panel.add(password_label);
panel.add(password);
panel.add(role);
panel.add(roleCmb);
panel.add(display_pswrd);
panel.add(loginButton);
panel.add(noAccount);
//set border for the panel
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panel is added to the JFrane's content panel
getContentPane().add(panel);
//Set this frame visible and display
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == loginButton){
//boolean usrFound = false;
String usr = userName.getText();
String pswrd = password.getText();
String loginRole = roleCmb.getSelectedItem().toString();
for(User user :AcademicSystem.allUser){ //for each user with details of username, password and role
if(user.getLogin_username().equals(usr)&&user.getLogin_password().equals(pswrd)&&user.getRole().equals(loginRole)){
AcademicSystem.user = user;
System.out.println(user.getLogin_username() + "\t" + userName.getText());
System.out.println(user.getLogin_password() + "\t" + password.getText());
System.out.println(user.getRole() + "\t" + roleCmb.getSelectedItem().toString());
System.out.println("");
}
}
if(AcademicSystem.user!=null){
if(roleCmb.getSelectedItem()=="Admin"){
JOptionPane.showMessageDialog(loginButton,"Username and password matched!");
JOptionPane.showMessageDialog(loginButton, "User[" + userName.getText() + "] have successfully logged in as " + roleCmb.getSelectedItem().toString() );
setVisible(false);
Dashboard d = new Dashboard();
d.setVisible(true);
//usrFound = true;
}else if(roleCmb.getSelectedItem()=="Lecturer"){
LecturerMenu lm = new LecturerMenu();
setVisible(false);
lm.setVisible(true);
}
}else{
JOptionPane.showMessageDialog(loginButton,"User not found");
AcademicSystem.user = null;
}
try{
PrintWriter p = new PrintWriter(new FileOutputStream("Logfile.txt", true)); //open the file in append mode
//p.print("USERNAME\tROLE\t\tACTION\t\tLOGON_TIME\n");
p.print(AcademicSystem.user.getLogin_username() + "\n");
p.print(AcademicSystem.user.getRole()+ "\n");
p.print("Login" + "\n");
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
p.print(simpleformat.format(cal.getTime())+"\n");
p.println();
p.close();
}catch(Exception er){
JOptionPane.showMessageDialog(this,er);
}
}
}
//Detect the change of state of checkbox
public void itemStateChanged(ItemEvent ie){
if (ie.getSource() == display_pswrd){
if(display_pswrd.isSelected()){
// Setting a value of 0 indicates that you wish to see the text
//as it is typed, similar to the behavior of a standard JTextField
display_pswrd.setText("Hide Password");
password.setEchoChar((char)0);
}else{
display_pswrd.setText("Show Password");
password.setEchoChar('*');
}
}
}
public void mouseClicked(MouseEvent me){
int a = JOptionPane.showConfirmDialog(null, "Do your want to a register a new account?");
if (a == JOptionPane.YES_OPTION){
setVisible(false);
Register rg = new Register();
rg.setVisible(true);
}
else{
setVisible(true);
}
}
public void mouseReleased(MouseEvent e){
//...
}
public void mouseEntered(MouseEvent e){
//...
}
public void mouseExited(MouseEvent e){
//....
}
public void mousePressed(MouseEvent e){
///......
}
}
This is my Dashboard.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Dashboard extends JFrame implements ActionListener{
//declaration here
private JTabbedPane tp;
private JPanel studentPanel;
private JPanel enrolPanel;
private JLabel nameLabel;
private JTextField nameTextField;
private JLabel GenderLabel;
private JTextField GenderTxtField;
private JLabel raceLabel;
private JComboBox raceCmbBox;
private JComboBox genderCmbBox;
private JLabel icLabel;
private JTextField icTxtField;
private JLabel religionLabel;
private JTextField religionTxtField;
private JLabel NationalityLabel;
private JTextField nationalityTxtField;
private JLabel addressLabel;
private JTextField addressTxtField;
private JLabel emailLabel;
private JTextField emailTxtField;
private JLabel contactLabel;
private JTextField contactTxtField;
private JLabel maritalLabel;
private JComboBox maritalCmb;
private JLabel postcodeLabel;
private JTextField postcodeTxtField;
private JLabel countryLabel;
private JComboBox countryCmb;
private JLabel acdmcLabel;
private JTable tbl;
private JLabel no1Label;
private JTextField no1TxtField;
private JLabel no2Label;
private JTextField no2TxtField;
private JLabel no3Label;
private JTextField no3TxtField;
private JLabel dataTableLabel;
private JButton registerButton;
private JButton editButton;
private JButton deleteButton;
private JButton gnrReportButton;
private JButton logoutButton;
public Dashboard(){
setSize(2000,500);
setTitle("Dashboard");
//component here
tp =new JTabbedPane();
studentPanel = new JPanel();
studentPanel.setLayout(null); //default layout is flow layout, set it to null so then easily to set the location of each component
nameLabel = new JLabel("Name: ");
nameLabel.setBounds(10,20,80,25);
nameTextField = new JTextField(25);
nameTextField.setBounds(100,20,165,25);
icLabel = new JLabel("IC Number: ");
icLabel.setBounds(10,50,80,25);
icTxtField = new JTextField(25);
icTxtField.setBounds(100,50,165,25);
GenderLabel = new JLabel("Gender: ");
GenderLabel.setBounds(300,20,165,25);
String[] genderList = {"","Male","Female","Other"};
genderCmbBox = new JComboBox(genderList);
genderCmbBox.setBounds(390,20,165,25);
raceLabel = new JLabel("Race:");
raceLabel.setBounds(300,50,80,25);
String[] raceList = {"","Malay","Chinese","Indians"};
raceCmbBox = new JComboBox(raceList);
raceCmbBox.setBounds(390,50,165,25);
religionLabel = new JLabel("Religion: ");
religionLabel.setBounds(10,80,80,25);
religionTxtField = new JTextField(15);
religionTxtField.setBounds(100,80,165,25);
NationalityLabel = new JLabel("Nationality: ");
NationalityLabel.setBounds(300,80,80,25);
nationalityTxtField = new JTextField(15);
nationalityTxtField.setBounds(390,80,165,25);
contactLabel = new JLabel("Contact:");
contactLabel.setBounds(10,110,165,25);
contactTxtField = new JTextField(15);
contactTxtField.setBounds(100,110,165,25);
maritalLabel = new JLabel("Marital");
maritalLabel.setBounds(300,110,165,25);
String []maritalStatus_List = {"","Single","Married"};
maritalCmb = new JComboBox(maritalStatus_List);
maritalCmb.setBounds(390,110,165,25);
postcodeLabel = new JLabel("Postcode:");
postcodeLabel.setBounds(10,140,165,25);
postcodeTxtField = new JTextField(15);
postcodeTxtField.setBounds(100,140,165,25);
countryLabel = new JLabel("Country:");
countryLabel.setBounds(300,140,165,25);
String []countryList = {"","Sarawak","Sabah"};
countryCmb = new JComboBox(countryList);
countryCmb.setBounds(390,140,165,25);
addressLabel = new JLabel("Address: ");
addressLabel.setBounds(10,170,165,25);
addressTxtField = new JTextField(30);
addressTxtField.setBounds(100,170,455,25);
emailLabel = new JLabel("Email:");
emailLabel.setBounds(10,200,165,25);
emailTxtField = new JTextField(30);
emailTxtField.setBounds(100,200,455,25);
acdmcLabel = new JLabel("Academic Qualification");
acdmcLabel.setBounds(10,230,165,25);
no1Label = new JLabel("1.");
no1Label.setBounds(10,260,165,25);
no1TxtField = new JTextField(15);
no1TxtField.setBounds(40,260,520,25);
no2Label = new JLabel("2.");
no2Label.setBounds(10,290,165,25);
no2TxtField = new JTextField(15);
no2TxtField.setBounds(40,290,520,25);
no3Label = new JLabel("3");
no3Label.setBounds(10,320,165,25);
no3TxtField = new JTextField(15);
no3TxtField.setBounds(40,320,520,25);
dataTableLabel = new JLabel("Record Table: ");
dataTableLabel.setBounds(580,1,165,25);
registerButton = new JButton("Register");
registerButton.setBounds(600,360,165,25);
registerButton.addActionListener(this);
editButton = new JButton("Edit");
editButton.setBounds(800,360,165,25);
deleteButton = new JButton("Delete");
deleteButton.setBounds(1000,360,165,25);
gnrReportButton = new JButton("Generate Report");
gnrReportButton.setBounds(1200,360,165,25);
logoutButton = new JButton("Logout");
logoutButton.setBounds(1400,360,165,25);
logoutButton.addActionListener(this);
int size = AcademicSystem.allStdInfo.size();
String[][]data = new String[size][12];
for(int i =0; i<size; i++){
Student std = AcademicSystem.allStdInfo.get(i);
data[i][0] = std.getName();
data[i][1] = "" + std.getIc();
data[i][2] = "" + std.getRace();
data[i][3] = "" + std.getGender();
data[i][4] = "" + std.getReligion();
data[i][5] = "" + std.getNationality();
data[i][6] = "" + std.getContact();
data[i][7] = "" + std.getMarital();
data[i][8] = "" + std.getPostcode();
data[i][9] = "" + std.getCountry();
data[i][10] = "" + std.getAddress();
data[i][11] = "" + std.getEmail();
data[i][12] = "" + std.getAcdmcq1();
}
String[]columns = {"Name","Ic","Race","Gender","Religion","Nationality","Contact","Marital","Postcode","Country","Address","Email","Academic Qualification"};
DefaultTableModel model = new DefaultTableModel(data,columns);
tbl= new JTable(model);
JScrollPane sp = new JScrollPane(tbl);
sp.setBounds(580,20,1335,325);
studentPanel.add(nameLabel);
studentPanel.add(nameTextField);
studentPanel.add(icLabel);
studentPanel.add(icTxtField);
studentPanel.add(raceLabel);
studentPanel.add(raceCmbBox);
studentPanel.add(GenderLabel);
studentPanel.add(genderCmbBox);
studentPanel.add(religionLabel);
studentPanel.add(religionTxtField);
studentPanel.add(NationalityLabel);
studentPanel.add(nationalityTxtField);
studentPanel.add(contactLabel);
studentPanel.add(contactTxtField);
studentPanel.add(maritalLabel);
studentPanel.add(maritalCmb);
studentPanel.add(addressLabel);
studentPanel.add(addressTxtField);
studentPanel.add(postcodeLabel);
studentPanel.add(postcodeTxtField);
studentPanel.add(countryLabel);
studentPanel.add(countryCmb);
studentPanel.add(emailLabel);
studentPanel.add(emailTxtField);
studentPanel.add(acdmcLabel);
studentPanel.add(no1Label);
studentPanel.add(no1TxtField);
studentPanel.add(no2Label);
studentPanel.add(no2TxtField);
studentPanel.add(no3Label);
studentPanel.add(no3TxtField);
studentPanel.add(dataTableLabel);
studentPanel.add(sp);
studentPanel.add(registerButton);
studentPanel.add(editButton);
studentPanel.add(deleteButton);
studentPanel.add(gnrReportButton);
studentPanel.add(logoutButton);
enrolPanel = new JPanel();
tp.add("Student",studentPanel);
tp.add("Enrolment",enrolPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panel is added to the JFrane's content panel
getContentPane().add(tp);
//Set this frame visible to be display
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==logoutButton){
setVisible(false);
AcademicSystem.user = null;
LoginWindow lg = new LoginWindow();
lg.setVisible(true);
}
else if(e.getSource()==registerButton){
String name = nameTextField.getText();
String ic = icTxtField.getText();
String race = raceCmbBox.getSelectedItem().toString();
String gender = genderCmbBox.getSelectedItem().toString();
String religion = religionTxtField.getText();
String nationality = nationalityTxtField.getText();
String contact = contactTxtField.getText();
String marital = maritalCmb.getSelectedItem().toString();
String address = addressTxtField.getText();
String postcode = postcodeTxtField.getText();
String country = countryCmb.getSelectedItem().toString();
String email = emailTxtField.getText();
String acdmc = no1TxtField.getText()+" ," + no2TxtField.getText()+" ,"+no3TxtField.getText();
if(!name.equals("")&&!ic.equals("")&&!race.equals("")&&!gender.equals("")&&!religion.equals("")&&!nationality.equals("")&&!contact.equals("")&&!marital.equals("")&&!address.equals("")&&!postcode.equals("")&&!country.equals("")&&!email.equals("")&&!no1TxtField.equals("")&&!no2TxtField.equals("")&&!no3TxtField.equals("")){
JOptionPane.showMessageDialog(this,"Profile registered successfully");
boolean found = false;
for(int i=0; i<AcademicSystem.allStdInfo.size(); i++){
Student std = AcademicSystem.allStdInfo.get(i);
if(name.equals(std.getName())){
found = true;
break;
}
}
if(!found){
Student std = new Student(name,Integer.parseInt(ic),race,gender,religion,nationality,Integer.parseInt(contact),marital,Integer.parseInt(postcode),country,address,email,acdmc);
AcademicSystem.allStdInfo.add(std);
DefaultTableModel model1 = (DefaultTableModel)tbl.getModel();
model1.addRow(new Object[]{name,ic,race,gender,religion,nationality,contact,marital,postcode,country,address,email,acdmc});
}else{
JOptionPane.showMessageDialog(this,"This user is exists in the record");
}
}else if(e.getSource()==editButton){
try{
PrintWriter p = new PrintWriter("StudentInfo.txt");
for(int i=0; i<AcademicSystem.allStdInfo.size(); i++){
Student stdnt = AcademicSystem.allStdInfo.get(i);
p.println(stdnt.getName());
p.println(stdnt.getIc());
p.println(stdnt.getRace());
p.println(stdnt.getGender());
p.println(stdnt.getReligion());
p.println(stdnt.getNationality());
p.println(stdnt.getContact());
p.println(stdnt.getMarital());
p.println(stdnt.getPostcode());
p.println(stdnt.getCountry());
p.println(stdnt.getAddress());
p.println(stdnt.getEmail());
p.println(stdnt.getAcdmcq1());
p.println();
}
p.close();
}catch(Exception er){
}
}
}
}
}
答案1
得分: 0
Java数组的索引从0开始,也就是说从零开始计数,最大的索引是长度减1。
如果你声明了一个数组,并且尝试访问超出长度的元素,你会得到和你目前遇到的完全相同的错误。
String[] data = new String[12];
data[12] = "这是一个错误";
将数组扩大一点:
String[] data = new String[13];
data[12] = "这是没问题的";
如果你习惯从1开始计数的话,可能会感到困惑。
更具体地说,在你的代码中你声明了一个数组:
String[][] data = new String[size][12];
然后你尝试在一个循环中访问这个数组:
data[i][12] = "" + std.getAcdmcq1();
需要注意的是,如果size
等于0,这段代码不会被运行,因为会受到循环条件的限制。
英文:
Java arrays are 0 indexed that means they start at zero,and the largest index is the length minus 1.
If you declare an array, and try to access an element beyond the length you get the exact error you are getting.
String[] data = new String[12];
data[12] = "this is an error";
Make your array bigger.
String[] data = new String[13];
data[12] = "this is fine";
This might be confusing if you are used to 1 base indexes.
More specifically, in your code you declare an array.
String[][]data = new String[size][12];
Then you try to access that array in a for loop.
data[i][12] = "" + std.getAcdmcq1();
Note,that this code will not get run if size is = 0 because of the for loop condition.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论