所以,我想要的JList是选择一个项目时要运行的另一段代码。但是我的问题是,如何MouseListeners对特定JList项目实施?
JList
MouseListeners
这是我的代码:
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“车辆”,“自行车/自行车”,“船”,“房屋”,“企业”,“对象”,“工作”,“等级”和“许可证”项中?
如果您希望在选择更改时发生某些事情,则不希望使用MouseListener,而希望使用ListSelectionListener。它不仅是正确的抽象,而且请记住,不使用鼠标就可以更改选择。如今,大多数计算机都配有键盘。
ListSelectionListener
Swing教程中描述了如何使用它。
在您的侦听器内部,获取选定的元素,然后采取相应的行动。