Solved

JDialogs content doesn't update, using StringBuilder

Posted on 2008-10-29
7
579 Views
Last Modified: 2013-11-23
Hi,

Im new with Java and I have a problem with using StringBuilder. I have Java GUI (Recipebook) where user can add, remove and list recipes. All works fine except the listing (JTextArea with added text from StringBuilder). It works the first time but when I e.g add new recipe and want to list all recipes (including the new one) my listing still shows the old list without last added recipe. I need to close my application before the changes shows in list.

My question is: How I can "update" my list so it will show the changes made instantly?


Here's the actionListener:

class RecipeList implements ActionListener {
            
            public void actionPerformed(java.awt.event.ActionEvent e) {
                  
                listDialog.setVisible(true);
                listDialog.validate();
            }
}


Here's ListDialog Class:

public class ListDialog extends JDialog {
      
      private static final long serialVersionUID = 1L;
      private JScrollPane scrollPane1;
      private JTextArea area;
      
      public ListDialog(Frame parentFrame) {
            
            super(parentFrame);
            
            setTitle("Test Dialog");
            setSize(350, 400);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);

            JPanel topPanel = new JPanel();
            topPanel.setLayout(new BorderLayout());
            getContentPane().add(topPanel);

            CreateTopPane(topPanel);
            
      }
      
      public void CreateTopPane( JPanel topPanel ) {
            
            area = new JTextArea();
            area.setEditable(false);
            
            BuildList();

            // Create the scrolling pane for the text area
            scrollPane1 = new JScrollPane();
            scrollPane1.getViewport().add( area );
            topPanel.add( scrollPane1, BorderLayout.CENTER );
            
      }
      
        //Parse Xml-file (DOM) and save in StringBuilder

      public void BuildList() {
            
            try {
                  
                  BufferedReader br = new BufferedReader(new FileReader("TestDOMXML4.xml"));
                  StringBuilder sb = new StringBuilder();
                  
                  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                  DocumentBuilder loader = factory.newDocumentBuilder();
                  Document doc = loader.parse("TestDOMXML4.xml");
                  
                  doc.getDocumentElement().normalize();
                  
                  NodeList listOfRecipes = doc.getElementsByTagName("recipe");
                  
                  
                  for(int i=0; i < listOfRecipes.getLength(); i++) {
                        
                        Node firstRecipeNode = listOfRecipes.item(i);
                        if (firstRecipeNode.getNodeType() == Node.ELEMENT_NODE) {
                              
                              Element firstRecipeElement = (Element)firstRecipeNode;
                              
                              NodeList nameList = firstRecipeElement.getElementsByTagName("name");
                              Element nameElement = (Element)nameList.item(0);
                              
                              NodeList textNameList = nameElement.getChildNodes();
                              String name = textNameList.item(0).getNodeValue().trim();
                              sb.append("Nimi: "+name+"\n");
                              
                              NodeList categoryList = firstRecipeElement.getElementsByTagName("category");
                              Element categoryElement = (Element)categoryList.item(0);
                              
                              NodeList textCategoryList = categoryElement.getChildNodes();
                              String category = textCategoryList.item(0).getNodeValue().trim();
                              sb.append("Kategoria: "+category+"\n");
                              
                              NodeList preparationList =
firstRecipeElement.getElementsByTagName("preparation");
                              Element preparationElement = (Element)preparationList.item(0);
                              
                              NodeList textPreparationList = preparationElement.getChildNodes();
                              String prep = textPreparationList.item(0).getNodeValue().trim();
                              sb.append("Ohje: "+prep+"\n\n");
                        }
                  }
                  
                  br.close();

                  area.append(sb.toString());
                  
            }
            
            catch (Exception e) {
              
                  System.out.println(e.getMessage());
          }
            
      }

}
0
Comment
Question by:Samsara82
  • 4
  • 2
7 Comments
 

Author Comment

by:Samsara82
ID: 22839141
Points increased.
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 22839217
>>>                   area.append(sb.toString());

I never did it that way.
I always practise:

String newText = ......................;
 String s = area.getText();
 area.setText(s + newText);

But .....................................................
If you want the additions listed top-down, it's better to set the first text:

