[英]How to build a new list containing all entries from existing list AND a copy of each entry with one field modified?
[英]Create a list of entries and make each entry clickable
我正在嘗試創建一個有兩個窗格的UI。
在左側窗格中,我顯示文件列表,右窗格顯示內容。
現在,我希望左窗格中的文件列表看起來像普通列表。 但是,當我單擊此列表中的條目時,特定文件的內容應顯示在右側窗格中。
如何使用Swing實現這一目標?
在這里,我做了一個簡短的例子,左邊是JList
,右邊是JTextArea
。 我使用ListSelectionListener
來獲取項目列表更改。 根據您的方便使用LayoutManager
。
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListTest {
private JList jList1;
private JPanel jPanel1;
private JTextArea jTextArea1;
public JListTest() {
initComponents();
}
private void initComponents() {
JFrame f = new JFrame();
jPanel1 = new JPanel();
jList1 = new JList();
jTextArea1 = new JTextArea();
jList1.setModel(new AbstractListModel() {
String[] strings = {"Item 1", "Item 2"};
@Override
public int getSize() {
return strings.length;
}
@Override
public Object getElementAt(int i) {
return strings[i];
}
});
jList1.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jPanel1.add(jList1);
jPanel1.add(jTextArea1);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.add(jPanel1);
f.pack();
f.setVisible(true);
}
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
//set text on right here
String s = (String) jList1.getSelectedValue();
if (s.equals("Item 1")) {
jTextArea1.setText("You clicked on list 1");
}
if (s.equals("Item 2")) {
jTextArea1.setText("You clicked on list 2");
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JListTest();
}
});
}
}
您可能想看看這個JTree示例 。
一些例子供參考:
FileBrowser
使用左側的JTree
和右側的嵌套詳細信息面板。
ImageDisplay
在左側嵌入自定義JFileChooser
並在右側顯示可滾動圖像。
CheckTable
顯示JTable
,右側DisplayPanel
。
使用JList.addListSelectionListener(ListSelectionListener)
。
有關更多示例,請參見如何編寫列表選擇偵聽器 。
首先,你還沒有嘗試過,對吧? Swing幾乎完成了與listeneres相關的所有輸入。 檢查鼠標監聽器,或調整下面的awnser
https://stackoverflow.com/a/4344762/258418
為了完整性,我在這里引用它:
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
JList list = (JList)evt.getSource();
if (evt.getClickCount() == 2) {
int index = list.locationToIndex(evt.getPoint());
} else if (evt.getClickCount() == 3) { // Triple-click
int index = list.locationToIndex(evt.getPoint());
}
}
});
我相信你也可以點擊一下,如果不寫評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.