Results 1 to 13 of 13
Like Tree1Likes
  • 1 Post By SurfMan

Thread: Help saving and loading XML from/into JList

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

    Post Help saving and loading XML from/into JList

    Hello everyone, I am new to this forum and the reason being is because I am trying to get more into Java. I have a program where I have two JLists and one is filled with "computer parts" and the other is empty. I add and remove parts in the empty JList with two buttons. I am trying to "save" and "load" the list in the JList that I add items to. Basically I want to save the list to an XML file and load the list from the XML file into the same JList. The only issue is, I have never worked with XML before. Is there any way someone can help me with this and explain a little bit so I can learn as well? Thank you in advance. I will provide my code and GUI.

    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.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    
    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);
    	}
    }
    Help saving and loading XML from/into JList-program.png

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Help saving and loading XML from/into JList

    Explain what exactly? Surely you've typed "java xml parsing" into google and got plenty of results. What don't you understand?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

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

    Default Re: Help saving and loading XML from/into JList

    Quote Originally Posted by gimbal2 View Post
    Explain what exactly? Surely you've typed "java xml parsing" into google and got plenty of results. What don't you understand?
    Well, I did find how to do this using JAXB but I am not getting it to work properly. For testing purposes, I am adding strings to an array manually and trying to save the items in the array to the XML. I get the XML file created but it is empty. Here is what I have.

    Java Code:
    ArrayList<String> items = new ArrayList<String>();
    	
    	public void save() {
    		items.add("Hello");
    		items.add("World");
    		
    		try {
    			File file = new File("save.xml");
    			JAXBContext jaxbContext = JAXBContext.newInstance();
    			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    			
    			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    			
    			jaxbMarshaller.marshal(items, file);
    		}
    		catch(JAXBException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public void load() {
    		
    	}

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Help saving and loading XML from/into JList

    Well try to answer this: in this example you create where you have only two plain String objects, what XML could possible be generated?

    Java Code:
    <?xml version="1.0">
    <?>
      <?>hello</?>
      <?>world</?>
    </?>
    JAXB is for emitting and parsing full objects with actual properties.

    Google: "Java simple jaxb example"
    First hit: JAXB hello world example
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

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

    Default Re: Help saving and loading XML from/into JList

    Quote Originally Posted by gimbal2 View Post
    Well try to answer this: in this example you create where you have only two plain String objects, what XML could possible be generated?

    Java Code:
    <?xml version="1.0">
    <?>
      <?>hello</?>
      <?>world</?>
    </?>
    JAXB is for emitting and parsing full objects with actual properties.

    Google: "Java simple jaxb example"
    First hit: JAXB hello world example
    I see.. That was the link I found and kind of followed it.. So what would be the easiest way to just save a simple list of strings from my JList?

  6. #6
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Help saving and loading XML from/into JList

    Quote Originally Posted by alexiz View Post
    I see.. That was the link I found and kind of followed it.. So what would be the easiest way to just save a simple list of strings from my JList?
    A plain text file? Each line is an item. Why make it more complicated than necessary?

    Forum service:
    http://docs.oracle.com/javase/7/docs...set.Charset%29
    Last edited by SurfMan; 12-15-2014 at 11:21 PM.
    gimbal2 likes this.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

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

    Default Re: Help saving and loading XML from/into JList

    Reason is because I was tasked to make it an XML file which I have never worked with.

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Help saving and loading XML from/into JList

    Quote Originally Posted by alexiz View Post
    Reason is because I was tasked to make it an XML file which I have never worked with.
    Well, that is not the easiest but it explains the requirement. Have you every worked with HTML? XML is similar but has some subtle differences. And are you required to use an XML parser? For something simple you could just process the tags yourself. If you want more detailed processing then you can investigate the XML parsers. Since you are unfamiliar with XML, check out this link.

    XML Tutorial

    For parsing XML, check out the Java tutorials.

    Trail: Java API for XML Processing (JAXP) (The Java Tutorials)

    Regards,
    Jim
    Last edited by jim829; 12-16-2014 at 01:23 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Help saving and loading XML from/into JList

    Of course if its only about CREATING an XML file, a good old PrintStream works just as well. Who cares that it represents XML data - its also still only a text file.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  10. #10
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Help saving and loading XML from/into JList

    Quote Originally Posted by gimbal2 View Post
    Of course if its only about CREATING an XML file, a good old PrintStream works just as well. Who cares that it represents XML data - its also still only a text file.
    If it's about learning how to handle XML then go the official way with Documents, SAX, Transformers, etc. You'll most likely end up with a utility class called XMLUtils that contains static methods to do the repeatable stuff:

    Java Code:
    public final class XMLUtils {
       public static Document createEmptyDocument() {
          ...
       } 
    
       public static void writeDocumentToFile( Document d, File f) {
          ...
       }
    }
    StringBuilders and PrintStreams for writing XML are the last resort. *shudder*. You should be slapped for that.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Help saving and loading XML from/into JList

    Hey, it works perfectly fine for emitting small XML messages. Of course for large XML streams its a really poor choice. But its not so black & white that you need to go down the path of wrist slapping, surfbiatch.

    I'd think that if you have to learn how to work with XML you'd focus more on the parsing aspect of it.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Help saving and loading XML from/into JList

    I can feel the need for the construction below. I'm not afraid to implement this in any app I develop. You can't beat this in LoC when using the "traditional" way of Documents and Transformers.
    Java Code:
    final String MESSAGE_TEMPLATE = "<?xml version=\"1.0\"?><message recipient=\"{0}\"><text>{1}</text></message>";
    ...
    XMLUtils.sendMessage(MessageFormat.format(MESSAGE_TEMPLATE, "gimbal2", "It's a slap on the cheek, not on the wrist"));
    However, for *learning* proper XML handling, nothing beats creating a Document and a SaxParser.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Help saving and loading XML from/into JList

    Quote Originally Posted by SurfMan View Post
    However, for *learning* proper XML handling, nothing beats creating a Document and a SaxParser.
    Agreed; and you start with XML parsing to get a feel for what XML is and building an object model, before you think about emitting a model to an XML file which in most circumstances is pretty much a one line of code kind of deal that doesn't teach you anything.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. JTables - Saving Loading
    By itsBenMason in forum New To Java
    Replies: 1
    Last Post: 09-06-2014, 01:21 AM
  2. problem with loading/saving hashmaps
    By S.Mason in forum New To Java
    Replies: 3
    Last Post: 07-08-2012, 03:53 AM
  3. saving / loading a file - TicTacToe
    By Herah in forum New To Java
    Replies: 0
    Last Post: 12-01-2011, 02:59 AM
  4. Saving from, and loading to an array.
    By VisionIncision in forum New To Java
    Replies: 4
    Last Post: 11-23-2010, 09:47 AM
  5. Saving and loading information
    By applewood13 in forum New To Java
    Replies: 1
    Last Post: 09-30-2010, 05:29 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
  •