问题
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