area.setText("<HTML><CENTER>" + firstText;

and subsequently:

area.setText(area.getText() + "<BR>" + newText);

;JOOP!
0
 

Author Comment

by:Samsara82
ID: 22839454
Thanks for the answer sciuriware,

I changed

area.append(sb.toString());

to your first solution

String newText = ......................;
 String s = area.getText();
 area.setText(s + newText);

It's working as the same as area.append(sb.toString());

Im not quite sure what is this firstText in area.setText("<HTML><CENTER>" + firstText); What String should it contain?

But still, this doesn't solve my original problem. If I list all recipes, close my listing dialog, add new recipe and open up my listing dialog again, it still shows the old list.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 24

Assisted Solution

by:sciuriware
sciuriware earned 200 total points
ID: 22839843
>>> Im not quite sure what is this firstText in area.setText("<HTML><CENTER>" + firstText); What String should it contain?

A JTextArea can handle HTML text, therefore the first text is preceeded by "<HTML>".


I get the impression that everything works, but that your JTextArea doesn't
get a chance to be updated.
That happens when you do all your work above on the event thread.

When an action is started from a button, you MUST put all lengthy operations
in a separate Thread or you get the problem you have.

;JOOP!
0
 

Author Comment

by:Samsara82
ID: 22846161
Thanks again, I changed my code to this:

//Main GUI

class RecipeList implements ActionListener {
           
            public void actionPerformed(java.awt.event.ActionEvent e) {
                 
                listDialog.setVisible(true);
                listDialog.validate();
            }
}


//ListDialog class

public class ListDialog extends JDialog implements Runnable {
      
      private static final long serialVersionUID = 1L;
      private JScrollPane scroll;
      private JTextArea area;
      
      
      public ListDialog(Frame parentFrame) {
                  
            super(parentFrame);
                  
            setTitle("List Recipes");
            setSize(350, 400);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);

            JPanel topPanel = new JPanel();
            topPanel.setLayout(new BorderLayout());
            getContentPane().add(topPanel);
                  
            area = new JTextArea();
            area.setEditable(false);

            scroll = new JScrollPane();
            //scroll.add(area);
            scroll.getViewport().add( area );
            topPanel.add(scroll);
            
            new Thread(this).start();
            
      }
            
      public void run() {
                  
            try {
                        
                  BufferedReader br = new BufferedReader(new FileReader("TestDOMXML4.xml"));
                  StringBuilder sb = new StringBuilder();
                  
                  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();                        DocumentBuilder loader = factory.newDocumentBuilder();
                  Document doc = loader.parse("TestDOMXML4.xml");
                        
                  doc.getDocumentElement().normalize();
                        
                  NodeList listOfRecipes = doc.getElementsByTagName("recipe");
                        
                        
                  for(int i=0; i < listOfRecipes.getLength(); i++) {
                              
                        Node firstRecipeNode = listOfRecipes.item(i);
                        
                        if (firstRecipeNode.getNodeType() == Node.ELEMENT_NODE) {
                                    
                              Element firstRecipeElement = (Element)firstRecipeNode;
                                    
                              NodeList nameList = firstRecipeElement.getElementsByTagName("name");
                              Element nameElement = (Element)nameList.item(0);
                                    
                              NodeList textNameList = nameElement.getChildNodes();
                              String name = textNameList.item(0).getNodeValue().trim();
                              sb.append("Nimi: "+name+"\n");
                                    
                              NodeList categoryList = firstRecipeElement.getElementsByTagName("category");
                              Element categoryElement = (Element)categoryList.item(0);
                                    
                              NodeList textCategoryList = categoryElement.getChildNodes();
                              String category = textCategoryList.item(0).getNodeValue().trim();
                              sb.append("Kategoria: "+category+"\n");
                                    
                              NodeList preparationList = firstRecipeElement.getElementsByTagName("preparation");
                              Element preparationElement = (Element)preparationList.item(0);
                                    
                              NodeList textPreparationList = preparationElement.getChildNodes();
                              String prep = textPreparationList.item(0).getNodeValue().trim();
                              sb.append("Ohje: "+prep+"\n\n");
                        }
                  }
                        
                  br.close();
                  
                  area.append(sb.toString());
            
            }
                  
            catch (Exception e) {
                  
                  System.out.println(e.getMessage());
            }
                  
      }
}


But still..doesn't work :(

Can you suggest something that could be wrong? I have tested add/remove methods, these methods change my xml-file instantly, I just can't show these changes in my listing.
0
 

Accepted Solution

by:
Samsara82 earned 0 total points
ID: 22863621
I solve the problem myself. It was quite easy actually..At original GUI I made new object of JDialog in GUI's constructor. In the solution I moved that to the actionlistener

class RecipeList implements ActionListener {
           
            public void actionPerformed(java.awt.event.ActionEvent e) {
               
                listDialog = new ListDialog(frame);
                listDialog.setVisible(true);

            }
}

It's working now and im happy :)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now