HỎI Hỏi về cách xử lý dữ liệu trong JList

Toantang2632000

New Member
18/5/20
11
1
3
Hà Nội
Chào mọi người,
Hiện tại e đang làm bài tập lớn, e đang xây dựng một Jlist gồm item a, b, c. Mỗi item sẽ gọi 1 method riêng rẽ, ví dụ: a sẽ gọi x, b sẽ gọi y, c sẽ gọi z (x, y, z là các method).
Vấn đề của e bây giờ là: khi e chọn đồng thời 2 item a và b thì làm sao để gọi đồng thời 2 method x, y và in ra jTextArea ạ?
Mong mọi người giúp đỡ. Code của e đây ạ
Java:
public String print() {
        return "haloooo";
    }
    public String Cat() {
        return "Cat";
    }
    @Override
    public void actionPerformed(ActionEvent e) {   
        if (e.getSource() == view.getShow()) {   
            String c = view.getPaperArea().getText();
                if (view.getTopicName().getSelectedItem().equals("co phieu")) {               
                    if (view.getTagList().getSelectedIndex() == 0) {
                        view.getPaperArea().setText((String) c + test.print());
                    }   
                    if (view.getTagList().getSelectedIndex() == 1) {
                        view.getPaperArea().setText((String) c + test.Cat());
                    }
                }
            }       
        if (e.getSource() == view.getClear()) {
            view.getPaperArea().setText("");
        }
        
    }
 
Sửa lần cuối:

Joe

Thành viên VIP
21/1/13
2,969
1,310
113
Chao cau @Toantang2632000
I am a foreigner who understands some Vietnamese, but I don't dare to write in Vietnamese because of the myriad accents (´`^?.~). I see your question and I could help you with a little program. However I don't because I think that you should firstly try to write down your coding idea and when it won't work you could post the codes HERE so that I could see what you have tried and reward you with the correction of your codes and give you some coding hints to the JList and more in general.

It's like trying to learn riding a bicycles. You cannot learn if you don't try to climb onto the bicycle seat and try to pedal forwards. Am I right? So, try to code and show us how far you have tried.
 
  • Like
Reactions: Toantang2632000

quydtkt

Administrator
1/11/19
389
38
28
27
Mình chưa hiểu câu hỏi của bạn. Bạn có thể giải thích rõ hơn không?
 

Toantang2632000

New Member
18/5/20
11
1
3
Hà Nội
Mình chưa hiểu câu hỏi của bạn. Bạn có thể giải thích rõ hơn không?
ý của em là : e tạo JList có 2 phần từ là a và b. a sẽ gọi hàm x, b sẽ gọi hàm y. Em mới chỉ biết gọi hàm của 1 lựa chọn, ví dụ e selecItem a thì sẽ gọi dc hàm x. Bây giờ e muốn chọn cả 2 item là a và b(giống như bôi đen 2 item ấy ạ) => chương trình sẽ gọi cả 2 hàm x và y tương ứng theo a và b ạ.
Code e đây ạ
 

Attachments

quydtkt

Administrator
1/11/19
389
38
28
27
Java:
    int[] selectedIx = list.getSelectedIndices();

    // Get all the selected items using the indices
    for (int i = 0; i < selectedIx.length; i++) {
      Object sel = list.getModel().getElementAt(selectedIx[i]);
      // do something
    }
Hy vọng cái này sẽ giúp được bạn
Ps: Bạn chỉnh code của mình lại cho đúng qua tắc nha
 
  • Love
Reactions: Toantang2632000

Joe

Thành viên VIP
21/1/13
2,969
1,310
113
Java:
    int[] selectedIx = list.getSelectedIndices();

    // Get all the selected items using the indices
    for (int i = 0; i < selectedIx.length; i++) {
      Object sel = list.getModel().getElementAt(selectedIx[i]);
      // do something
    }
Hy vọng cái này sẽ giúp được bạn
Ps: Bạn chỉnh code của mình lại cho đúng qua tắc nha
Boss, he said
muốn chọn cả 2 item là a và b (giống như bôi đen 2 item ấy ạ)
meaning he wants to have BOTH items at once. And that has nothing to do with the execution, but with the declaration of selection policy: single or MULTIPLE selection. BTW, as I said, I help only if I see the codes, not a screenshot. Rules are rules and must be kept. They are not there just for fun.
 
  • Sad
Reactions: Toantang2632000

Toantang2632000

New Member
18/5/20
11
1
3
Hà Nội
Chao cau @Toantang2632000
I am a foreigner who understands some Vietnamese, but I don't dare to write in Vietnamese because of the myriad accents (´`^?.~). I see your question and I could help you with a little program. However I don't because I think that you should firstly try to write down your coding idea and when it won't work you could post the codes HERE so that I could see what you have tried and reward you with the correction of your codes and give you some coding hints to the JList and more in general.

