简体   繁体   English

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

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

I'm trying to add an actionListener to a JList, so whenever a user click a value in the JList , it will just println the value. 我正在尝试将actionListener添加到JList中,因此,每当用户单击JList中的值时,它都将println该值。

Here's the code 这是代码

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);


    }

}

Here's the result of the codes 这是代码的结果

在此处输入图片说明

So how do I add an action Listener to the JList? 那么如何将动作侦听器添加到JList?

I'm trying to add an actionListener to a JList, 我正在尝试将actionListener添加到JList中,

You can't, it doesn't have ActionListener support 您不能,它没有ActionListener支持

so whenever a user click a value in the JList , it will just println the value. 因此,每当用户单击JList中的值时,它将只打印该值。

Use a ListSelectionListener instead 改用ListSelectionListener

Take a look at How to Use Lists and How to Write a List Selection Listener for more details 看一看如何使用列表如何编写列表选择监听器以了解更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM