Here is the ListSelectionListener from my JListExample that gets the name from the list, requests the object associated with that list and then passes it to the second form.
private class SelectionListener implements ListSelectionListener{ @Override public void valueChanged(ListSelectionEvent e) { if (list.getSelectedIndex() != -1) { //No selection, disable fire button. String name=list.getSelectedValue(); Item i = iList.getItem(name); SecondForm second = new SecondForm(i); } }
Here is the code for the second form. Note especially the Constructor
package com.spconger.JListExample; import java.awt.FlowLayout; import java.awt.LayoutManager; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SecondForm { Item i; //the constructor takes in an object of the type Item public SecondForm(Item i){ this.i=i; createJFrame(); } private void createJFrame(){ JFrame frame= new JFrame(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setBounds(200,200,200,200); frame.add(createPanel()); frame.setVisible(true); } private JPanel createPanel(){ JPanel panel = new JPanel(); panel.setLayout(new FlowLayout(FlowLayout.LEFT)); //the labels get their value from the Item object passed in JLabel label1=new JLabel(i.getName()); JLabel label2 = new JLabel(Double.toString(i.getPrice())); panel.add(label1); panel.add(label2); return panel; } }
No comments:
Post a Comment