当前位置: 首页 > 知识库问答 >
问题:

JTable选择和删除

费子濯
2023-03-14

我有一个JTable,它显示保存在ArrayList集合中的customer对象列表。从这个JTable中,我希望能够突出显示一个特定的客户,然后单击一个“delete customer”按钮,该按钮从选定的表行中提取ID列值,并用它用迭代器在ArrayList中搜索,找到匹配的客户,并将其从集合中删除。我在swing组件和eventlisteners方面的专业知识还有很多需要改进的地方,到目前为止我已经尝试了大约5种不同的组合,但没有任何进展。我该怎么做?到目前为止,我的代码的相关部分有:

class CustomerFrame extends JFrame{
    public CustomerFrame(travelagent agent){

        CustomerPanel cp = new CustomerPanel(agent, this);
        setSize(800,500);
        setLocationRelativeTo(null);
        setTitle("Actions for customer");


        add(cp);

    }
}

class CustomerPanel extends JPanel implements ActionListener, ListSelectionListener{
    private travelagent agent;
    private JButton addCust;
    private JButton deleteCust;
    private JButton editCust;
    private JButton bookFlight;
    private JButton exit;
    private CustomerFrame frame;
    private Object selectedID;
    private JTable ref;

    public CustomerPanel(travelagent agent, CustomerFrame frame){
        ListCustPanel lp = new ListCustPanel(agent);
        setLayout(new GridLayout(2,1,5,5));

        ref = lp.getTable();
        ListSelectionModel sel = ref.getSelectionModel();
        sel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        sel.addListSelectionListener(this);

        this.agent = agent;
        this.frame = frame;
        JLabel options = new JLabel("Options:");
        addCust = new JButton("Add customer");
        deleteCust = new JButton("Delete customer");
        editCust = new JButton("Edit Customer");
        bookFlight = new JButton("Book a flight");
        exit = new JButton("Back to main menu");

        options.setHorizontalAlignment(SwingConstants.CENTER);
        JPanel b = new JPanel(new GridLayout(3,2,5,5));

        b.add(options);
        b.add(addCust);
        b.add(deleteCust);
        b.add(editCust);
        b.add(bookFlight);
        b.add(exit);

        add(lp);
        add(b);

        addCust.addActionListener(this);
        deleteCust.addActionListener(this);
        editCust.addActionListener(this);
        bookFlight.addActionListener(this);
        exit.addActionListener(this);
    }


    public void valueChanged(ListSelectionEvent l){
        if(!l.getValueIsAdjusting()){
            int index = ref.getSelectedRow();
            selectedID = ref.getValueAt(index, 0);
        }
    }

    public void actionPerformed(ActionEvent e){
        if(e.getSource() == addCust){
            NewCustFrame cf = new NewCustFrame(agent, frame);
            cf.setVisible(true);
            cf.setDefaultCloseOperation(NewCustFrame.DISPOSE_ON_CLOSE);

        if(e.getSource() == deleteCust){
            DeleteCustFrame df = new DeleteCustFrame(agent, selectedID);
            df.setVisible(true);
            df.setDefaultCloseOperation(DeleteCustFrame.DISPOSE_ON_CLOSE);
        }
        if(e.getSource() == editCust){

        }
        if(e.getSource() == bookFlight){

        }
        if(e.getSource() == exit){
            frame.dispose();
        }

    }
    }



}





/*
 * this displays the list of customers:
 */
class ListCustPanel extends JPanel{

    private static final long serialVersionUID = 1L;
    private JTable table;
    public ListCustPanel(travelagent agent){

        String[] colNames = {"ID", "First Name", "Last Name"};

        int size = agent.getCust().size(); //get the size of the arraylist in order to define an object array to contain information in
        Object[][] data = new Object[size][3]; // create the array

        int i = 0;
        Iterator<customer> iter = agent.getCust().iterator(); //create an iterator to progress thought the arraylist
        while(iter.hasNext()){
            customer temp = iter.next(); //assign the current customer to a variable

            //extract its attributes and feed into object array
            data[i][0] = temp.getID(); 
            data[i][1] = temp.getFname();
            data[i++][2] = temp.getLname();

        }
        setLayout(new GridLayout(1,1,5,5));


        // convert the object array into a JTable
        table = new JTable(data, colNames);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // create a sorter to sort table rows
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());
        table.setRowSorter(sorter);
        ArrayList<SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
        sortKeys.add(new RowSorter.SortKey(2, SortOrder.ASCENDING));
        sorter.setSortKeys(sortKeys);


        JScrollPane scrollPane = new JScrollPane(table);
        table.setFillsViewportHeight(true);
        add(scrollPane);


    }

    public JTable getTable(){
        return table;
    }
}


/*
 * delete the customer using this
 */
