-1

I have been struggling with this sorting for a while now and giving my hope to you guys.

Idea is to have a jlist that can be sorted and unsorted. I also want functionality to add an remove items from the list.

I am now asking what is the best way to do this?

I have been playing around with array.sort. right now it do sort but after sort I cannot add anymore Items to the list. Also I do not get how to unsort.

AddButton Method

        Button addButton = new Button("Add");
    addButton.setForeground(Color.WHITE);
    addButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            rightModel.addElement(leftList.getSelectedItem());
            sortList.add(leftList.getSelectedItem());

        }
    });
    addButton.setBackground(new Color(241, 57, 83));
    addButton.setBounds(48, 366, 85, 22);
    panel.add(addButton);

Jlist component

        DefaultListModel rightModel = new DefaultListModel();
    JList rightList = new JList(rightModel);
    rightList.setBounds(412, 58, 219, 283);
    contentPane.add(rightList);

SortButton method

        Button sortButton = new Button("Sort A-Z");
    sortButton.setForeground(Color.WHITE);
    sortButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            ListModel model = rightList.getModel();
            String[] strings = new String[rightModel.size()];
            for (int i = 0; i < strings.length; i++) {
                strings[i] = model.getElementAt(i).toString();
            }
            Arrays.sort(strings);
            rightList.setListData(strings); 
        }
    });
    sortButton.setBackground(new Color(241, 57, 83));
    sortButton.setBounds(412, 345, 80, 22);
    contentPane.add(sortButton);
  • 2
    Hi Marcus, you have only provided what you want to happen, but no attempt or otherwise. Please show a [mcve] and demonstrate what went wrong with your existing code, and where you specifically are stuck. – achAmháin Feb 13 '19 at 07:29
  • *I have been struggling with this sorting for a while now..* what is **this** here?? – Vishwa Ratna Feb 13 '19 at 07:30
  • Hello, I have updated now with code. – Marcus Wilen Feb 13 '19 at 08:10
  • Conceptually, what you want is a proxy model. This model will take another model as it's source and change the order in which items are returned based on some set of criteria, [for example](https://stackoverflow.com/questions/34735325/how-to-sort-a-string-array-within-a-gui/34735734#34735734). The idea is, the original model remains unchanged, so different criteria can be applied without affecting the original model – MadProgrammer Feb 13 '19 at 08:10
  • *"I have updated now with code."* But not a [mcve], as suggested by @achAmháin. Please [edit] again to add one, after carefully reviewing the MCVE document. BTW: Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Feb 13 '19 at 08:40
  • Other matters: 1) `new Button("Add");` For Swing, use `JButton`. 2) *"Idea is to have a jlist that can be sorted and unsorted."* A [`JTable`](https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/javax/swing/JTable.html) is better suited to this. *"To enable **sorting** and filtering of rows, use a `RowSorter`. .."* 3) *"Also I do not get how to unsort."* I'd approach this by adding another field that indicates the original order in which the rows were added. Then when that is sorted, it will restore the original order. How to handle items that are added after initial sort, BNI.. – Andrew Thompson Feb 13 '19 at 08:48

1 Answers1

0

This is what you need to do on your table:

table.getTableHeader().addMouseListener(new MouseAdapter() {
      private SortOrder   currentOrder    = SortOrder.UNSORTED;
      private int         lastCol         = -1;

      @Override
      public void mouseClicked(MouseEvent e) {
          int column = table.getTableHeader().columnAtPoint(e.getPoint());
          column = convertColumnIndexToModel(column);
          if (column != lastCol) {
              currentOrder = SortOrder.UNSORTED;
              lastCol = column;
          }
          RowSorter<?> sorter = getRowSorter();

          if (!((TableRowSorter)sorter).isSortable(column)) {
              return;
          }

          List<RowSorter.SortKey> sortKeys = new ArrayList<>();
          if (e.getButton() == MouseEvent.BUTTON1) {
              switch (currentOrder) {
                  case UNSORTED:
                      sortKeys.add(new RowSorter.SortKey(column, currentOrder = SortOrder.ASCENDING));
                      break;
                  case ASCENDING:
                      sortKeys.add(new RowSorter.SortKey(column, currentOrder = SortOrder.DESCENDING));
                      break;
                  case DESCENDING:
                      sortKeys.add(new RowSorter.SortKey(column, currentOrder = SortOrder.UNSORTED));
                      break;
              }
              sorter.setSortKeys(sortKeys);

          }
      }

  });

}