Results 1 to 9 of 9
  1. #1
    alexiz is offline Member
    Join Date
    Dec 2014
    Posts
    8
    Rep Power
    0

    Post Help with accessing JList "properties"

    Hello everyone, I am fairly new to Java and I have probably the stupidest question anyone has seen on this forum but I just can't get it. I currently have some code using a JFrame. I am trying to access the items in a JList to save them in a TXT file. For this, I am using a "for" loop. The problem is, is that when I try to access the list items, I can't access them. The way I am trying to access the items is by using:

    Java Code:
    listRight.getModel().getSize();
    BUT, I can't seem to get this to work. I tried to place this for loop everywhere and I can't access it. I tried accessing it under "public class Window", "private JFrame frmPcPartBuilder", "public static void main(String[] args)", "public void Initialize()" and I can't seem to access the JList.

    I am sorry if this is really stupid to ask but any help would be appreciated. I have also provided my current working code to see if someone can direct me where to place my code. I basically have a save button that saves the list to a text file and the code I am trying to write is called by this button. Thanks again!

    Java Code:
    package com.cooksys.assessment;
    
    import java.awt.EventQueue;
    
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JList;
    import javax.swing.AbstractListModel;
    
    public class Window {
    
    	private JFrame frmPcPartBuilder;
    
    	/**
    	 * Launch the application. The main method is the entry point to a Java application. 
    	 * For this assessment, you shouldn't have to add anything to this.
    	 */
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					Window window = new Window();
    					window.frmPcPartBuilder.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
    
    	/**
    	 * Create the application. This is the constructor for this Window class.
    	 * All of the code here will be executed as soon as a Window object is made.
    	 */
    	public Window() {
    		initialize();
    	}
    
    	/**
    	 * Initialize the contents of the frame. This is where Window Builder
    	 * will generate its code.
    	 */
    	@SuppressWarnings({ "unchecked", "rawtypes", "serial" })
    	public void initialize() {
    		frmPcPartBuilder = new JFrame();
    		frmPcPartBuilder.setResizable(false);
    		frmPcPartBuilder.setTitle("PC Part Builder");
    		frmPcPartBuilder.setBounds(100, 100, 450, 600);
    		frmPcPartBuilder.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		//Creates new Menu Bar
    		JMenuBar menuBar = new JMenuBar();
    		frmPcPartBuilder.setJMenuBar(menuBar);
    		
    		/**
    		 * ---------START----------
    		 * Create File Menu and Menu Items
    		 */
    		JMenu mnFile = new JMenu("File");
    		menuBar.add(mnFile);
    		
    		JMenuItem mntmLoad = new JMenuItem("Load");
    		mntmLoad.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				//load();
    			}
    		});
    		mnFile.add(mntmLoad);
    		
    		JMenuItem mntmSave = new JMenuItem("Save");
    		mntmSave.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				//save();
    			}
    		});
    		mnFile.add(mntmSave);
    		
    		JMenuItem mntmExit = new JMenuItem("Exit");
    		mntmExit.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent arg0) {
    				System.exit(0);
    			}
    		});
    		mnFile.add(mntmExit);
    		/**
    		 * ----------END----------
    		 */
    		
    		frmPcPartBuilder.getContentPane().setLayout(null);
    
    		//New list "Left" and properties
    		final JList listLeft = new JList();
    		listLeft.setBounds(0, 0, 170, 551);
    		frmPcPartBuilder.getContentPane().add(listLeft);
    		listLeft.setModel(new AbstractListModel() {
    			String[] values = new String[] {"Case", "Motherboard", "CPU", "GPU", "PSU", "RAM", "HDD"};
    			public int getSize() {
    				return values.length;
    			}
    			public Object getElementAt(int index) {
    				return values[index];
    			}
    		});
    		
    		//New list "Right"
    		final JList listRight = new JList();
    		listRight.setBounds(274, 0, 170, 551);
    		frmPcPartBuilder.getContentPane().add(listRight);
    		
    		//New button "Add" and Event Handler
    		final DefaultListModel list = new DefaultListModel();
    		
    		JButton btnAdd = new JButton(">>");
    		btnAdd.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				list.addElement(listLeft.getSelectedValue());
    				listRight.setModel(list);
    			}
    		});
    		btnAdd.setBounds(192, 229, 59, 45);
    		frmPcPartBuilder.getContentPane().add(btnAdd);
    		
    		//New button "Remove" and Event Handler
    		JButton btnRemove = new JButton("<<");
    		btnRemove.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				list.removeElement(listRight.getSelectedValue());
    				listRight.setModel(list);
    			}
    		});
    		btnRemove.setBounds(192, 285, 59, 45);
    		frmPcPartBuilder.getContentPane().add(btnRemove);
    	}
    }

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: Help with accessing JList "properties"

    You have to read the documentation to understand how to use JList (and any other JDK class). The description of the class provides an example.

    So paste this in your browser and use it often.
    Java Platform SE 8

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,087
    Rep Power
    4

    Default Re: Help with accessing JList "properties"

    Your JList is declared on line 113 inside the method initialize. This means it's only accessible inside that method, and after the declaration.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,891
    Rep Power
    25

    Default Re: Help with accessing JList "properties"

    I can't seem to get this to work.
    If you are getting errors, please copy the full text and paste it here.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    alexiz is offline Member
    Join Date
    Dec 2014
    Posts
    8
    Rep Power
    0

    Post Re: Help with accessing JList "properties"

    Quote Originally Posted by Norm View Post
    If you are getting errors, please copy the full text and paste it here.
    Okay, so I got it to the point where it creates the XML file and it writes to it, but I want to know how to save the actual 'listRight" contents. At this point I only added "Hello" and "World" just to try to get it working. Now, I need a little help in adding the actual contents of the list. Here is my current code.

    Configuration.java
    Java Code:
    package com.cooksys.assessment;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    import javax.xml.bind.annotation.XmlAccessType;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
    		"component"
    })
    @XmlRootElement(name = "Configuration")
    public class Configuration {
    	
    	protected List<String> component;
    	
    	public List<String> getComponent() {
    		if(component == null) {
    			component = new ArrayList<String>();
    		}
    		return this.component;
    	}
    }
    Window.java
    Java Code:
    package com.cooksys.assessment;
    
    import java.awt.EventQueue;
    
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JList;
    import javax.swing.AbstractListModel;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    
    public class Window {
    
    	private JFrame frmPcPartBuilder;
    
    	/**
    	 * Launch the application. The main method is the entry point to a Java application. 
    	 * For this assessment, you shouldn't have to add anything to this.
    	 */
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					Window window = new Window();
    					window.frmPcPartBuilder.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
    
    	/**
    	 * Create the application. This is the constructor for this Window class.
    	 * All of the code here will be executed as soon as a Window object is made.
    	 */
    	public Window() {
    		initialize();
    	}
    	
    	public void save() throws Exception {
    		JAXBContext context = JAXBContext.newInstance(Configuration.class);
    		Marshaller marshaller = context.createMarshaller();
    		Configuration config = new Configuration();
    		File file = new File("save.xml");
    		List<String> list = config.getComponent();
    		list.add("Hello");
    		list.add("World");
    		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    		marshaller.marshal(config, file);
    	}
    
    	/**
    	 * Initialize the contents of the frame. This is where Window Builder
    	 * will generate its code.
    	 */
    	@SuppressWarnings({ "unchecked", "rawtypes", "serial" })
    	public void initialize() {
    		frmPcPartBuilder = new JFrame();
    		frmPcPartBuilder.setResizable(false);
    		frmPcPartBuilder.setTitle("PC Part Builder");
    		frmPcPartBuilder.setBounds(100, 100, 450, 600);
    		frmPcPartBuilder.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		//Creates new Menu Bar
    		JMenuBar menuBar = new JMenuBar();
    		frmPcPartBuilder.setJMenuBar(menuBar);
    		
    		/**
    		 * ---------START----------
    		 * Create File Menu and Menu Items
    		 */
    		JMenu mnFile = new JMenu("File");
    		menuBar.add(mnFile);
    		
    		JMenuItem mntmLoad = new JMenuItem("Load");
    		mntmLoad.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				//load();
    			}
    		});
    		mnFile.add(mntmLoad);
    		
    		JMenuItem mntmSave = new JMenuItem("Save");
    		mntmSave.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				try {
    					save();
    				} catch (Exception e1) {
    					// TODO Auto-generated catch block
    					e1.printStackTrace();
    				}
    			}
    		});
    		mnFile.add(mntmSave);
    		
    		JMenuItem mntmExit = new JMenuItem("Exit");
    		mntmExit.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent arg0) {
    				System.exit(0);
    			}
    		});
    		mnFile.add(mntmExit);
    		/**
    		 * ----------END----------
    		 */
    		
    		frmPcPartBuilder.getContentPane().setLayout(null);
    
    		//New list "Left" and properties
    		final JList listLeft = new JList();
    		listLeft.setBounds(0, 0, 170, 551);
    		frmPcPartBuilder.getContentPane().add(listLeft);
    		listLeft.setModel(new AbstractListModel() {
    			String[] values = new String[] {"Case", "Motherboard", "CPU", "GPU", "PSU", "RAM", "HDD"};
    			public int getSize() {
    				return values.length;
    			}
    			public Object getElementAt(int index) {
    				return values[index];
    			}
    		});
    		
    		//New list "Right"
    		final JList listRight = new JList();
    		listRight.setBounds(274, 0, 170, 551);
    		frmPcPartBuilder.getContentPane().add(listRight);
    		
    		//DefaultListModel created on the following line.
    		final DefaultListModel list = new DefaultListModel();
    		
    		//New button "Add" and Event Handler
    		JButton btnAdd = new JButton(">>");
    		btnAdd.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				list.addElement(listLeft.getSelectedValue());
    				listRight.setModel(list);
    			}
    		});
    		btnAdd.setBounds(192, 229, 59, 45);
    		frmPcPartBuilder.getContentPane().add(btnAdd);
    		
    		//New button "Remove" and Event Handler
    		JButton btnRemove = new JButton("<<");
    		btnRemove.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				list.removeElement(listRight.getSelectedValue());
    				listRight.setModel(list);
    			}
    		});
    		btnRemove.setBounds(192, 285, 59, 45);
    		frmPcPartBuilder.getContentPane().add(btnRemove);
    	}
    }


    All help is really appreciated.

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,891
    Rep Power
    25

    Default Re: Help with accessing JList "properties"

    The contents of the listRight list needs to be made available to the save() method so it can extract its contents to write to the file.
    If the listRight variable were defined at the class level then all the methods in the class could access it.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    alexiz is offline Member
    Join Date
    Dec 2014
    Posts
    8
    Rep Power
    0

    Post Re: Help with accessing JList "properties"

    Quote Originally Posted by Norm View Post
    The contents of the listRight list needs to be made available to the save() method so it can extract its contents to write to the file.
    If the listRight variable were defined at the class level then all the methods in the class could access it.
    Thank you so much! :)
    Here is what I have...

    Configuration.java
    Java Code:
    package com.cooksys.assessment;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    import javax.xml.bind.annotation.XmlAccessType;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
    		"component"
    })
    @XmlRootElement(name = "Configuration")
    public class Configuration {
    	
    	protected List<String> component;
    	
    	public List<String> getComponent() {
    		if(component == null) {
    			component = new ArrayList<String>();
    		}
    		return this.component;
    	}
    }



    Window.java
    Java Code:
    package com.cooksys.assessment;
    
    import java.awt.EventQueue;
    
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JList;
    import javax.swing.AbstractListModel;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    
    public class Window {
    
    	private JFrame frmPcPartBuilder;
    
    	/**
    	 * Launch the application. The main method is the entry point to a Java application. 
    	 * For this assessment, you shouldn't have to add anything to this.
    	 */
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					Window window = new Window();
    					window.frmPcPartBuilder.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
    
    	/**
    	 * Create the application. This is the constructor for this Window class.
    	 * All of the code here will be executed as soon as a Window object is made.
    	 */
    	public Window() {
    		initialize();
    	}
    	
    	public void load() {
    		
    	}
    	
    	public void save() throws Exception {
    		JAXBContext context = JAXBContext.newInstance(Configuration.class);
    		Marshaller marshaller = context.createMarshaller();
    		Configuration config = new Configuration();
    		File file = new File("save.xml");
    		List<String> printList = config.getComponent();
    		for(int i = 0;i < list.getSize();i++) {
    			printList.add((String) list.getElementAt(i));
    		}
    		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    		marshaller.marshal(config, file);
    	}
    
    	/**
    	 * Initialize the contents of the frame. This is where Window Builder
    	 * will generate its code.
    	 */
    	@SuppressWarnings({ "unchecked", "rawtypes", "serial" })
    	public void initialize() {
    		frmPcPartBuilder = new JFrame();
    		frmPcPartBuilder.setResizable(false);
    		frmPcPartBuilder.setTitle("PC Part Builder");
    		frmPcPartBuilder.setBounds(100, 100, 450, 600);
    		frmPcPartBuilder.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		//Creates new Menu Bar
    		JMenuBar menuBar = new JMenuBar();
    		frmPcPartBuilder.setJMenuBar(menuBar);
    		
    		/**
    		 * ---------START----------
    		 * Create File Menu and Menu Items
    		 */
    		JMenu mnFile = new JMenu("File");
    		menuBar.add(mnFile);
    		
    		JMenuItem mntmLoad = new JMenuItem("Load");
    		mntmLoad.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				//load();
    			}
    		});
    		mnFile.add(mntmLoad);
    		
    		JMenuItem mntmSave = new JMenuItem("Save");
    		mntmSave.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				try {
    					save();
    				} catch (Exception e1) {
    					e1.printStackTrace();
    				}
    			}
    		});
    		mnFile.add(mntmSave);
    		
    		JMenuItem mntmExit = new JMenuItem("Exit");
    		mntmExit.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent arg0) {
    				System.exit(0);
    			}
    		});
    		mnFile.add(mntmExit);
    		/**
    		 * ----------END----------
    		 */
    		
    		frmPcPartBuilder.getContentPane().setLayout(null);
    
    		//New list "Left" and properties
    		final JList listLeft = new JList();
    		listLeft.setBounds(0, 0, 170, 551);
    		frmPcPartBuilder.getContentPane().add(listLeft);
    		listLeft.setModel(new AbstractListModel() {
    			String[] values = new String[] {"Case", "Motherboard", "CPU", "GPU", "PSU", "RAM", "HDD"};
    			public int getSize() {
    				return values.length;
    			}
    			public Object getElementAt(int index) {
    				return values[index];
    			}
    		});
    		
    		//New list "Right"
    		final JList listRight = new JList();
    		listRight.setBounds(274, 0, 170, 551);
    		frmPcPartBuilder.getContentPane().add(listRight);
    		
    		//DefaultListModel created on the following line.
    		
    		//New button "Add" and Event Handler
    		JButton btnAdd = new JButton(">>");
    		btnAdd.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				list.addElement(listLeft.getSelectedValue());
    				listRight.setModel(list);
    			}
    		});
    		btnAdd.setBounds(192, 229, 59, 45);
    		frmPcPartBuilder.getContentPane().add(btnAdd);
    		
    		//New button "Remove" and Event Handler
    		JButton btnRemove = new JButton("<<");
    		btnRemove.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				list.removeElement(listRight.getSelectedValue());
    				listRight.setModel(list);
    			}
    		});
    		btnRemove.setBounds(192, 285, 59, 45);
    		frmPcPartBuilder.getContentPane().add(btnRemove);
    	}
    	final DefaultListModel list = new DefaultListModel();
    }

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,891
    Rep Power
    25

    Default Re: Help with accessing JList "properties"

    Here is what I have...
    Is it working now?
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    alexiz is offline Member
    Join Date
    Dec 2014
    Posts
    8
    Rep Power
    0

    Default Re: Help with accessing JList "properties"

    Quote Originally Posted by Norm View Post
    Is it working now?
    Yes! Thank you so much for your help! :)

    Now, I want to "load" the parts from the XML file and load them into the JList on the right. Is there any way I can get help with that? I did find a link that explained it a little but couldn't get it correct after trying for a while. Here is the link.

    Java to XML, XML to Java (Marshalling and Unmarshalling) | lstierneyltd

Similar Threads

  1. Replies: 0
    Last Post: 12-07-2012, 09:29 AM
  2. Replies: 3
    Last Post: 10-30-2012, 04:06 PM
  3. Replies: 3
    Last Post: 01-18-2012, 06:51 PM
  4. Replies: 0
    Last Post: 07-28-2009, 07:45 PM
  5. Replies: 1
    Last Post: 10-20-2008, 08:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •