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

我的未来我决定 提交于 2019-12-13 07:25:05

问题


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.

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?


回答1:


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

You can't, it doesn't have ActionListener support

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

Use a ListSelectionListener instead

Take a look at How to Use Lists and How to Write a List Selection Listener for more details



来源:https://stackoverflow.com/questions/31239605/how-do-i-add-an-action-listener-to-a-jlist-in-a-proper-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!