切换屏幕时JList复制字符串

时间:2014-05-01 20:04:10

标签: java swing jlist defaultlistmodel

我正在开发一个程序,当管理员使用ID登录他们的帐户时,他们会进入Manager屏幕。在Manager屏幕上,有一个JList,其中包含所有员工的姓名(从数据库中检索)和按钮,允许经理更新员工的信息,更新他们的日程安排,添加新员工等。按下按钮时,它切换到一个不同的屏幕,该屏幕是与ManagerLogIn类不同的类。

第一次显示经理屏幕时,员工姓名列表显示正常。我遇到的问题是当我点击任何按钮时(我将使用“更新员工信息”按钮作为示例)。我单击“更新员工信息”按钮,它会切换屏幕/类,但是当我在更新员工信息按钮上单击确定并切换回管理器屏幕时,JList会以奇怪的顺序列出每个名称两次。

我在将模型添加到JList之前使用了DefaultListModel来添加名称,我尝试在actionListener中清除JList和模型,以便在切换到新屏幕之前按下按钮,但是没有做任何事。

我的managerScreen和我的updateEmployeeInformation代码如下。我意识到他们有点长,而且组织得不好。有关如何解决问题或为何发生这种情况的任何建议?谢谢!

**我解决了这个问题。当我从数据库中选择员工时,我没有创建新的ArrayList来保存员工信息,所以一切都出现了多次

public static void main(String[] args) throws SQLException
{
    ManagerLogIn m = new ManagerLogIn();
    m.setVisible(true);
}
public ManagerLogIn() throws SQLException
{
    setTitle("Manager");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(WIDTH, HEIGHT);

    JPanel panel = new JPanel();
    JPanel buttonPanel = new JPanel();
    JPanel listPanel = new JPanel();

    panel.setLayout(new BorderLayout());
    buttonPanel.setLayout(new GridLayout(5, 1));
    listPanel.setLayout(new BorderLayout());

    /**get employees' names for a JList to appear on the Manager screen
     * Will be easy to select an employee name to grab their data and
     * view their hours, change information, generate pay stub, etc.
     */

    runDatabase();
    listData = new String[employees.size()];
    for(int i = 0; i < employees.size(); i++)
    {
        listData[i] = String.format(employees.get(i).getID() + "  " + employees.get(i).getName());
        listModel.addElement(listData[i]);
    }

    //JList code
    employeeList = new JList<String>(listModel);    
    employeeList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    employeeList.setLayoutOrientation(JList.VERTICAL_WRAP);
    ListListener lsl = new ListListener();
    employeeList.addListSelectionListener(lsl);

    //scrollpane for the JList
    scrollPane = new JScrollPane(employeeList);
    scrollPane.setPreferredSize(new Dimension(250, 100));
    scrollPane.getVerticalScrollBar().setValue(0);

    //buttons disabled until a name is selected from JList
    updateInfoB.setEnabled(false);
    generatePayStubB.setEnabled(false);
    updateScheduleB.setEnabled(false);

    ButtonHandler bh = new ButtonHandler();

    //adds button handler to all buttons
    updateInfoB.addActionListener(bh);
    generatePayStubB.addActionListener(bh);
    createNewEmpB.addActionListener(bh);
    logOutB.addActionListener(bh);
    updateScheduleB.addActionListener(bh);
    addToScheduleB.addActionListener(bh);
    addShiftB.addActionListener(bh);

    buttonPanel.add(updateInfoB);
    buttonPanel.add(generatePayStubB);
    buttonPanel.add(updateScheduleB);
    buttonPanel.add(createNewEmpB);
    buttonPanel.add(addToScheduleB);
    buttonPanel.add(addShiftB);
    buttonPanel.add(logOutB);

    listPanel.add(empLabel, BorderLayout.NORTH);
    listPanel.add(scrollPane, BorderLayout.CENTER);

    panel.add(listPanel, BorderLayout.CENTER);
    panel.add(buttonPanel, BorderLayout.EAST);

    this.add(panel);
}
//gets the name and ID of the employee selected from the JList
private class ListListener implements ListSelectionListener 
{
    /**gets name and ID of employee selected from JList and splits it into
     * an array to retrieve just the ID number.  Sends the selected ID number
     * to update classes to update that particular employee's information*/
    public void valueChanged(ListSelectionEvent e)
    {

        if(employeeList.getSelectedValuesList().size() > 0)
        {
            //enables 3 buttons when a name is selected
            updateInfoB.setEnabled(true);
            generatePayStubB.setEnabled(true);
            updateScheduleB.setEnabled(true);

            //gets the name and ID of the employee selected and splits them into an array
            selectedEmployee = listData[employeeList.getSelectedIndex()];
            String[] employeeInfo = selectedEmployee.split("  ");

            //gets the ID of the selected employee
            selectedID = employeeInfo[0];

            UpdateEmpInfoGUI ue = new UpdateEmpInfoGUI();
            ue.setID(selectedID);

            UpdateScheduleGUI us = new UpdateScheduleGUI();
            ue.setID(selectedID);

            GeneratePayStubGUI g = new GeneratePayStubGUI();
            g.setID(selectedID);
        }

        //disables buttons if a name is not selected
        else
        {
            updateInfoB.setEnabled(false);
            generatePayStubB.setEnabled(false);
            updateScheduleB.setEnabled(false);
        }
    }
}
private class ButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        //update information button pressed AND an employee's name is selected from JList
        if(e.getActionCommand().equals("Update Employee Information"))
        {

            setVisible(false);
            new UpdateEmpInfoGUI().setVisible(true);
        }

        //generate pay stub button pressed AND an employee's name is selected from JList
        else if(e.getActionCommand().equals("Generate Pay Stub"))
        {
            setVisible(false);
            new GeneratePayStubGUI().setVisible(true);
        }

        //create new employee button pressed
        else if(e.getActionCommand().equals("Create New Employee"))
        {
            setVisible(false);
            new CreateNewEmpGUI().setVisible(true);
        }

        //add to schedule button pressed
        else if(e.getActionCommand().equals("Add to Schedule"))
        {
            setVisible(false);
            new AddToScheduleGUI().setVisible(true);
        }

        //update schedule button pressed
        else if(e.getActionCommand().equals("Update Schedule"))
        {
            setVisible(false);
            new UpdateScheduleGUI().setVisible(true);;
        }

        //update shift button pressed
        else if(e.getActionCommand().equals("Add Shift"))
        {
            setVisible(false);
            new AddShiftGUI().setVisible(true);;
        }

        else //log out button
        {
            System.exit(0);
        }
    }
}