It's like trying to learn riding a bicycles. You cannot learn if you don't try to climb onto the bicycle seat and try to pedal forwards. Am I right? So, try to code and show us how far you have tried.
Oh, I'm sorry so much. Thank you very much for reading my post, I have just joined this community and I editted my post. Thank you.
 

Toantang2632000

New Member
18/5/20
11
1
3
Hà Nội
Boss, he said

meaning he wants to have BOTH items at once. And that has nothing to do with the execution, but with the declaration of selection policy: single or MULTIPLE selection. BTW, as I said, I help only if I see the codes, not a screenshot. Rules are rules and must be kept. They are not there just for fun.
I'm sorry so much, help me please
 

quydtkt

Administrator
1/11/19
389
38
28
27
Boss, he said

meaning he wants to have BOTH items at once. And that has nothing to do with the execution, but with the declaration of selection policy: single or MULTIPLE selection. BTW, as I said, I help only if I see the codes, not a screenshot. Rules are rules and must be kept. They are not there just for fun.
he corrected it. Hopefully, he will learn from his experience for next time
 
  • Love
Reactions: Toantang2632000

Joe

Thành viên VIP
21/1/13
2,969
1,310
113
If you posted the whole app I could give you MORE hints about Java SWING and how to program an APP optimally. Here is an example for MULTIPLE selection of JList. The codes have 2 commented sections:

ListSelectionListener
Java:
        /* This selection way */
        jlist.addListSelectionListener(e -> {
          int i = 1;
          jta.setText("");
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
        });
