如何以正确的方式将动作侦听器添加到 JList?

How do i add an action listener to a JList in a proper way?

我正在尝试向 JList 添加一个 actionListener,因此每当用户单击 JList 中的一个值时,它只会打印该值。

这是代码

public class FontProgram {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        JFrame mainFrame = new JFrame("Fonts Frame");
        JPanel panel = new JPanel(new BorderLayout());

        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames = e.getAvailableFontFamilyNames();




        JComboBox fontbox = new JComboBox(fontNames);

        JList fontList = new JList(fontNames);
        JButton button = new JButton("Submit");

        JScrollPane scrollPane = new JScrollPane();

        scrollPane.setViewportView(fontList);

        fontList.addListSelectionListener(new SharedListSelectionHandler());
        panel.add(fontbox, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(button, BorderLayout.SOUTH);

        mainFrame.add(panel);
        mainFrame.setVisible(true);
        mainFrame.setSize(250, 250);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }

}

这是代码的结果

那么如何向 JList 添加动作侦听器?

I'm trying to add an actionListener to a JList,

你不能,它没有 ActionListener 支持

so whenever a user click a value in the JList , it will just println the value.

改用ListSelectionListener

查看 How to Use Lists and How to Write a List Selection Listener 了解更多详情