Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 20 of 20

Thread: newbie help threads

  1. #1
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default newbie help threads

    Hi Guys,

    Im very new to java and trying to learn threads and what i am trying to achive is basically my program does a search through a text file and it goes under heavy load locking out the program so what i want is a background worker to run a thread doing the heavy work updating a progress bar maybe and not locking out my gui. Do you know the simplest way to achive this and can you point me into the right direction so i can learn please because i am having some great dificulty


  2. #2
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: newbie help threads

    all i need is a point in the right direction id really appriciate it

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: newbie help threads

    I think you're looking for SwingWorker. Google is your friend.

  4. #4
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: newbie help threads

    Hello fortune2k,

    How large is your text file?

    Can you please post the code you have for us to look at.

    It is possible to achive this without locking out your GUI.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  5. #5
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: newbie help threads

    heres my code
    /*
     * DesktopApplication3View.java
     */
     
    package desktopapplication3;
     
    import org.jdesktop.application.Action;
    import org.jdesktop.application.ResourceMap;
    import org.jdesktop.application.SingleFrameApplication;
    import org.jdesktop.application.FrameView;
    import org.jdesktop.application.TaskMonitor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Timer;
    import javax.swing.Icon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import java.io.File;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileNameExtensionFilter;
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.lang.*;
    import java.text.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.Color;
    import java.io.InputStreamReader;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.GroupLayout.*;
     
    public class DesktopApplication3View extends FrameView {
     
     String selectedItem;
     
        public DesktopApplication3View(SingleFrameApplication app) {
         super(app);
         initComponents();
         hilit = new DefaultHighlighter();
         painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
         MainTextArea.setHighlighter(hilit);
     
     
             if(selectedItem == null)
             {
                MainTextArea.append("No File Selected\n");
             }
        }
     
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            mainPanel = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            MainTextArea = new javax.swing.JTextArea();
            StringSearchTextArea = new javax.swing.JTextField();
            SearchButton = new javax.swing.JButton();
            StatusMessage = new javax.swing.JLabel();
            StatusLabel = new javax.swing.JLabel();
            StringSearchLabel = new javax.swing.JLabel();
            menuBar = new javax.swing.JMenuBar();
            javax.swing.JMenu fileMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenuItem exitMenuItem1 = new javax.swing.JMenuItem();
            javax.swing.JMenu helpMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem HiglightKeyMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
            Satus = new javax.swing.JLabel();
     
            mainPanel.setName("mainPanel"); // NOI18N
     
            jScrollPane1.setName("jScrollPane1"); // NOI18N
     
            MainTextArea.setColumns(20);
            MainTextArea.setEditable(false);
            MainTextArea.setRows(5);
            MainTextArea.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(desktopapplication3.DesktopApplication3.class).getContext().getResourceMap(DesktopApplication3View.class);
            MainTextArea.setDisabledTextColor(resourceMap.getColor("MainTextArea.disabledTextColor")); // NOI18N
            MainTextArea.setDoubleBuffered(true);
            MainTextArea.setDragEnabled(true);
            MainTextArea.setName("MainTextArea"); // NOI18N
            jScrollPane1.setViewportView(MainTextArea);
     
            StringSearchTextArea.setText(resourceMap.getString("StringSearchTextArea.text")); // NOI18N
            StringSearchTextArea.setName("StringSearchTextArea"); // NOI18N
            StringSearchTextArea.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
            });
            StringSearchTextArea.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
            });
     
            SearchButton.setText(resourceMap.getString("SearchButton.text")); // NOI18N
            SearchButton.setName("SearchButton"); // NOI18N
            SearchButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    SearchForString(evt);
                }
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    SearchForString(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    SearchForString(evt);
                }
            });
     
            StatusMessage.setBackground(resourceMap.getColor("StatusMessage.background")); // NOI18N
            StatusMessage.setText(resourceMap.getString("StatusMessage.text")); // NOI18N
            StatusMessage.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            StatusMessage.setName("StatusMessage"); // NOI18N
     
            StatusLabel.setText(resourceMap.getString("StatusLabel.text")); // NOI18N
            StatusLabel.setName("StatusLabel"); // NOI18N
     
            StringSearchLabel.setText(resourceMap.getString("StringSearchLabel.text")); // NOI18N
            StringSearchLabel.setName("StringSearchLabel"); // NOI18N
     
            javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
            mainPanel.setLayout(mainPanelLayout);
            mainPanelLayout.setHorizontalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 791, Short.MAX_VALUE)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGap(1, 1, 1)
                            .addComponent(StringSearchLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(StringSearchTextArea, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(SearchButton)
                            .addGap(18, 18, 18)
                            .addComponent(StatusLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(StatusMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)))
                    .addContainerGap())
            );
            mainPanelLayout.setVerticalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 465, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(StringSearchTextArea)
                                .addComponent(SearchButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(StringSearchLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(StatusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(87, 87, 87))
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addComponent(StatusMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())))
            );
     
            menuBar.setName("menuBar"); // NOI18N
     
            javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(desktopapplication3.DesktopApplication3.class).getContext().getActionMap(DesktopApplication3View.class, this);
            fileMenu.setAction(actionMap.get("OpenFileDialoge")); // NOI18N
            fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
            fileMenu.setName("fileMenu"); // NOI18N
     
            exitMenuItem.setAction(actionMap.get("OpenFileDialoge")); // NOI18N
            exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
            exitMenuItem.setName("exitMenuItem"); // NOI18N
            fileMenu.add(exitMenuItem);
     
            exitMenuItem1.setAction(actionMap.get("quit")); // NOI18N
            exitMenuItem1.setName("exitMenuItem1"); // NOI18N
            fileMenu.add(exitMenuItem1);
     
            menuBar.add(fileMenu);
     
            helpMenu.setAction(actionMap.get("showHiglightBox")); // NOI18N
            helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
            helpMenu.setName("helpMenu"); // NOI18N
     
            HiglightKeyMenuItem.setAction(actionMap.get("showHiglightBox")); // NOI18N
            HiglightKeyMenuItem.setText(resourceMap.getString("HiglightKeyMenuItem.text")); // NOI18N
            HiglightKeyMenuItem.setToolTipText(resourceMap.getString("HiglightKeyMenuItem.toolTipText")); // NOI18N
            HiglightKeyMenuItem.setName("HiglightKeyMenuItem"); // NOI18N
            helpMenu.add(HiglightKeyMenuItem);
     
            aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
            aboutMenuItem.setName("aboutMenuItem"); // NOI18N
            helpMenu.add(aboutMenuItem);
     
            menuBar.add(helpMenu);
     
            Satus.setText(resourceMap.getString("Satus.text")); // NOI18N
            Satus.setName("Satus"); // NOI18N
     
            setComponent(mainPanel);
            setMenuBar(menuBar);
        }// </editor-fold>                        
     
        private void SearchForString(java.awt.event.MouseEvent evt) {                                 
     
            int index, end, counter=0;
            boolean loop = true;
            String s = StringSearchTextArea.getText();
            String content = MainTextArea.getText();
     
            hilit.removeAllHighlights();
     
            if (s.length() <= 0) {
                StatusMessage.setText("Nothing to search");
                return;
            }
     
          while(loop == true)
          {
            index = content.indexOf(s, counter);
            if (index >= 0) {   // match found
                ++counter;
                try {
                    end = index + s.length();
                    hilit.addHighlight(index, end, painter);
                }
                catch (BadLocationException e) {
                    StatusMessage.setText("Error: " + e.getMessage());
                }
             loop = true;
             StatusMessage.setText("'" + s + "' found."); 
            } 
            else if (index < 0){
               loop = false;
               if(counter == 0)StatusMessage.setText("'" + s + "' not found.");
            }
          }
        }                                
     
        private void StringSearchTextAreaMouseClicked(java.awt.event.MouseEvent evt) {                                                  
          if (StringSearchTextArea.getText().equals("**Search is Case Sensitive**"))
          {
            StringSearchTextArea.setText(""); // clears the fiedl if equal to **Search is Case Sensitive**
          }
        }                                                 
     
     
       public void DispalyFile()
        {
         try{
            FileInputStream fstream = new FileInputStream(selectedItem);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
     
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            MainTextArea.setText(""); // Clear the Text Box
                while ((strLine = br.readLine()) != null) //loop through each line 
                {
                // Print the content on the console
                MainTextArea.append(strLine+"\n");  // print out each line in the text file in jTextArea1
                }
            in.close();//Close the input stream
            }
            catch (Exception e)
            {//Catch exception if any
            StatusMessage.setText("Error: " + e.getMessage());
            } 
        }
     
        @Action
        public void showAboutBox() {
            if (aboutBox == null) {
                JFrame mainFrame = DesktopApplication3.getApplication().getMainFrame();
                aboutBox = new DesktopApplication3AboutBox(mainFrame);
                aboutBox.setLocationRelativeTo(mainFrame);
            }
            DesktopApplication3.getApplication().show(aboutBox);
        }
     
        @Action
        public void showHiglightBox() {
            if (HighlightBox == null) {
                JFrame mainFrame = DesktopApplication3.getApplication().getMainFrame();
                HighlightBox = new DesktopApplication3HighlightKey(mainFrame);
                HighlightBox.setLocationRelativeTo(mainFrame);
            }
            DesktopApplication3.getApplication().show(HighlightBox);
        }
     
        @Action
        public void OpenFileDialoge() {
            Frame parent = new Frame();
            FileDialog fd = new FileDialog(parent, "Please choose a file:",FileDialog.LOAD);
    	fd.show();
    	selectedItem = fd.getDirectory() + fd.getFile(); // get the full directory of the file
            DispalyFile();
        }
     
     
        // Variables declaration - do not modify                     
        private javax.swing.JTextArea MainTextArea;
        private javax.swing.JLabel Satus;
        private javax.swing.JButton SearchButton;
        private javax.swing.JLabel StatusLabel;
        private javax.swing.JLabel StatusMessage;
        private javax.swing.JLabel StringSearchLabel;
        private javax.swing.JTextField StringSearchTextArea;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JPanel mainPanel;
        private javax.swing.JMenuBar menuBar;
        // End of variables declaration                   
     
        final Highlighter hilit;
        final Highlighter.HighlightPainter painter;
        final static Color  HILIT_COLOR = Color.YELLOW;
        private JDialog HighlightBox;
        private JDialog aboutBox;
    }


    basically what it does is opens up a text file displays it in maintextarea and there is a text box which allows you to put in a string and when pressed search it will search the maintextarea highlighting the string you are searching for.

    What i want to do is have a progressbar and backgroundworker so the gui doesnt lock out beause the size of the text file can vary in size when i open large text files the gui locks out and the search locks out until finished beacuse the program is under heavy load so if i could get them to run in the background the gui can lock out and i can have a cancel button which would cancel the task i kn ow in c# u can use Backgroundworker . I also want a progress bar to update whilst the search/opening is taken place


    i hope this gives you a better idea and please let me know if you need more info
    Last edited by JavaPF; October 14th, 2010 at 10:02 AM. Reason: Please use HIGHLIGHT tags instead of CODE tags. See my signature..

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: newbie help threads

    Still sounds like a job for SwingWorker to me...

  7. #7
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: newbie help threads

    You need to put a Thread in the DispalyFile() method.

    I did something similar with an application I was working on recently.

    This code should do the trick. Play around with it...

    	public static void DispalyFile() throws IOException{
     
    		Runnable runnable = new Thread(){
     
    		    public void run(){
     
    		        FileInputStream fstream = new FileInputStream(selectedItem);
    		        // Get the object of DataInputStream
    		        DataInputStream in = new DataInputStream(fstream);
     
    		        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    		        String strLine;      
     
    		        try {
    					while ((strLine = br.readLine()) != null) {					     
    					//System.out.println(strLine);
    					MainTextArea.append(strLine+"\n");  // print out each line in the text file in jTextArea1
    					}
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    		        try {
    					in.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    		    }
    		};
     
    		Thread thread = new Thread(runnable);
    		thread.start();		
     
    	}
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  8. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: newbie help threads

    Quote Originally Posted by JavaPF View Post
    You need to put a Thread in the DispalyFile() method.

    I did something similar with an application I was working on recently.

    This code should do the trick. Play around with it...

    	public static void DispalyFile() throws IOException{
     
    		Runnable runnable = new Thread(){
     
    		    public void run(){
     
    		        FileInputStream fstream = new FileInputStream(selectedItem);
    		        // Get the object of DataInputStream
    		        DataInputStream in = new DataInputStream(fstream);
     
    		        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    		        String strLine;      
     
    		        try {
    					while ((strLine = br.readLine()) != null) {					     
    					//System.out.println(strLine);
    					MainTextArea.append(strLine+"\n");  // print out each line in the text file in jTextArea1
    					}
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    		        try {
    					in.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    		    }
    		};
     
    		Thread thread = new Thread(runnable);
    		thread.start();		
     
    	}
    Hate to disagree with a seasoned vet, but I see two problems with this:

    Assuming MainTextArea (er, mainTextArea?) is a JTextArea, you don't want to be updating it off of the EDT, right? Actually, I just looked it up, and that method appears to be thread safe, but I'm not sure it's a great habit to get a newbie into. Hence my vote for SwingWorker.

    Also, this doesn't handle the problem with the JProgressBar. Again, SwingWorker would handle that.

    Anyway, I'm not disagreeing, and it's up to the OP, but I thought I'd voice my concerns about simply using a regular thread instead of a SwingWorker.

  9. The Following User Says Thank You to KevinWorkman For This Useful Post:

    JavaPF (October 14th, 2010)

  10. #9
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: newbie help threads

    Well said KevinWorkman.

    I haven't tested the above code. I bodged it together from something I was working on recently. It worked in not locking up the GUI so thought this would be a simple solution for him.

    Looking into SwingWorker though, it's well worth considering this
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  11. #10
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: newbie help threads

    An alternative is to use SwingUtilities.invokeLater, with the parameter Runnable implementation updating the GUI. This dispatches to the EDT, and is a good alternative to SwingWorker when one intends a program to run on JDK's prior to 1.6 (when SwingWorker was introduced).

  12. #11
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: newbie help threads

    import org.jdesktop.application.Action;
    import org.jdesktop.application.ResourceMap;
    import org.jdesktop.application.SingleFrameApplication;
    import org.jdesktop.application.FrameView;
    import org.jdesktop.application.TaskMonitor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Timer;
    import javax.swing.Icon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import java.io.File;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileNameExtensionFilter;
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.lang.*;
    import java.text.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.Color;
    import java.io.InputStreamReader;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.GroupLayout.*;
    HOLY CRAP! That's the definition of redundancy.

    import org.jdesktop.application.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import javax.swing.filechooser.*;
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.lang.*;
    import java.text.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.GroupLayout.*;

  13. #12
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: newbie help threads

    yea i added loads of imports i will have a look tonight at the program and let you know how it goes.

    Thankyou for all your help

  14. #13
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: newbie help threads

    right it looks like SwingWorker would do the trick because i want to implement a progress bar and the main task of the program will be a heavy loader. Do you know any good books/tutorials which will help me ?

  15. #14
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: newbie help threads

    Quote Originally Posted by fortune2k View Post
    right it looks like SwingWorker would do the trick because i want to implement a progress bar and the main task of the program will be a heavy loader. Do you know any good books/tutorials which will help me ?
    I'd start with a google search. The first page of results seems extremely promising.

  16. #15
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: newbie help threads

    Hi Guys,

    Right i have been doing a fare bit of reading and playing around with swingworker but i still cant sort it. I have managed to put some code together which i belive will work and the program runs however when the search is looking throigh a large txt file i get the "laggy" no responsive GUI. Can someone have a glance over my code and steer me in the right direction please . thanks you

    /*
     * DesktopApplication3View.java
     */
     
    package desktopapplication3;
     
    import org.jdesktop.application.Action;
    import org.jdesktop.application.ResourceMap;
    import org.jdesktop.application.SingleFrameApplication;
    import org.jdesktop.application.FrameView;
    import org.jdesktop.application.TaskMonitor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Timer;
    import javax.swing.Icon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import java.io.File;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileNameExtensionFilter;
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.lang.*;
    import java.text.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.Color;
    import java.io.InputStreamReader;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.GroupLayout.*;
    import java.util.regex.*;
    import javax.swing.SwingWorker;
     
     
     
    public class DesktopApplication3View extends FrameView {
        private Task task;
        public boolean cancel;
        String selectedItem;
     
     
     
     
     
        class Task extends SwingWorker{
        @Override
     
     
     
        public Void doInBackground() {
     
            cancel= false;
            int index, end, counter=0;
            boolean loop = true;
            String s = StringSearchTextArea.getText();
            String content = MainTextArea.getText();
            hilit.removeAllHighlights();
     
            if (s.length() <= 0) {
                StatusMessage.setText("Nothing to search");
            }
     
     
          while(cancel == false)
          {
              while(loop == true)
              {
                index = content.indexOf(s, counter);
                if (index >= 0) {   // match found
                    ++counter;
                    try {
                        end = index + s.length();
                        hilit.addHighlight(index, end, painter);
                    }
                    catch (BadLocationException e) {
                        StatusMessage.setText("Error: " + e.getMessage());
                    }
                 loop = true;
                 StatusMessage.setText("'" + s + "' found.");
                }
                else if (index < 0){
                   loop = false;
                   if(counter == 0)StatusMessage.setText("'" + s + "' not found.");
                }
              }
         }
     
     
     
     
         return null;
        }
     
        @Override
        public void done() {
        SearchButton.setEnabled(true);
        if(cancel == true)
        {
          StatusMessage.setText("Canceld");
        }
        }
     
      }
     
     
     
     
        public DesktopApplication3View(SingleFrameApplication app) {
         super(app);
         initComponents();
     
         hilit = new DefaultHighlighter();
         painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
         MainTextArea.setHighlighter(hilit);
         SearchButton.setEnabled(true);
             if(selectedItem == null)
             {
                MainTextArea.append("No File Selected\n");
             }
        }
     
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
     
            mainPanel = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            MainTextArea = new javax.swing.JTextArea();
            StringSearchTextArea = new javax.swing.JTextField();
            SearchButton = new javax.swing.JButton();
            StatusMessage = new javax.swing.JLabel();
            StatusLabel = new javax.swing.JLabel();
            StringSearchLabel = new javax.swing.JLabel();
            Cancel = new javax.swing.JButton();
            menuBar = new javax.swing.JMenuBar();
            javax.swing.JMenu fileMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenuItem exitMenuItem1 = new javax.swing.JMenuItem();
            javax.swing.JMenu helpMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem HiglightKeyMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
            Satus = new javax.swing.JLabel();
     
            mainPanel.setName("mainPanel"); // NOI18N
     
            jScrollPane1.setName("jScrollPane1"); // NOI18N
     
            MainTextArea.setColumns(20);
            MainTextArea.setEditable(false);
            MainTextArea.setRows(5);
            MainTextArea.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(desktopapplication3.DesktopApplication3.class).getContext().getResourceMap(DesktopApplication3View.class);
            MainTextArea.setDisabledTextColor(resourceMap.getColor("MainTextArea.disabledTextColor")); // NOI18N
            MainTextArea.setDoubleBuffered(true);
            MainTextArea.setDragEnabled(true);
            MainTextArea.setName("MainTextArea"); // NOI18N
            jScrollPane1.setViewportView(MainTextArea);
     
            StringSearchTextArea.setText(resourceMap.getString("StringSearchTextArea.text")); // NOI18N
            StringSearchTextArea.setName("StringSearchTextArea"); // NOI18N
            StringSearchTextArea.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
            });
            StringSearchTextArea.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
            });
     
            SearchButton.setText(resourceMap.getString("SearchButton.text")); // NOI18N
            SearchButton.setName("SearchButton"); // NOI18N
            SearchButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    SearchButton(evt);
                }
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    SearchButton(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    SearchButton(evt);
                }
            });
     
            StatusMessage.setBackground(resourceMap.getColor("StatusMessage.background")); // NOI18N
            StatusMessage.setText(resourceMap.getString("StatusMessage.text")); // NOI18N
            StatusMessage.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            StatusMessage.setName("StatusMessage"); // NOI18N
     
            StatusLabel.setText(resourceMap.getString("StatusLabel.text")); // NOI18N
            StatusLabel.setName("StatusLabel"); // NOI18N
     
            StringSearchLabel.setText(resourceMap.getString("StringSearchLabel.text")); // NOI18N
            StringSearchLabel.setName("StringSearchLabel"); // NOI18N
     
            Cancel.setText(resourceMap.getString("Cancel.text")); // NOI18N
            Cancel.setName("Cancel"); // NOI18N
            Cancel.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    CancelButton(evt);
                }
            });
     
            javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
            mainPanel.setLayout(mainPanelLayout);
            mainPanelLayout.setHorizontalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 793, Short.MAX_VALUE)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGap(1, 1, 1)
                            .addComponent(StringSearchLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(StringSearchTextArea, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(Cancel)
                                .addGroup(mainPanelLayout.createSequentialGroup()
                                    .addComponent(SearchButton)
                                    .addGap(18, 18, 18)
                                    .addComponent(StatusLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(StatusMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)))))
                    .addContainerGap())
            );
            mainPanelLayout.setVerticalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 465, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(StringSearchTextArea)
                                .addComponent(SearchButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(StringSearchLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(StatusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(Cancel)
                            .addGap(53, 53, 53))
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addComponent(StatusMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())))
            );
     
            menuBar.setName("menuBar"); // NOI18N
     
            javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(desktopapplication3.DesktopApplication3.class).getContext().getActionMap(DesktopApplication3View.class, this);
            fileMenu.setAction(actionMap.get("OpenFileDialoge")); // NOI18N
            fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
            fileMenu.setName("fileMenu"); // NOI18N
     
            exitMenuItem.setAction(actionMap.get("OpenFileDialoge")); // NOI18N
            exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
            exitMenuItem.setName("exitMenuItem"); // NOI18N
            fileMenu.add(exitMenuItem);
     
            exitMenuItem1.setAction(actionMap.get("quit")); // NOI18N
            exitMenuItem1.setName("exitMenuItem1"); // NOI18N
            fileMenu.add(exitMenuItem1);
     
            menuBar.add(fileMenu);
     
            helpMenu.setAction(actionMap.get("showHiglightBox")); // NOI18N
            helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
            helpMenu.setName("helpMenu"); // NOI18N
     
            HiglightKeyMenuItem.setAction(actionMap.get("showHiglightBox")); // NOI18N
            HiglightKeyMenuItem.setText(resourceMap.getString("HiglightKeyMenuItem.text")); // NOI18N
            HiglightKeyMenuItem.setToolTipText(resourceMap.getString("HiglightKeyMenuItem.toolTipText")); // NOI18N
            HiglightKeyMenuItem.setName("HiglightKeyMenuItem"); // NOI18N
            helpMenu.add(HiglightKeyMenuItem);
     
            aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
            aboutMenuItem.setName("aboutMenuItem"); // NOI18N
            helpMenu.add(aboutMenuItem);
     
            menuBar.add(helpMenu);
     
            Satus.setText(resourceMap.getString("Satus.text")); // NOI18N
            Satus.setName("Satus"); // NOI18N
     
            setComponent(mainPanel);
            setMenuBar(menuBar);
        }// </editor-fold>
     
     
     
     
     
     
        private void SearchButton(java.awt.event.MouseEvent evt) {                                 
             task = new Task();
            try {
              task.execute();
            } catch (Exception e) {
              e.printStackTrace();
            }
           SearchButton.setEnabled(false);
        }                                
     
        private void StringSearchTextAreaMouseClicked(java.awt.event.MouseEvent evt) {                                                  
          if (StringSearchTextArea.getText().equals("**Search is Case Sensitive**"))
          {
            StringSearchTextArea.setText(""); // clears the fiedl if equal to **Search is Case Sensitive**
          }
        }                                                 
     
        private void CancelButton(java.awt.event.MouseEvent evt) {
            cancel = true;
        }
     
     
       public void DispalyFile()
        {
         try{
            FileInputStream fstream = new FileInputStream(selectedItem);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
     
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            MainTextArea.setText(""); // Clear the Text Box
                while ((strLine = br.readLine()) != null) //loop through each line 
                {
                // Print the content on the console
                MainTextArea.append(strLine+"\n");  // print out each line in the text file in jTextArea1
                }
            in.close();//Close the input stream
            }
            catch (Exception e)
            {//Catch exception if any
            StatusMessage.setText("Error: " + e.getMessage());
            } 
        }
     
        @Action
        public void showAboutBox() {
            if (aboutBox == null) {
                JFrame mainFrame = DesktopApplication3.getApplication().getMainFrame();
                aboutBox = new DesktopApplication3AboutBox(mainFrame);
                aboutBox.setLocationRelativeTo(mainFrame);
            }
            DesktopApplication3.getApplication().show(aboutBox);
        }
     
        @Action
        public void showHiglightBox() {
            if (HighlightBox == null) {
                JFrame mainFrame = DesktopApplication3.getApplication().getMainFrame();
                HighlightBox = new DesktopApplication3HighlightKey(mainFrame);
                HighlightBox.setLocationRelativeTo(mainFrame);
            }
            DesktopApplication3.getApplication().show(HighlightBox);
        }
     
        @Action
        public void OpenFileDialoge() {
            Frame parent = new Frame();
            FileDialog fd = new FileDialog(parent, "Please choose a file:",FileDialog.LOAD);
    	fd.show();
    	selectedItem = fd.getDirectory() + fd.getFile(); // get the full directory of the file
            DispalyFile();
        }
     
     
        // Variables declaration - do not modify
        public javax.swing.JButton Cancel;
        private javax.swing.JTextArea MainTextArea;
        private javax.swing.JLabel Satus;
        public javax.swing.JButton SearchButton;
        private javax.swing.JLabel StatusLabel;
        private javax.swing.JLabel StatusMessage;
        private javax.swing.JLabel StringSearchLabel;
        private javax.swing.JTextField StringSearchTextArea;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JPanel mainPanel;
        private javax.swing.JMenuBar menuBar;
        // End of variables declaration
     
        final Highlighter hilit;
        final Highlighter.HighlightPainter painter;
        final static Color  HILIT_COLOR = Color.YELLOW;
        private JDialog HighlightBox;
        private JDialog aboutBox;
    }
    Last edited by fortune2k; October 19th, 2010 at 06:20 PM.

  17. #16
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: newbie help threads

    That's a lot of code, and chances are that nobody will want to wade through it. You're welcome to wait and hope that somebody does, but you'd be more likely to get help if you narrowed the problem down to an SSCCE. Up to you.

  18. #17
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: newbie help threads

    The mian problem im seeing is the swingthread i think the code is

     
        class Task extends SwingWorker{
        @Override
     
     
     
        public Void doInBackground() {
     
            cancel= false;
            int index, end, counter=0;
            boolean loop = true;
            String s = StringSearchTextArea.getText();
            String content = MainTextArea.getText();
            hilit.removeAllHighlights();
     
            if (s.length() <= 0) {
                StatusMessage.setText("Nothing to search");
            }
     
     
          while(cancel == false)
          {
              while(loop == true)
              {
                index = content.indexOf(s, counter);
                if (index >= 0) {   // match found
                    ++counter;
                    try {
                        end = index + s.length();
                        hilit.addHighlight(index, end, painter);
                    }
                    catch (BadLocationException e) {
                        StatusMessage.setText("Error: " + e.getMessage());
                    }
                 loop = true;
                 StatusMessage.setText("'" + s + "' found.");
                }
                else if (index < 0){
                   loop = false;
                   if(counter == 0)StatusMessage.setText("'" + s + "' not found.");
                }
              }
         }
     
     
     
     
         return null;
        }
     
        @Override
        public void done() {
        SearchButton.setEnabled(true);
        if(cancel == true)
        {
          StatusMessage.setText("Canceld");
        }
        }
     
      }

    I just want to know if i have set it up correctly i want a seperate thread tunning when the search button is pressed so the heavy loading (searcing through the text file) is being done in the background and not locking out the GUI

  19. #18
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: newbie help threads

    Right im actully going insane here getting no where been stuck on this for days so lets re explain myself and see if this helps. I really really want to understand this so please help i know im a newbie who may be a pain in the ass.

    Right i am making a program which will highlight various strings in a text file




    As you can see in the pic above the program runs allows you to select the text file to read in which is displayed in the MainTextArea. Ive ran a search already for '44' the program has gone through higlighting all the 44 in the MainTextArea.

    The problem is that when I read in a text file with thousounds of words, lines and charcters the gui starts to slow down and when i perfrom the same search for '44' the GUI will almost crash and no response.

    a freind of mine said look up "BackgroundWorker" so I did and found the following : BackgroundWorker. Anyway I have had no luck with this. Some of the guys suggested swingworker / Threadding and still getting no where. I have done a great deal of research and reading on the subject and getting no where Im really not grasping it.


    What im bascially trying to achive is when i open the txt file another thread will start and eventually i will have a status bar showing the progress of opening the file. Searching the text file is the main task which takes up resources so i will need to put the search method inanother thread and also i will have the progress bar updating as the search runs.

    Im really struggling here guys please help me i know im a big newbie

    PLEASE HELP . How can i achive this


    /*
     * DesktopApplication3View.java
     */
     
    package desktopapplication3;
     
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import org.jdesktop.application.Action;
    import org.jdesktop.application.ResourceMap;
    import org.jdesktop.application.SingleFrameApplication;
    import org.jdesktop.application.FrameView;
    import org.jdesktop.application.TaskMonitor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Timer;
    import javax.swing.Icon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import java.io.File;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileNameExtensionFilter;
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.lang.*;
    import java.text.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.Color;
    import java.io.InputStreamReader;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.GroupLayout.*;
    import java.util.regex.*;
     
     
    public class DesktopApplication3View extends FrameView {
     
     String selectedItem;
     
        public DesktopApplication3View(SingleFrameApplication app) {
         super(app);
         initComponents();
         hilit = new DefaultHighlighter();
         painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
         MainTextArea.setHighlighter(hilit);
     
     
             if(selectedItem == null)
             {
                MainTextArea.append("No File Selected\n");
             }
        }
     
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            mainPanel = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            MainTextArea = new javax.swing.JTextArea();
            StringSearchTextArea = new javax.swing.JTextField();
            SearchButton = new javax.swing.JButton();
            StatusMessage = new javax.swing.JLabel();
            StatusLabel = new javax.swing.JLabel();
            StringSearchLabel = new javax.swing.JLabel();
            menuBar = new javax.swing.JMenuBar();
            javax.swing.JMenu fileMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenuItem exitMenuItem1 = new javax.swing.JMenuItem();
            javax.swing.JMenu helpMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem HiglightKeyMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
            Satus = new javax.swing.JLabel();
     
            mainPanel.setName("mainPanel"); // NOI18N
     
            jScrollPane1.setName("jScrollPane1"); // NOI18N
     
            MainTextArea.setColumns(20);
            MainTextArea.setEditable(false);
            MainTextArea.setRows(5);
            MainTextArea.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(desktopapplication3.DesktopApplication3.class).getContext().getResourceMap(DesktopApplication3View.class);
            MainTextArea.setDisabledTextColor(resourceMap.getColor("MainTextArea.disabledTextColor")); // NOI18N
            MainTextArea.setDoubleBuffered(true);
            MainTextArea.setDragEnabled(true);
            MainTextArea.setName("MainTextArea"); // NOI18N
            jScrollPane1.setViewportView(MainTextArea);
     
            StringSearchTextArea.setText(resourceMap.getString("StringSearchTextArea.text")); // NOI18N
            StringSearchTextArea.setName("StringSearchTextArea"); // NOI18N
            StringSearchTextArea.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
            });
            StringSearchTextArea.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    StringSearchTextAreaMouseClicked(evt);
                }
            });
     
            SearchButton.setText(resourceMap.getString("SearchButton.text")); // NOI18N
            SearchButton.setName("SearchButton"); // NOI18N
            SearchButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    SearchForString(evt);
                }
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    SearchForString(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    SearchForString(evt);
                }
            });
     
            StatusMessage.setBackground(resourceMap.getColor("StatusMessage.background")); // NOI18N
            StatusMessage.setText(resourceMap.getString("StatusMessage.text")); // NOI18N
            StatusMessage.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            StatusMessage.setName("StatusMessage"); // NOI18N
     
            StatusLabel.setText(resourceMap.getString("StatusLabel.text")); // NOI18N
            StatusLabel.setName("StatusLabel"); // NOI18N
     
            StringSearchLabel.setText(resourceMap.getString("StringSearchLabel.text")); // NOI18N
            StringSearchLabel.setName("StringSearchLabel"); // NOI18N
     
            javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
            mainPanel.setLayout(mainPanelLayout);
            mainPanelLayout.setHorizontalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 791, Short.MAX_VALUE)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGap(1, 1, 1)
                            .addComponent(StringSearchLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(StringSearchTextArea, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(SearchButton)
                            .addGap(18, 18, 18)
                            .addComponent(StatusLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(StatusMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)))
                    .addContainerGap())
            );
            mainPanelLayout.setVerticalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 465, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(StringSearchTextArea)
                                .addComponent(SearchButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(StringSearchLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(StatusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(87, 87, 87))
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addComponent(StatusMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())))
            );
     
            menuBar.setName("menuBar"); // NOI18N
     
            javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(desktopapplication3.DesktopApplication3.class).getContext().getActionMap(DesktopApplication3View.class, this);
            fileMenu.setAction(actionMap.get("OpenFileDialoge")); // NOI18N
            fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
            fileMenu.setName("fileMenu"); // NOI18N
     
            exitMenuItem.setAction(actionMap.get("OpenFileDialoge")); // NOI18N
            exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
            exitMenuItem.setName("exitMenuItem"); // NOI18N
            fileMenu.add(exitMenuItem);
     
            exitMenuItem1.setAction(actionMap.get("quit")); // NOI18N
            exitMenuItem1.setName("exitMenuItem1"); // NOI18N
            fileMenu.add(exitMenuItem1);
     
            menuBar.add(fileMenu);
     
            helpMenu.setAction(actionMap.get("showHiglightBox")); // NOI18N
            helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
            helpMenu.setName("helpMenu"); // NOI18N
     
            HiglightKeyMenuItem.setAction(actionMap.get("showHiglightBox")); // NOI18N
            HiglightKeyMenuItem.setText(resourceMap.getString("HiglightKeyMenuItem.text")); // NOI18N
            HiglightKeyMenuItem.setToolTipText(resourceMap.getString("HiglightKeyMenuItem.toolTipText")); // NOI18N
            HiglightKeyMenuItem.setName("HiglightKeyMenuItem"); // NOI18N
            helpMenu.add(HiglightKeyMenuItem);
     
            aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
            aboutMenuItem.setName("aboutMenuItem"); // NOI18N
            helpMenu.add(aboutMenuItem);
     
            menuBar.add(helpMenu);
     
            Satus.setText(resourceMap.getString("Satus.text")); // NOI18N
            Satus.setName("Satus"); // NOI18N
     
            setComponent(mainPanel);
            setMenuBar(menuBar);
        }// </editor-fold>                        
     
        private void SearchForString(java.awt.event.MouseEvent evt) {                                 
     
            int index, end, counter=0;
            boolean loop = true;
            String s = StringSearchTextArea.getText();
            String content = MainTextArea.getText();
            hilit.removeAllHighlights();
     
            if (s.length() <= 0) {
                StatusMessage.setText("Nothing to search");
                return;
            }
     
          while(loop == true)
          {
            index = content.indexOf(s, counter);
            if (index >= 0) {   // match found
                ++counter;
                try {
                    end = index + s.length();
                    hilit.addHighlight(index, end, painter);
                }
                catch (BadLocationException e) {
                    StatusMessage.setText("Error: " + e.getMessage());
                }
             loop = true;
             StatusMessage.setText("'" + s + "' found."); 
            } 
            else if (index < 0){
               loop = false;
               if(counter == 0)StatusMessage.setText("'" + s + "' not found.");
            }
          }
        }                                
     
        private void StringSearchTextAreaMouseClicked(java.awt.event.MouseEvent evt) {                                                  
          if (StringSearchTextArea.getText().equals("**Search is Case Sensitive**"))
          {
            StringSearchTextArea.setText(""); // clears the fiedl if equal to **Search is Case Sensitive**
          }
        }                                                 
     
     
    public  void DispalyFile() {
     
            Runnable runnable = new Thread(){
     
                @Override
                public void run(){
     
                    FileInputStream fstream = null;
                    try {
                        fstream = new FileInputStream(selectedItem);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(DesktopApplication3View.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    // Get the object of DataInputStream
                    DataInputStream in = new DataInputStream(fstream);
     
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    String strLine;      
     
                    try {
                        while ((strLine = br.readLine()) != null) {                      
                        //System.out.println(strLine);
                        MainTextArea.append(strLine+"\n");  // print out each line in the text file in jTextArea1
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
     
            Thread thread = new Thread(runnable);
            thread.start();    
     
        }
     
     
     
     
     
        @Action
        public void showAboutBox() {
            if (aboutBox == null) {
                JFrame mainFrame = DesktopApplication3.getApplication().getMainFrame();
                aboutBox = new DesktopApplication3AboutBox(mainFrame);
                aboutBox.setLocationRelativeTo(mainFrame);
            }
            DesktopApplication3.getApplication().show(aboutBox);
        }
     
        @Action
        public void showHiglightBox() {
            if (HighlightBox == null) {
                JFrame mainFrame = DesktopApplication3.getApplication().getMainFrame();
                HighlightBox = new DesktopApplication3HighlightKey(mainFrame);
                HighlightBox.setLocationRelativeTo(mainFrame);
            }
            DesktopApplication3.getApplication().show(HighlightBox);
        }
     
        @Action
        public void OpenFileDialoge() {
            Frame parent = new Frame();
            FileDialog fd = new FileDialog(parent, "Please choose a file:",FileDialog.LOAD);
    	fd.show();
    	selectedItem = fd.getDirectory() + fd.getFile(); // get the full directory of the file
            DispalyFile();
        }
     
     
        // Variables declaration - do not modify                     
        private javax.swing.JTextArea MainTextArea;
        private javax.swing.JLabel Satus;
        private javax.swing.JButton SearchButton;
        private javax.swing.JLabel StatusLabel;
        private javax.swing.JLabel StatusMessage;
        private javax.swing.JLabel StringSearchLabel;
        private javax.swing.JTextField StringSearchTextArea;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JPanel mainPanel;
        private javax.swing.JMenuBar menuBar;
        // End of variables declaration                   
     
        final Highlighter hilit;
        final Highlighter.HighlightPainter painter;
        final static Color  HILIT_COLOR = Color.YELLOW;
        private JDialog HighlightBox;
        private JDialog aboutBox;
    }



    thank you all
    Last edited by fortune2k; October 20th, 2010 at 01:46 PM.

  20. #19
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: newbie help threads

    SwingWorker or starting another thread will allow you to perform the long running task without the GUI locking up. Be sure that if you start another thread, to make ANY updates to the GUI using SwingUtilities.invoke later (some methods in a JTextArea are thread safe, but you have to read the API in detail to determine if calling a method of a Swing component is thread safe). SwingWorker provides utility methods to do this for you. See
    Worker Threads and SwingWorker
    Threads and Swing

  21. #20
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: newbie help threads

    i read somewhere that swingworker can only be run once , cant be canceld and cant be restarted is this true because i want to implement a cancel button and to have the ability to change the string search.

    Thanks copeg I will have a read tomo and play around see what i can do

Similar Threads

  1. How Can I run java threads
    By Saeid in forum Threads
    Replies: 12
    Last Post: August 6th, 2010, 02:12 PM
  2. Working with threads
    By tccool in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 12th, 2010, 10:21 AM
  3. threads in gui
    By urosz in forum AWT / Java Swing
    Replies: 1
    Last Post: November 3rd, 2009, 05:20 PM
  4. [SOLVED] Fixing of bug for a small program
    By Koren3 in forum Threads
    Replies: 3
    Last Post: April 21st, 2009, 06:28 AM