我坚持使用Jlist,从来没有想过Jlist会这么复杂。
用鼠标左键单击Jlist项目,我想要执行一些操作。我知道我需要动作监听器,但我不能让它工作。
在我的特殊情况下,JList中有.sql文件的保存路径。当我单击JList中的项目时,我想从该文件中读取并将其保存到JTextArea。
也许我在代码中把监听器放在了错误的位置?还是我的代码写错了?
型号名称=型号
JList名称= SQLScriptList
Jtextarea名称= SQLEditor
使用此代码,我尝试将列表中的项保存到特定的标签或文本框中,以查看操作是否有效。
//Copy from LIST to TextArea
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
String selectedItem = (String) SQLScriptList.getSelectedValue();
// add selectedItem to your second list.
DefaultListModel model = (DefaultListModel) SQLScriptList.getModel();
if (model == null) {
//model = new DefaultListModel();
SQLScriptList.setModel(model);
}
model.addElement(selectedItem);
}
SQLScriptList.addMouseListener(mouseListener);
}
//list.addMouseListener(mouseListener);
};已解决
以下是在我的案例中起作用的解决方案:
private void SQLScriptListMouseClicked(java.awt.event.MouseEvent evt) {
JList list = (JList) evt.getSource();
if (evt.getClickCount() == 2) {
int index = list.locationToIndex(evt.getPoint()); //GET INDEX 0,1,2,3
try {
FileReader reader = new FileReader(files[index]);
SQLEditor.read(reader, files[index]); //Object of JTextArea
} catch (Exception e) {
e.printStackTrace();
}
}
} 发布于 2018-06-15 22:59:15
当我单击JList中的项目时,我想从该文件中读取并将其保存到JTextArea。
通常,这不是通过单击一次鼠标就能完成的。
通常,当用户执行以下操作时,将调用操作:
对于这种类型的处理,请查看List Action,它允许您提供在上述任何一种情况下要调用的Action。
否则,您应该使用MouseListener,而不是上面注释中建议的ListSelectionListener,因为用户应该能够使用向下/向上箭头键在列表中导航,而不会导致调用操作。请阅读How to Write a MouseListener上的Swing教程中的一节以获取工作示例。
https://stackoverflow.com/questions/50874846
复制相似问题