【问题标题】:how do i make a button that sorts my list in an ascending order(java swing)?我如何制作一个按升序对列表进行排序的按钮(java swing)?
【发布时间】:2021-03-13 11:18:47
【问题描述】:

我在 java swing 中创建了一个 jtable,如下所示

我添加了 6 个按钮,其中 3 个可以正常工作(添加、更新、删除)。我不担心随机匹配按钮,但我想要“按目标排序”按钮来整理所有由最高目标数输入的记录。积分也是如此。我试了很多次,但我似乎无法弄清楚。

这是我的表格数组的代码;

  // create JFrame and JTable
    JFrame frame = new JFrame();
    JTable table = new JTable();

    Container c = frame.getContentPane();
    c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
    c.add(table);

    // create a table model and set a Column Identifiers to this model
    Object[] columns = {"Team name", "Wins", "Losses", "Goals Difference","Points","Matches played"};
    DefaultTableModel model = new DefaultTableModel();

    model.setColumnIdentifiers(columns);

    // set the model to the table
    table.setModel(model);

    // Change A JTable Background Color, Font Size, Font Color, Row Height
    table.setBackground(Color.LIGHT_GRAY);
    table.setForeground(Color.black);
    Font font = new Font("", 1, 22);
    table.setFont(font);
    table.setRowHeight(30);
  //  table.setVisible(true);

这是我的按钮草稿;

btnSortPoints.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {


            }
        });

这是我的删除按钮;

 btnDelete.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {

                // i = the index of the selected row
                int i = table.getSelectedRow();
                if(i >= 0){
                    // remove a row from jtable
                    model.removeRow(i);
                }
                else{
                    System.out.println("Delete Error");
                }
            }
        });

这是我的全部代码;

 public class table{
        public static void main(String[] args) {
    
            // create JFrame and JTable
            JFrame frame = new JFrame();
            JTable table = new JTable();
    
            Container c = frame.getContentPane();
            c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
            c.add(table);
    
            // create a table model and set a Column Identifiers to this model
            Object[] columns = {"Team name", "Wins", "Losses", "Goals Difference","Points","Matches played"};
            DefaultTableModel model = new DefaultTableModel();
    
            model.setColumnIdentifiers(columns);
    
            // set the model to the table
            table.setModel(model);
    
            // Change A JTable Background Color, Font Size, Font Color, Row Height
            table.setBackground(Color.LIGHT_GRAY);
            table.setForeground(Color.black);
            Font font = new Font("", 1, 22);
            table.setFont(font);
            table.setRowHeight(30);
          //  table.setVisible(true);
    
            // create JTextFields
            JTextField txtTeamName = new JTextField();
            JTextField txtWins = new JTextField();
            JTextField txtLosses = new JTextField();
            JTextField txtGD = new JTextField();
            JTextField txtPoints = new JTextField();
            JTextField txtMatches = new JTextField();
    
            JLabel lblTeamName = new JLabel("Team name");
            JLabel lblWins = new JLabel("Wins");
            JLabel lblLosses = new JLabel("Losses");
            JLabel lblGD = new JLabel("Goal difference");
            JLabel lblPoints = new JLabel("Points");
            JLabel lblMatches = new JLabel("Matches");
    
            // create JButtons
            JButton btnAdd = new JButton("Add");
            JButton btnDelete = new JButton("Delete");
            JButton btnUpdate = new JButton("Update");
            JButton btnSortPoints = new JButton("Sort by points");
            JButton btnSortGoals = new JButton("Sort by goals");
            JButton btnRandomMatch = new JButton("Add a random data");
    
    
            txtTeamName.setBounds(1200, 230, 100, 25);
            txtWins.setBounds(1200, 260, 100, 25);
            txtLosses.setBounds(1200, 290, 100, 25);
            txtGD.setBounds(1200, 320, 100, 25);
            txtMatches.setBounds(1200,350,100,25);
            txtPoints.setBounds(1200,380,100,25);
    
            lblTeamName.setBounds(1100,230,100,25);
            lblWins.setBounds(1100,260,100,25);
            lblLosses.setBounds(1100,290,100,25);
            lblGD.setBounds(1100,320,100,25);
            lblMatches.setBounds(1100,350,100,25);
            lblPoints.setBounds(1100,380,100,25);
    
    
    
            btnAdd.setBounds(1150, 20, 200, 50);
            btnUpdate.setBounds(1150, 80, 200, 50);
            btnDelete.setBounds(1150, 140, 200, 50);
            btnSortGoals.setBounds(920,20,200,50);
            btnSortPoints.setBounds(920,80,200,50);
            btnRandomMatch.setBounds(920,140,200,50);
    
            // create JScrollPane
            JScrollPane pane = new JScrollPane(table);
            pane.setBounds(0, 0, 880, 400);
    
            frame.setLayout(null);
    
            frame.add(pane);
    
            // add JTextFields to the jframe
            frame.add(txtTeamName);
            frame.add(txtWins);
            frame.add(txtLosses);
            frame.add(txtGD);
            frame.add(txtMatches);
            frame.add(txtPoints);
    
    
            //Adding the labels to the frame
            frame.add(lblTeamName);
            frame.add(lblWins);
            frame.add(lblLosses);
            frame.add(lblGD);
            frame.add(lblMatches);
            frame.add(lblPoints);
    
            // add JButtons to the jframe
            frame.add(btnAdd);
            frame.add(btnDelete);
            frame.add(btnUpdate);
            frame.add(btnSortGoals);
            frame.add(btnSortPoints);
            frame.add(btnRandomMatch);
    
            // create an array of objects to set the row data
            Object[] row = new Object[6];
    
            // button add row
            btnAdd.addActionListener(new ActionListener(){
    
                @Override
                public void actionPerformed(ActionEvent e) {
    
                    row[0] = txtTeamName.getText();
                    row[1] = txtWins.getText();
                    row[2] = txtLosses.getText();
                    row[3] = txtGD.getText();
                    row[4] = txtMatches.getText();
                    row[5] = txtPoints.getText();
    
                    // add row to the model
                    model.addRow(row);
                }
            });
    
            // Event listener for button remove row
            btnDelete.addActionListener(new ActionListener(){
    
                @Override
                public void actionPerformed(ActionEvent e) {
    
                    // i = the index of the selected row
                    int i = table.getSelectedRow();
                    if(i >= 0){
                        // remove a row from jtable
                        model.removeRow(i);
                    }
                    else{
                        System.out.println("Delete Error");
                    }
                }
            });
    
            // get selected row data From table to textfields
            table.addMouseListener(new MouseAdapter(){
    
                @Override
                public void mouseClicked(MouseEvent e){
    
                    // i = the index of the selected row
                    int i = table.getSelectedRow();
    
                    txtTeamName.setText(model.getValueAt(i, 0).toString());
                    txtWins.setText(model.getValueAt(i, 1).toString());
                    txtLosses.setText(model.getValueAt(i, 2).toString());
                    txtGD.setText(model.getValueAt(i, 3).toString());
                    txtMatches.setText(model.getValueAt(i,4).toString());
                    txtPoints.setText(model.getValueAt(i,5).toString());
                }
            });
    
            // button update row
            btnUpdate.addActionListener(new ActionListener(){
    
                @Override
                public void actionPerformed (ActionEvent e) {
    
                    // i = the index of the selected row
                    int i = table.getSelectedRow();
    
                    if(i >= 0)
                    {
                        model.setValueAt(txtTeamName.getText(), i, 0);
                        model.setValueAt(txtWins.getText(), i, 1);
                        model.setValueAt(txtLosses.getText(), i, 2);
                        model.setValueAt(txtGD.getText(), i, 3);
                        model.setValueAt(txtMatches.getText(),i,4);
                        model.setValueAt(txtPoints.getText(),i,5);
                    }
                    else{
                        System.out.println("Update Error");
                    }
                }
            });
    
            btnSortPoints.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
    
    
                }
            });
    
    
                    frame.setSize(1400, 500);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    
        }
    
    }