public static void main(String[] args) 
{
    UpdateEmpInfoGUI u = new UpdateEmpInfoGUI();
    u.setVisible(true);
}
//GUI window
public UpdateEmpInfoGUI()
{
    setTitle("Update Employee Information");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(WIDTH, HEIGHT);

    JPanel panel = new JPanel();
    JPanel answerPanel = new JPanel();
    JPanel buttonPanel = new JPanel();

    panel.setLayout(new BorderLayout());
    answerPanel.setLayout(new BoxLayout(answerPanel, BoxLayout.PAGE_AXIS));
    ButtonHandler bh = new ButtonHandler();

    runDatabase();

    nameTF.setText(emp.getName());
    idTF.setText(selectedID);
    payRateTF.setText(String.valueOf(emp.getPayRate()));

    ok.addActionListener(bh);
    cancel.addActionListener(bh);

    answerPanel.add(nameL, Component.LEFT_ALIGNMENT);
    answerPanel.add(nameTF, Component.RIGHT_ALIGNMENT);
    answerPanel.add(idL, Component.LEFT_ALIGNMENT);
    answerPanel.add(idTF, Component.RIGHT_ALIGNMENT);
    answerPanel.add(payRateL, Component.LEFT_ALIGNMENT);
    answerPanel.add(payRateTF, Component.RIGHT_ALIGNMENT);

    buttonPanel.add(ok);
    buttonPanel.add(cancel);

    panel.add(answerPanel, BorderLayout.CENTER);
    panel.add(buttonPanel, BorderLayout.SOUTH);

    this.add(panel);
}
//gets the ID selected by the manager in the ManagerScreen class
public void setID(String id)
{
    selectedID = id;
}
//handles buttons when pushed
public class ButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e) 
    {
        //updates the employee's information when pressed
        if(e.getActionCommand().equals("Ok"))
        {
            try
            {
                updateInfo();
                new ManagerScreen().setVisible(true);
            } 
            catch (SQLException e1) 
            {
                e1.printStackTrace();
            }
        }
        //goes back to the Manager log in screen
        else
        {
            try
            {
                new ManagerScreen().setVisible(true);
            } 
            catch (SQLException e1) 
            {
                e1.printStackTrace();
            }
        }
    }
}
//updates the employee's information
public static void updateInfo()
{
    try 
    {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

        // Method 1: direct access to a Microsoft access database file
        String filename = "./database.accdb";//use the name of your database!
        String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=";
        database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end 
        // now we can get the connection from the DriverManager
        Connection con = DriverManager.getConnection(database ,"",""); 

        // try and create a java.sql.Statement so we can run queries
        Statement s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        //gets the text from the text fields
        String employeeName = nameTF.getText();
        String id = idTF.getText();
        Double payRate = Double.valueOf(payRateTF.getText());

        //update statement
        PreparedStatement ps = con.prepareStatement("UPDATE employee SET ID=?, name=?, payRate=? WHERE ID='"+selectedID+"'");

        ps.setString(1, id); 
        ps.setString(2, employeeName);
        ps.setDouble(3, payRate);

        ps.executeUpdate();
        ps.close();

        successMessage();

    } 
    catch (Exception err) 
     {
            err.printStackTrace();
            String message = "An error occurred.\n"
                    + "Employee " + emp.getID() + "not updated.";
            String title = "Error";
            JOptionPane.showMessageDialog(null, message, title, JOptionPane.WARNING_MESSAGE);
            err.printStackTrace();
     }
}
public static void successMessage()
{
    String message = "Employee " + idTF.getText() + " successfully updated.";
    String title = "Success";
    JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
//gets the row with the selected ID number
public static void runDatabase()
{
    try 
    {
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

         // Method 1: direct access to a Microsoft access database file
         String filename = "./database.accdb";//use the name of your database!
         String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=";
         database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end 
         // now we can get the connection from the DriverManager
         Connection con = DriverManager.getConnection(database ,"",""); 

         // try and create a java.sql.Statement so we can run queries
         java.sql.Statement s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

         String query=("select name, payRate from employee where ID = '"+selectedID+"'");
         s.execute(query);
         ResultSet rs = s.getResultSet();// get any ResultSet that came from our query
         if (rs != null)
         {
             // if rs == null, then there is no ResultSet to view
            while ( rs.next()) // this will step through our data row-by-row
            {
                //the next line will get the first column in our current row's ResultSet 
                String name = rs.getString("name");
                Double payRate = rs.getDouble("payRate");

                //creates a new employee
                emp = new Employee(selectedID, name, payRate);
            }
         }

         s.close(); // close the Statement to let the database know we're done with it
      }
     catch (Exception err) 
     {
            System.out.println("ERROR: " + err);
     }
}

0 个答案:

没有答案