如何在我的ButtonActionPerformed

时间:2018-06-04 03:10:12

标签: java swing methods buttonclick writetofile

背景

我有大约4个按钮,每次点击按钮我想写入文件。到目前为止,当我写了ToFile();就像在deleteStudentActionPerformed方法中一样,它会从所有课程中删除所有学生。

问题:

我可以在actionPerformed方法中调用此方法吗?

我已经使用更完整的代码更新了这篇文章,让每个人都能看到我想要实现的目标。

Course.java

package coursestudent;

import java.util.ArrayList;


public class Course { //one course, multiple students

//fields / instance variables
private String courseName;
//stores a list of students
private ArrayList<String> studentList = new ArrayList();

//methods

public void setCourseName(String name)
{
    courseName = name;
}

public String getCourseName()
{
    return courseName;
}

//add one student
public void addStudent(String studentName)
{
    studentList.add(studentName);
}

//delete one student
public void deleteStudent(int index)
{
    studentList.remove(index);
}

//get student list
public ArrayList<String> getStudentList()
{
    return studentList;
}
  public boolean isEmpty()
{
    if (studentList.isEmpty())
        return true;
    else
        return false;

}





}

CourseApp.java

package coursestudent;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;


public class CourseApp extends javax.swing.JFrame {

//courseData will store a list of courses
HashMap<String, Course> courseData = new HashMap<String, Course>();
//file name
final String FILENAME = "course.txt";

/**
 * Creates new form CourseApp
 */
public CourseApp() {

    initComponents();

    //reads from file course.txt
    readFile();

    //add courses to combobox
    for(String coursename : courseData.keySet())
    {
        courseCombobox.addItem(coursename);
    }
}

//method to read from course.txt and put data in variable courseData
public void readFile()
{
    BufferedReader bw = null;
    try {
        bw = new BufferedReader(new FileReader(FILENAME));

        //reads the first line of file
        String line = bw.readLine();

        while(line!=null)//while it is not the end of file
        {
            //parses this line
            //find index of "<<<<"
            int index = line.indexOf("<<<<");
            //call subString to return the course Name
            String courseName = line.substring(0,index);//returns course name
            String studentName = line.substring(index+4);

            //make a course Object

            //if hashmap has the key already
            //add one more student 
            if(courseData.containsKey(courseName))
            {
                //get the course object
                Course c = courseData.get(courseName);
                c.addStudent(studentName);
            }
            else//add one new course
            {

                Course cObj = new Course();
                cObj.setCourseName(courseName);
                cObj.addStudent(studentName);
                courseData.put(courseName, cObj);
            }

            //read next line
            line = bw.readLine();

        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(CourseApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CourseApp.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally
    {
        try {
            bw.close();
        } catch (IOException ex) {
            Logger.getLogger(CourseApp.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
    public void writeToFile()
{

    PrintWriter out = null;

    try
    {
        out = new PrintWriter(new BufferedWriter(new FileWriter("course.txt")));

        for (String courseName:courseData.keySet())
        {

            Course course = courseData.get(courseName);
            if(!course.isEmpty())
            {

                ArrayList<String> students = course.getStudentList();
                for (String s : students)
                {
                    out.println(courseName + "<<<<");                        
                }
            }
            else
            {
                out.println(courseName + "<<<<");
            }
        }
    } catch (IOException ex)
    {
        Logger.getLogger(CourseApp.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally
    {
        out.close();
    }
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")



// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    courseCombobox = new javax.swing.JComboBox<>();
    addcourseButton = new javax.swing.JButton();
    addTextField = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    studentListBox = new javax.swing.JList<>();
    addstudentButton = new javax.swing.JButton();
    deletestudentButton = new javax.swing.JButton();
    deletecourseButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    courseCombobox.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            courseComboboxItemStateChanged(evt);
        }
    });

    addcourseButton.setText("Add Course");
    addcourseButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            addcourseButtonActionPerformed(evt);
        }
    });

    jScrollPane1.setViewportView(studentListBox);

    addstudentButton.setText("Add Student");
    addstudentButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            addstudentButtonActionPerformed(evt);
        }
    });

    deletestudentButton.setText("Delete Student");
    deletestudentButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            deletestudentButtonActionPerformed(evt);
        }
    });

    deletecourseButton.setText("Delete Course");
    deletecourseButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            deletecourseButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(64, 64, 64)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(addTextField)
                    .addComponent(courseCombobox, 0, 127, Short.MAX_VALUE))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(68, 68, 68)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(deletestudentButton, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                .addComponent(deletecourseButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(addstudentButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(addcourseButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGap(73, 73, 73))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(42, 42, 42)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(courseCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(addcourseButton))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(34, 34, 34)
                    .addComponent(addTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addComponent(addstudentButton)))
            .addGap(24, 24, 24)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(14, 14, 14)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(2, 2, 2)
                    .addComponent(deletecourseButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(deletestudentButton)))
            .addContainerGap(136, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void addcourseButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
    // TODO add your handling code here:
    //1. read text from text field
    String newcourseName = addTextField.getText();

    //2. create a course object
    //initializes the course name
    Course newcourseObj = new Course();
    newcourseObj.setCourseName(newcourseName);

    //3. add this new course to the hashmap
    //use put(key, value) method to add a new course
    courseData.put(newcourseName, newcourseObj);

    //update combobox

    courseCombobox.addItem(newcourseName);

      if (addTextField.getText().equals("")){

        JOptionPane.showMessageDialog(null, "Missing A Course Name!", "Missing A Course Name!", JOptionPane.ERROR_MESSAGE);


    }

    //4..to be continued (update file)

}                                               

private void courseComboboxItemStateChanged(java.awt.event.ItemEvent evt) {                                                
    // TODO add your handling code here:
    //step1 : get selected course name from the combobox
    //CIS 304 OR ACC 207

    String courseName = courseCombobox.getSelectedItem().toString();

    //step2: retrieve the course object from the hashmap courseData using course name
    //value will be returned after key is provided
    Course cObj = courseData.get(courseName);


    //step3: get the student list from the course object(getStudents())
    ArrayList<String> studentlist = cObj.getStudentList();


   //step4: add student names to the list box
   //defaultlistmodel
   DefaultListModel model = new DefaultListModel();

   //enhanced for loop
   for(String name: studentlist)
   {
       model.addElement(name);
   }

   //link the model with listbox
   studentListBox.setModel(model);






}                                               




private void addstudentButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                 
    // TODO add your handling code here:
    //step1: get course name
    String courseName = courseCombobox.getSelectedItem().toString();

    //step2: get student
    String studentName = addTextField.getText();


    //step3: retrieve the course object from the hashmap
    Course cObj = courseData.get(courseName);

    //step4: add this student
    cObj.addStudent(studentName);

    //Update Model
    DefaultListModel model = (DefaultListModel)studentListBox.getModel();
    model.addElement(studentName);



    if (addTextField.getText().equals("")){

        JOptionPane.showMessageDialog(null, "Missing A Students Name!", "Missing A Students Name!", JOptionPane.ERROR_MESSAGE);


    }
    //to be continued

}                                                