【问题讨论】:

  • 您是否查看了How to use Tables 的教程,尤其是Sorting and Filtering 部分?
  • @maloomeister 是的,它对这个特定问题没有帮助。
  • 按下按钮时,您正试图按“目标”列对表格进行排序,对吗?如果是这样,那么第二个链接应该会有所帮助。

标签: java arrays swing


【解决方案1】:
  1. 您首先需要为您的 JTable 添加排序支持。阅读教程中的 Sorting and Filtering 链接,了解如何执行此操作。

  2. 完成后,用户将能够通过单击列的列标题对任何列进行排序。

通过手动单击列标题来验证排序是否有效。

我希望“按目标排序”按钮将所有输入的记录按目标和分数最高的次数排序

现在您的JTable 支持排序,您可以在按钮中添加ActionListener 以进行特定排序:

btnSortPoints.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {

        // Points column in the model is converted to the view column

        int viewColumn = table.convertColumnIndexToView(4); 

        // Set up the columns you want to sort on

        List<RowSorter.SortKey> sortKeys = new ArrayList<>();
        sortKeys.add(new RowSorter.SortKey(viewColumn, SortOrder.ASCENDING));

        // Do the sorting

        TableRowSorter sorter = (TableRowSorter)table.getRowSorter();
        sorter.setSortKeys(sortKeys);    
    }
});

`

【讨论】:

  • 嗨,我仍在努力让我的桌子支持分拣机,但我仍然无法做到
  • 示例和我的主要区别在于示例 1 已经有数据。用我的你可以添加数据
  • @Alireza1999 这没什么区别。您创建模型并将数据添加到模型中。然后将模型添加到表中。然后启用对表格的排序。然后通过更新模型来完成对数据的任何更改。数据会自动排序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多