Java – creates a list of entries and makes each entry clickable

I'm trying to create a UI with two panes

In the left pane, I display a list of files and the right pane displays the contents

Now, I want the file list in the left pane to look like a normal list However, when I click an entry in this list, the contents of a specific file should appear in the right pane

How can swing be used to achieve this goal?

Solution

Here, I made a short example. On the left is JList and on the right is jtextarea I use listselectionlistener to get item list changes Use layoutmanager for your convenience

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JListTest {

    private JList jList1;
    private JPanel jPanel1;
    private JTextArea jTextArea1;

    public JListtest() {
        initComponents();
    }

    private void initComponents() {
        JFrame f = new JFrame();
        jPanel1 = new JPanel();
        jList1 = new JList();
        jTextArea1 = new JTextArea();

        jList1.setModel(new AbstractListModel() {

            String[] strings = {"Item 1","Item 2"};

            @Override
            public int getSize() {
                return strings.length;
            }

            @Override
            public Object getElementAt(int i) {
                return strings[i];
            }
        });
        jList1.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);

        jPanel1.add(jList1);
        jPanel1.add(jTextArea1);
         f.setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
        f.add(jPanel1);
        f.pack();
        f.setVisible(true);
    }

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
        //set text on right here
        String s = (String) jList1.getSelectedValue();
        if (s.equals("Item 1")) {
            jTextArea1.setText("You clicked on list 1");
        }
        if (s.equals("Item 2")) {
            jTextArea1.setText("You clicked on list 2");
        }
    }

    public static void main(String args[]) {
        SwingUtilities.invokelater(new Runnable() {

            @Override
            public void run() {
                new JListtest();
            }
        });
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>