class DeleteCustFrame extends JFrame{
    public DeleteCustFrame(travelagent agent, Object ID){
        DeleteCustPanel dcp = new DeleteCustPanel(agent, this, ID);
        add(dcp);

        setSize(300,200);
        setTitle("Delete Customer");
        setLocationRelativeTo(null);

    }

}

class DeleteCustPanel extends JPanel implements ActionListener{
    private travelagent agent;
    private JButton delete;
    private JButton cancel;
    private JTextField id;
    private DeleteCustFrame frame;
    public int ID;

    public DeleteCustPanel(travelagent agent, DeleteCustFrame frame, Object ID){
        this.ID = (int)ID;
        this.agent = agent;
        setLayout(new GridLayout(3,1,5,5));

        String fname = null;
        String lname = null;
        boolean hasFlight = false;
        Iterator<customer> iter = agent.getCust().iterator();
        while(iter.hasNext()){
            customer temp = iter.next();
            if(temp.getID() == this.ID){
                 fname = temp.getFname();
                 lname = temp.getLname();
            }
            if(temp.getNumFlight() > 0){
                hasFlight = true;
            }
        }

        JLabel desc = new JLabel("Customer: " + ID + " " + fname + " " + lname);;
        desc.setHorizontalAlignment(SwingConstants.CENTER);
        JLabel yesFlight;
        if(hasFlight){
             yesFlight = new JLabel("This customer has flights booked!");
        }else{
            yesFlight = new JLabel("No flights are booked for this customer");
        }

        yesFlight.setHorizontalAlignment(SwingConstants.CENTER);

        JPanel buttonPanel = new JPanel();

        buttonPanel.setLayout(new GridLayout(1,2,5,5));
        buttonPanel.add(delete);
        buttonPanel.add(cancel);

        add(desc);
        add(yesFlight);
        add(buttonPanel);

        delete.addActionListener(this);
        cancel.addActionListener(this);

    }


    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == delete){
            Iterator<customer> iter = agent.getCust().iterator();
            while(iter.hasNext()){
                customer temp = iter.next();
                if(temp.getID() == ID){
                    agent.deleteCust(temp);
                }
            }
            JOptionPane.showMessageDialog(null, "Customer deleted!", null, JOptionPane.PLAIN_MESSAGE);
            frame.dispose();
        }
        if(e.getSource() == cancel){
            frame.dispose();
        }

    }
}

到目前为止,当我单击delete customer并突出显示一个customer时,不会采取任何操作。我知道一个很长的问题,但如果它有帮助的话,我怀疑我的问题发生在我试图使用ListSelectionListener的地方。

共有1个答案

尉迟安民
2023-03-14

JTable提供了一个DefaultTableModel使此操作更加简单。请使用它来代替arraylist

这些方法包括removerow(int),其中int(row)来自JTable.GetSelectedRow()

 类似资料:
  • 问题内容: 我目前正在使用JTable来显示数据库中的内容。我想为用户提供便利,以便他可以使用Shift +箭头键选择想要的行数,然后稍后使用提供的删除选项删除那些记录。请提供一个小例子。 问题答案: 您需要允许多项选择: 然后,您需要编写适当的选择侦听器。这有点困难,请尝试在Google相关解决方案中查找。您可以看一个选择侦听器的示例。

  • 问题内容: 我有一个JTable,它的一列是不可编辑的文本,第二列是一个显示布尔值的复选框…。现在我要的是,当用户选择多行并取消选中其中的任何一个时选中的复选框,则选中的所有复选框都应取消选中,反之亦然。 问题答案: 使用@Hovercraft的示例和@camickr的建议,以下示例显示了合适的用户界面。尽管它使用按钮,但它也适用于菜单或弹出窗口。

  • 在我的Jtable实例中,一个列有jcombobox,现在我想要的是,一旦所选jComboBox的值被更改,就选择单元格的行和列。 如果我使用jcombobox的actionPerformed事件,并获得jtable.getSelectedrow和column。系统给我最后选择的行和列,而不是当前的行和列。 请指导我该怎么做..谢谢

  • 除了使用之外,是否有其他方法可以侦听已选择的单元格(即使是带有)的单元格)? 我有一个带有行和列侦听器的JTable。当选择已经选择的单元格时,两个侦听器都不会触发: 我的目标是打开/关闭电池。它是有效的,除了监听器在选择一个已经选择的单元格时不会触发之外,这是通过上面的SSCCE表示的。 似乎没有任何监听器可以连接到(或者它的模型/选择模型)来处理这个问题,除非我使用并手动管理Cooridate

  • 我想将JTable中的行选择限制为仅2行。如果用户尝试选择第三行(Ctrl单击),则应通过编程方式取消选择表中最早的选择。为了实现这一点,我在表中添加了一个ListSelectionListener。在下面的示例中,似乎不起作用。 如果有更简单或更优雅的方法来达到同样的效果,请给出建议。