private void deletestudentButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                    
    // TODO add your handling code here:
    String courseName = courseCombobox.getSelectedItem().toString();

    Course cObj = courseData.get(courseName);

    List<String> studentNames = studentListBox.getSelectedValuesList();

    DefaultListModel model = (DefaultListModel)studentListBox.getModel();
    //loop to delete all the students from the hash map

    for(String student: studentNames)
    {
        cObj.getStudentList().remove(student);
        model.removeElement(student);
    }

     if (addTextField.getText().equals("")){

    writeToFile(); 

        JOptionPane.showMessageDialog(null, "Missing A Students Name!", "Missing A Students Name!", JOptionPane.ERROR_MESSAGE);

    }
    // to be continued



}                                                   

private void deletecourseButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                   
    // TODO add your handling code here:
    //read text box
     String newcourseName = addTextField.getText();

      Course newcourseObj = new Course();
    newcourseObj.setCourseName(newcourseName);

     //3. add this new course to the hashmap
    //use put(key, value) method to add a new course
    courseData.remove(newcourseName, newcourseObj);

    //update combobox

    courseCombobox.removeItem(newcourseName);


     if (addTextField.getText().equals("")){

        JOptionPane.showMessageDialog(null, "Missing A Course Name!", "Missing A Course Name!", JOptionPane.ERROR_MESSAGE);


    }


}                                                  






/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(CourseApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CourseApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CourseApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CourseApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new CourseApp().setVisible(true);
        }
    });
}


// Variables declaration - do not modify                     
private javax.swing.JTextField addTextField;
private javax.swing.JButton addcourseButton;
private javax.swing.JButton addstudentButton;
private javax.swing.JComboBox<String> courseCombobox;
private javax.swing.JButton deletecourseButton;
private javax.swing.JButton deletestudentButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList<String> studentListBox;
// End of variables declaration                   

}

这是我第一次在这里发帖。提出两个问题是不恰当的? 谢谢!

1 个答案:

答案 0 :(得分:0)

如果要在actionPerformed方法中调用writeToFile,则它取决于您使用的结构。这些方法是否属于同一类?

如果是:

import java.awt.event.ActionEvent;

public class Thing {

  private void deleteCourseButton(ActionEvent event) {
    // STUFF YA KNOW

    // Call the helper method
    if (somethingHappens) {
      writeToFile();
    }

    // OTHER STUFF
  }

  // The helper method to be called
  private void writeToFile() {
    // Do something fun
  }

}

如果不是,则需要导入包含writeToFile的类,实例化该类的对象,并在该对象上调用writeToFile:

public class Thing1 {

  public void writeToFile() {
    // Fun stuff right here
  }

}

*和:

import Thing1;
import java.awt.event.ActionEvent;

public class Thing2 {

  private void deleteCourseButton(ActionEvent event) {
    // stuff heh

    if (condition) {
      // Instantiate object
      Thing1 thing1= new Thing1();
      // Call the object's method
      thing1.writeToFile();
    }

    // otherStuff
  }

}

请注意,如果类位于两个不同的包中,则导入为:

import packageNameHere.Thing1;

另请注意不同的可见性修饰符。如果方法属于同一类,则两者都可以是私有的,并且仍然可以相互调用。如果它们位于不同的类中,则在其本机类之外调用的方法不能是私有的,因此现在将其公开以保持简单。

不确定你想要做什么,但这是一个简单的答案。您可能需要使用多线程和无限循环,具体取决于。