Results 1 to 5 of 5
Like Tree1Likes
  • 1 Post By Fubarable

Thread: How to update the contents of a JTextArea

  1. #1
    Reptar693 is offline Member
    Join Date
    Mar 2012
    Posts
    6
    Rep Power
    0

    Default How to update the contents of a JTextArea

    I am trying to create a utility program that helps the user organize an external hardrive

    So far i have 3 classes , A main class, a GUI class, and a class that generates a JTree(for the files)

    What i want to happen is that when you select a file that appears in the tree the filename would appear on the JTextArea and it would change if you selected a different file

    Ive added a TreeSelectionListener and it works fine the problem is how do i get it to appear on the JTextAre

    Here's the Code

    Here's the main class
    XML Code:
    <code>
    public class Organizer {
    
        
        public static void main(String[] args) throws Exception {
            
           
            HomeWindow HM= new HomeWindow();
            
            HM.HomeWindowMain();
           
        }
    
       
    }
    
    </code>
    Here's the GUI class
    XML Code:
    <code>
    
    package organizer;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.io.File;
    import java.sql.*;
    import java.util.ArrayList;
    import javax.swing.*;
    
    
    
    /**
     *
     * @author
     */
    public class HomeWindow implements ActionListener, ItemListener {
       
        
           
        public void HomeWindowMain()
        {
        //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            SwingUtilities.invokeLater(new Runnable() {//This code is constant, it is important that the GUI is 
                @Override                              //executed using this method so that the GUI 
                public void run() {                    //is 'thread-safe'.
                    HomeStart();                        //:)
                }
            });
            
        }
        
        
     public static Connection getConnection() throws Exception 
          {
             Connection conn;                                               // Connection Instance
           String driver = "org.apache.derby.jdbc.ClientDriver";            //driver url
           String connectionURL = "jdbc:derby://localhost:1527/Organizer";  // connection url
           String Username= "Vince_Tiu";                                    //Username
           String Password= "v930906t";                                     //password
           Class.forName(driver);                                           //Finds a database driver
           conn= DriverManager.getConnection(connectionURL,Username,Password);  //Establish a session with a
                                                                                //particular database.
           return conn;
         }   
       
        public void HomeStart()
        {
        /**Here, the main frame is made**/
            
        //JFrame.setDefaultLookAndFeelDecorated(true);//to cutomize the JFrame
            JFrame frame = new JFrame("External HD");
           
            
            HomeWindow HomeObject = new HomeWindow();
            frame.getContentPane().setLayout(new BorderLayout());//adds the main panel to the Frame
            frame.add(HomeObject.MainContentPanel());
            frame.setJMenuBar(HomeObject.MenuBar());
            
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//default Action if the frame is closed
            frame.setSize(803,484);
            frame.setLocation(300,90);
            frame.setLocationRelativeTo(null);  
            frame.pack();
            frame.setVisible(true);
            
            
        }
    
        public void setSampleFileName(String SampleFileName) {
            this.SampleFileName = SampleFileName;
        }
        
        
        /* Variable Declarations*/
        
      JMenu HomeMenu;
      JMenuItem Admin, About;
      JToggleButton CopyBtn;
      public JTextArea FileNameText;
      
      String SampleFileName;
        
        /**/
        
        
        
        public JPanel MainContentPanel()
        { 
            
          FilesPanel filesObject= new FilesPanel(); 
          String SampleDescription="";       
            
          JPanel MainPanel= new JPanel();  //Main panel
          MainPanel.setLayout(new BorderLayout());
         
          
          JPanel DetailsPanel = new JPanel(); //Panel for the details on the left side
          DetailsPanel.setLayout(new BoxLayout(DetailsPanel, BoxLayout.Y_AXIS));   
          DetailsPanel.setMinimumSize(new Dimension(0, 0));
          DetailsPanel.setMaximumSize(new Dimension(190, 840));
          DetailsPanel.setPreferredSize(new Dimension(190, 240));     
          
          
          JPanel FileNamePanel= new JPanel();//Panel that holds the File Name Label
          JLabel FileName = new JLabel("File Name");// File name Label
          FileNamePanel.add(FileName);
          FileNamePanel.setPreferredSize(new Dimension(0,20));
          DetailsPanel.add(FileNamePanel);
          
          JPanel FNTextAreaPanel= new JPanel();// Panel holds the file name text area
          FileNameText = new JTextArea();// File name Text area
          FileNameText.setEditable(false);
          FileNameText.setLineWrap(true);
          FileNameText.setWrapStyleWord(true);
          FileNameText.setBackground(Color.white);
          FileNameText.setPreferredSize(new Dimension(170,22));
          FNTextAreaPanel.add(FileNameText);
          FNTextAreaPanel.setPreferredSize(new Dimension(0,50));
          DetailsPanel.add(FNTextAreaPanel);
          
          
          JPanel DescriptionPanel= new JPanel();// Panel that holds the Description Label
          JLabel Description = new JLabel("Description");// the description Label
          DescriptionPanel.add(Description);
          DescriptionPanel.setPreferredSize(new Dimension(0,20));
          DetailsPanel.add(DescriptionPanel);
          
          JPanel TextAreaPanel= new JPanel();// Panel That holds the Description Text area
          TextAreaPanel.setLayout(new BorderLayout());
          JTextArea DescriptionText = new JTextArea(SampleDescription);// the description text area
          DescriptionText.setEditable(false);
          DescriptionText.setLineWrap(true);
          DescriptionText.setWrapStyleWord(true);
          DescriptionText.setBackground(Color.white);
         
          
          JScrollPane DescriptionArea = new JScrollPane(DescriptionText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                              JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);// Creates A scrollpane for the 
                                                                                         // Description text area
          TextAreaPanel.add(DescriptionArea, BorderLayout.CENTER);
          TextAreaPanel.setPreferredSize(new Dimension(0,30));
          DetailsPanel.add(TextAreaPanel);
          
          
          JPanel BtnPanel= new JPanel();// Panel that Holds the copy button
          CopyBtn=new JToggleButton("Copy"); // The Copy Button
          CopyBtn.addItemListener(this);
          CopyBtn.setSize(190,60);
          CopyBtn.setLocation(30,50);
          BtnPanel.add(CopyBtn);
          BtnPanel.setPreferredSize(new Dimension(10,50));
          DetailsPanel.add(BtnPanel);
          
          
          MainPanel.add(DetailsPanel, BorderLayout.WEST);
          MainPanel.add(new FilesPanel(), BorderLayout.CENTER);
          MainPanel.setOpaque(true);
            
          return MainPanel;
        }
        
        public JMenuBar MenuBar()
        {
         JMenuBar HomeBar= new JMenuBar();  // The Menu Bar
          
          HomeMenu = new JMenu("Menu"); 
          HomeBar.add(HomeMenu);
          
          Admin=new JMenuItem("Admin Access");
          Admin.addActionListener(this);
          About=new JMenuItem("About");
          About.addActionListener(this);
          
          HomeMenu.add(Admin);
          HomeMenu.add(About);
          
      
          return HomeBar;
        }
        
        
        // Deals with the Item Events.
        @Override
        public void actionPerformed(ActionEvent e) {
             
            if(e.getSource() == Admin)
            {
              Log LG = new Log();
                LG.Logmain();
            }
            else if(e.getSource()== About)
            {
              String info = "Yet to be added";  
                
              JFrame AboutFrame = new JFrame();
              JPanel AboutPanel = new JPanel();
              AboutPanel.setLayout(new BoxLayout(AboutPanel,BoxLayout.LINE_AXIS)); // sets layout to be a boxtype layout
              
              JTextArea AboutText = new JTextArea(info,5,30);
              AboutText.setEditable(false);
              AboutText.setLineWrap(true);
              AboutText.setWrapStyleWord(true);
              AboutText.setBackground(Color.lightGray);
                        
              
              AboutPanel.add(Box.createRigidArea(new Dimension(0,0))); //attributes for the box layout
              AboutPanel.add(AboutText);          
              AboutPanel.setOpaque(true);
              
              AboutFrame.setContentPane(AboutPanel);
              AboutFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//default Action if the frame is closed
              AboutFrame.setSize(310, 200);
              AboutFrame.setLocation(560,200);
              AboutFrame.setVisible(true);  
            }   
        }
    
        @Override
        public void itemStateChanged(ItemEvent e) 
        {
            if(e.getStateChange() == ItemEvent.SELECTED)
            {
                CopyBtn.setText("Copying");
                
            }
            else
            {
                CopyBtn.setText("Copy");
                
            } 
        }
    }
    
    </code>
    Here's the JTree class
    XML Code:
    <code>
    
    package organizer;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.io.File;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.SpringLayout;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    
    /**
     *
     * @author ASUS
     */
    @SuppressWarnings("serial")
    public class FilesPanel extends JPanel{
    
        public String getFilename() {
            return Filename;
        }
    
        public void setFilename(String Filename) {
            this.Filename = Filename;
        }
        
    
        public static JTree tree;
        public String Filename;
     
        
        
      FilesPanel()
        {
        String Dir="I:\\";
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(Dir);
        
        Process(Dir, top, true);
        tree=new JTree(top);
        
        JScrollPane scroll = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                               JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setPreferredSize(new Dimension(600, 420));
        scroll.setMaximumSize(new Dimension(800,800));
        scroll.setMinimumSize(new Dimension(0,0));
        this.setLayout(new BorderLayout());
        
        tree.addTreeSelectionListener(new TreeSelectionListener() {
    	public void valueChanged(TreeSelectionEvent evt) {
    		// Get all nodes whose selection status has changed
    		TreePath[] paths = evt.getPaths();
     
    		// Iterate through all affected nodes
    		for (int i=0; i<paths.length; i++) {
    			if (evt.isAddedPath(i)) {
    				// This node has been selected
    				Filename= paths[i].getLastPathComponent().toString();
                                    System.out.println(Filename);// here it prints fine therefore it is working
    				break;
    			} else {
    				// This node has been deselected
    				break;
    			}
    		}
    	}
    });
        this.add(scroll);
                  
        }
      
    
       
        public static void Process(String FD, DefaultMutableTreeNode root, Boolean recursive)
        {
           
            /*
            * @params: String directory ~ the directory to scan
            * @params: DefaultMutableTreeNode parent ~ the node to add any files as children
            * @params: Boolean recursive ~ determine whether to scan all subdirectories, or just the parent
            */
            
            File[] DirFiles = new File(FD).listFiles();// list all the files in the directory
            
            for(int x=0; x<DirFiles.length;x++)
            { 
              
              DefaultMutableTreeNode node = new DefaultMutableTreeNode(DirFiles[x].getName());
              // only display the node if it isn't a folder, and if this is a recursive call
              if(DirFiles[x].isFile()&& recursive) // loop through each
              {
                 
                 root.add(node);// add it as a node and do nothing else
              }
              else if(DirFiles[x].isDirectory()&& recursive)
              {
                
              root.add(node);// add as a child node
              Process(DirFiles[x].getPath(), node, recursive);// call again for the subdirectory
              }
              
            }
           
        }
        
    
        
        
    }
    
    
    </code>
    I got most of the ideas online, as i'm still new to this. And any tips or advice would be a great help
    Thanks in advance

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,234
    Rep Power
    19

    Default Re: How to update the contents of a JTextArea

    Moved from New to Java.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How to update the contents of a JTextArea

    That's an awful lot of code to ask a volunteer to slog through without more direction. How about helping us out here? For instance, to have text show in a JTextArea you call its setText(...) method if you want to replace all text with your text or its append(...) method if you want to add text to existing text. What problems are you having when you try this? Please tell us the details, show us the important code, try to limit the volume of noise we have to go through to get to the core problem. Also, consider replying to answers in your previous thread before asking a new question. It helps motivate us to help you.
    Reptar693 likes this.

  4. #4
    Reptar693 is offline Member
    Join Date
    Mar 2012
    Posts
    6
    Rep Power
    0

    Default Re: How to update the contents of a JTextArea

    I apologize, I am kinda new to forums, anyway i found the solution, it was to make my JTextArea Variable static.

    I appreciate the advice and i will definitely use them next time, Thank you very much

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How to update the contents of a JTextArea

    Quote Originally Posted by Reptar693 View Post
    I apologize, I am kinda new to forums, anyway i found the solution, it was to make my JTextArea Variable static.
    No, that is not a good, viable or long-term workable solution at all. You've still got a problem.

Similar Threads

  1. How to update JTable contents
    By chyrl in forum AWT / Swing
    Replies: 10
    Last Post: 04-17-2010, 05:26 AM
  2. Display partial file contents in JTextArea
    By tmoehlman in forum New To Java
    Replies: 0
    Last Post: 11-02-2009, 11:03 PM
  3. Replies: 12
    Last Post: 10-09-2009, 06:26 AM
  4. Replies: 1
    Last Post: 07-18-2007, 11:20 PM
  5. viewing the contents of a text file in JTextArea
    By warship in forum New To Java
    Replies: 0
    Last Post: 07-17-2007, 02:29 PM

Tags for this Thread

Posting Permissions

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