Lambda ActionListener (without the "implements ActionListener")
Java:
        jb.addActionListener(e -> {
          int i = 1;
          jta.setText("");
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
and here is the 3rd option with implements ActionListener
Java:
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
// Joe Nartca
public class ExampleJList extends JFrame implements ActionListener {
    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        new ExampleJList();
    }
    public ExampleJList() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel jp = new JPanel();
        JLabel jl = new JLabel("Pick the day(s)");
        // declare TextArea
        jta = new JTextArea();
        String week[]= { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
        // declare JList with the String Array week
        jlist = new JList<>(week);
        // set model for MULTIPLE CHOICES
        jlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        /* This selection way
        jlist.addListSelectionListener(e -> {
          int i = 1;
          jta.setText("");
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
        });
        */
        // or this JButton way
        JButton jb = new JButton("OK");
        jb.addActionListener(this);
        /* This way without implements ActionListener
        jb.addActionListener(e -> {
          int i = 1;
          jta.setText("");
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
        });
        */
        jp.add(jl); jp.add(jlist);
        add("North", jp);
        add("Center", jta);
        add("South", jb);
        setSize(300,400);
        setVisible(true);
    }
    private JTextArea jta;
    private JList<String> jlist;
    public void actionPerformed(ActionEvent e) {
          int i = 1;
          jta.setText("");
          // get the list of selected Items.
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
    }
}
JlistExample.png
 
  • Like
Reactions: Toantang2632000

Toantang2632000

New Member
18/5/20
11
1
3
Hà Nội
If you posted the whole app I could give you MORE hints about Java SWING and how to program an APP optimally. Here is an example for MULTIPLE selection of JList. The codes have 2 commented sections:

ListSelectionListener
Java:
        /* This selection way */
        jlist.addListSelectionListener(e -> {
          int i = 1;
          jta.setText("");
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
        });
Lambda ActionListener (without the "implements ActionListener")
Java:
        jb.addActionListener(e -> {
          int i = 1;
          jta.setText("");
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
and here is the 3rd option with implements ActionListener
Java:
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
// Joe Nartca
public class ExampleJList extends JFrame implements ActionListener {
    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        new ExampleJList();
    }
    public ExampleJList() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel jp = new JPanel();
        JLabel jl = new JLabel("Pick the day(s)");
        // declare TextArea
        jta = new JTextArea();
        String week[]= { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
        // declare JList with the String Array week
        jlist = new JList<>(week);
        // set model for MULTIPLE CHOICES
        jlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        /* This selection way
        jlist.addListSelectionListener(e -> {
          int i = 1;
          jta.setText("");
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
        });
        */
        // or this JButton way
        JButton jb = new JButton("OK");
        jb.addActionListener(this);
        /* This way without implements ActionListener
        jb.addActionListener(e -> {
          int i = 1;
          jta.setText("");
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
        });
        */
        jp.add(jl); jp.add(jlist);
        add("North", jp);
        add("Center", jta);
        add("South", jb);
        setSize(300,400);
        setVisible(true);
    }
    private JTextArea jta;
    private JList<String> jlist;
    public void actionPerformed(ActionEvent e) {
          int i = 1;
          jta.setText("");
          // get the list of selected Items.
          List<String> lst = jlist.getSelectedValuesList();
          jta.append("Your selections:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
    }
}
View attachment 2174
thank you so much. Can I have a question?
Ví dụ mình có 2 method: x, y. x chỉ có thể được gọi bởi Item Wednesday, y chỉ có thể được gọi bời Item Thursday. Liệu rằng có cách nào để khi mình chọn 2 Item kia thì sẽ in ra 2 method x, y chứ không phải là in ra Values ? Help me please
 

Joe

Thành viên VIP
21/1/13
2,969
1,310
113
Hope I understand you correctly. If not you have to try writing a piece of codes and show me your codes.
Java:
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
// Joe Nartca
public class ExampleJList extends JFrame {
    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        new ExampleJList();
    }
    public ExampleJList() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel jp = new JPanel();
        JLabel jl = new JLabel("Pick the day(s)");
        // declare TextArea
        jta = new JTextArea();
        String week[]= { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
        // declare JList with the String Array week
        jlist = new JList<>(week);
        // set model for MULTIPLE CHOICES
        jlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        /* This selection way */
        jlist.addListSelectionListener(e -> {
          runSelected("From SelectionListener");
        });
        //
        // or this JButton way
        JButton jb = new JButton("OK");
        jb.addActionListener(e -> {
          runSelected("From JButton");
        });
        jp.add(jl); jp.add(jlist);
        add("North", jp);
        add("Center", jta);
        add("South", jb);
        setSize(300,400);
        setVisible(true);
    }
    private JTextArea jta;
    private JList<String> jlist;
    public void runSelected(String msg) {
          jta.setText("");
          jta.append(msg+"\n");
          List<String> lst = jlist.getSelectedValuesList();
          if (msg.indexOf("JButton") > 0) methodX(lst);
          else methodY(lst);
    }
    private void methodY(List<String> lst) {
          int i = 1;
          jta.append("methodY:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
    }
    private void methodX(List<String> lst) {
          int i = 1;
          jta.append("methodX:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
    }
}
JlistExample_1.png

Another method is to embed the JButton as an item and when an item or JButton is selected (as ActionListener) methodX or methodY is invoked. However this technique is more complex than the method I show you above. It requires:
  • ListCellRenderer to be implemented as, for example, JButtonRenderer
  • array of JButtons
  • Selection or/and MouseListener
  • etc.
 
Sửa lần cuối:
  • Love
Reactions: Toantang2632000

Toantang2632000

New Member
18/5/20
11
1
3
Hà Nội
Hope I understand you correctly. If not you have to try writing a piece of codes and show me your codes.
Java:
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
// Joe Nartca
public class ExampleJList extends JFrame {
    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        new ExampleJList();
    }
    public ExampleJList() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel jp = new JPanel();
        JLabel jl = new JLabel("Pick the day(s)");
        // declare TextArea
        jta = new JTextArea();
        String week[]= { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
        // declare JList with the String Array week
        jlist = new JList<>(week);
        // set model for MULTIPLE CHOICES
        jlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        /* This selection way */
        jlist.addListSelectionListener(e -> {
          runSelected("From SelectionListener");
        });
        //
        // or this JButton way
        JButton jb = new JButton("OK");
        jb.addActionListener(e -> {
          runSelected("From JButton");
        });
        jp.add(jl); jp.add(jlist);
        add("North", jp);
        add("Center", jta);
        add("South", jb);
        setSize(300,400);
        setVisible(true);
    }
    private JTextArea jta;
    private JList<String> jlist;
    public void runSelected(String msg) {
          jta.setText("");
          jta.append(msg+"\n");
          List<String> lst = jlist.getSelectedValuesList();
          if (msg.indexOf("JButton") > 0) methodX(lst);
          else methodY(lst);
    }
    private void methodY(List<String> lst) {
          int i = 1;
          jta.append("methodY:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
    }
    private void methodX(List<String> lst) {
          int i = 1;
          jta.append("methodX:\n");
          for (String s:lst)
            jta.append((i++)+". :"+s+"\n");
    }
}
View attachment 2179

Another method is to embed the JButton as an item and when an item or JButton is selected (as ActionListener) methodX or methodY is invoked. However this technique is more complex than the method I show you above. It requires:
  • ListCellRenderer to be implemented as, for example, JButtonRenderer
  • array of JButtons
  • Selection or/and MouseListener
  • etc.
oh thank you so muchhhhhhh