所以,我想要的是,当选择JList
项时,运行另一部分代码。但我的问题是,如何为特定的MouseListeners
项实施JList
?
这是我的代码:
public void launchFrame() {
String selection1 = "";
String[]mainContents = {"Vehicles","Bikes/Bicycles","Boats","Houses","Businesses","Objects","Jobs","Ranks","Licenses"};
String[]selectionVehicles = {};
String[]selectionBikesBicycles = {};
String[]selectionBoats = {};
String[]selectionHouses = {};
String[]selectionBusinesses = {};
String[]selectionObjects = {};
String[]selectionJobs = {};
String[]selectionRanks = {};
String[]selectionLicenses = {};
JFrame f = new JFrame("MTG SAMP Server Reference");
JList listAll = new JList(mainContents);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.pack();
f.setSize(1200, 800);
f.setLocationRelativeTo(null);
f.add(listAll);
listAll.setSize(250, 250);
listAll.setLocation(50, 50);
switch (selection1) {
case "Vehicles":
JList listVehicles = new JList(mainContents);
f.add(listVehicles);
listVehicles.setSize(250, 250);
listVehicles.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
case "Bikes/Bicycles":
JList listBikesBicycles = new JList(mainContents);
f.add(listBikesBicycles);
listBikesBicycles.setSize(250, 250);
listBikesBicycles.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
case "Boats":
JList listBoats = new JList(mainContents);
f.add(listBoats);
listBoats.setSize(250, 250);
listBoats.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
case "Houses":
JList listHouses = new JList(mainContents);
f.add(listHouses);
listHouses.setSize(250, 250);
listHouses.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
case "Businesses":
JList listBusinesses = new JList(mainContents);
f.add(listBusinesses);
listBusinesses.setSize(250, 250);
listBusinesses.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
case "Objects":
JList listObjects = new JList(mainContents);
f.add(listObjects);
listObjects.setSize(250, 250);
listObjects.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
case "Jobs":
JList listJobs = new JList(mainContents);
f.add(listJobs);
listJobs.setSize(250, 250);
listJobs.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
case "Ranks":
JList listRanks = new JList(mainContents);
f.add(listRanks);
listRanks.setSize(250, 250);
listRanks.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
case "Licenses":
JList listLicenses = new JList(mainContents);
f.add(listLicenses);
listLicenses.setSize(250, 250);
listLicenses.setLocation(350, 50);
f.repaint();
f.revalidate();
break;
}
Container contentPaneMain = f.getContentPane();
contentPaneMain.add(new MTGSAMPServerReference());
}
如何将MouseListeners
添加到JList
项目,“车辆”,“自行车/自行车”,“船只”,“房屋”,“商家”,“物品”,“工作“,”排名“和”许可“?
答案 0 :(得分:4)
如果您希望在选择更改时发生某些事情,则不需要MouseListener,而是ListSelectionListener
。它不仅是正确的抽象,而是记住选择可以在不使用鼠标的情况下改变。现在大多数电脑都有键盘。
Swing tutorial中描述了如何使用它。
在收听者中,获取所选元素,并采取相应行动。