gpt4 book ai didi

java - 不使用 JButton 从 JList 获取值

转载 作者:行者123 更新时间:2023-12-02 03:34:12 26 4
gpt4 key购买 nike

我想通过使用 ActionListener 从 JList 获取值。当用户选择索引并且所选索引更新时,我想获取更新后的值。

如何在不按按钮的情况下做到这一点?我想将 ActionListener 添加到我的 JList。

最佳答案

How can i do it without pressing a button? I want to add ActionListener to my JList.

不,您确实不想向 JList“添加 ActionListener”,因为这是不允许的,因为 JList 没有 addActionListener(...) 方法,但您确实需要添加一个监听器,通过查找 JList tutorial 可以轻松找到哪个监听器或JList API 。在那里您会找到最好的选择,ListSelectionListener .

有用的资源:

例如:

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

@SuppressWarnings("serial")
public class ListListenerDemo extends JPanel {
private static final String[] LIST_DATA = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
private JList<String> list = new JList<>(LIST_DATA);

public ListListenerDemo() {
list.setVisibleRowCount(4);

// add the ListSelectionListener to our JList
list.addListSelectionListener(new MyListListener());

JScrollPane scrollPane = new JScrollPane(list);
add(scrollPane);
}

// here's our ListSelectionListener
private class MyListListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
JList<String> lst = (JList<String>) e.getSource();
String selection = lst.getSelectedValue();
if (selection != null) {
JOptionPane.showMessageDialog(list, selection, "Selected Item",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
}

private static void createAndShowGui() {
ListListenerDemo mainPanel = new ListListenerDemo();

JFrame frame = new JFrame("ListListenerDemo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

关于java - 不使用 JButton 从 JList 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com