1

I want to draw a complex JFrame with inside a console this is my frame:

public class SearchWindows  extends JPanel {


    public ArrayList<String> res = new ArrayList();
    private JFrame frmSearchtool;
    private JTextField workDir;
    private JTextField outFile;
    private JTextField word;
    public static  String log = "";
    public JTextArea textArea;
    public TextAreaLogger taOutputStream;

    /**
     * Create the application.
     */
    public SearchWindows() {
           initialize();
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {

                    SearchWindows window = new SearchWindows();
                    window.frmSearchtool.setVisible(true);

                } catch (Exception e) {
                     System.out.println(e);
                }
            }
        });
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {

        frmSearchtool = new JFrame();
        frmSearchtool.setTitle("SearchTool");
        frmSearchtool.setBounds(100, 100, 1000, 812);
        frmSearchtool.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmSearchtool.getContentPane().setLayout(null);

        //Workdir   
        JLabel WorkDir = new JLabel("WorkDir");
        WorkDir.setFont(new Font("Franklin Gothic Demi Cond", Font.PLAIN, 17));
        WorkDir.setBounds(22, 13, 91, 30);
        frmSearchtool.getContentPane().add(WorkDir);

        JPanel pWorkDir = new JPanel();
        pWorkDir.setBounds(22, 40, 848, 30);
        frmSearchtool.getContentPane().add(pWorkDir);
        pWorkDir.setLayout(null);

        workDir = new JTextField();
        workDir.setAlignmentY(0.0f);
        workDir.setAlignmentX(0.0f);
        workDir.setBounds(5, 5, 837, 22);
        pWorkDir.add(workDir);
        workDir.setColumns(10);

        JButton btnBrowseDir = new JButton("Browse");
        btnBrowseDir.setBounds(882, 47, 87, 23);
        frmSearchtool.getContentPane().add(btnBrowseDir);
        btnBrowseDir.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            // For Directory
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.setAcceptAllFileFilterUsed(false);
            int rVal = fileChooser.showOpenDialog(null);
            if (rVal == JFileChooser.APPROVE_OPTION) {
                workDir.setText(fileChooser.getSelectedFile().toString());
            }
          }
        });


        //File CSV
        JLabel outputFile = new JLabel("OutputFile");
        outputFile.setFont(new Font("Franklin Gothic Demi Cond", Font.PLAIN, 17));
        outputFile.setBounds(22, 91, 138, 26);
        frmSearchtool.getContentPane().add(outputFile);

        JPanel pOutFile = new JPanel();
        pOutFile.setBounds(22, 116, 848, 30);
        frmSearchtool.getContentPane().add(pOutFile);
        pOutFile.setLayout(null);

        outFile = new JTextField();
        outFile.setBounds(5, 5, 837, 22);
        pOutFile.add(outFile);
        outFile.setColumns(10);

        JButton btnBrowseFile = new JButton("Browse");
        btnBrowseFile.setBounds(882, 123, 87, 23);
        frmSearchtool.getContentPane().add(btnBrowseFile);
        btnBrowseFile.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            // For File
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setAcceptAllFileFilterUsed(false);
            int rVal = fileChooser.showOpenDialog(null);
            if (rVal == JFileChooser.APPROVE_OPTION) {
                outFile.setText(fileChooser.getSelectedFile().toString());
            }
          }
        });

        //Word to Find      
        JLabel WordToSearch = new JLabel("WordToSearch");
        WordToSearch.setFont(new Font("Franklin Gothic Demi Cond", Font.PLAIN, 17));
        WordToSearch.setBounds(22, 165, 116, 35);
        frmSearchtool.getContentPane().add(WordToSearch);

        JPanel pWord = new JPanel();
        pWord.setBounds(22, 200, 504, 30);
        frmSearchtool.getContentPane().add(pWord);
        pWord.setLayout(null);

        word = new JTextField();
        word.setBounds(5, 5, 493, 22);
        pWord.add(word);
        word.setColumns(10);

        //Search button
        JButton search = new JButton("Search");
        search.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
                   try {
                           DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
                           Search s = new Search();

                           String workiDir = workDir.getText();
                           String outpFile = outFile.getText();
                           String wordSe = word.getText();

                           if ((Validator.validatePath(workiDir)) && 
                                 (Validator.validatePath(outpFile)) && 
                                   (Validator.validateWord(wordSe)) ) {

                                 System.out.println("workiDir: " + workiDir);
                                 System.out.println("outpFile: " + outpFile);
                                 System.out.println("wordSe: " + wordSe);

                                 Date date = new Date();
                                 String dat = dateFormat.format(date);

                                 ResultWriter rw = s.excecute(workiDir, wordSe, outpFile, res);

                                 Date date1 = new Date();
                                 String dat1 = dateFormat.format(date1);

                                 System.out.println("FINEEEEE!!!!  Start: " + dat + " Fine: " + dat1);
                                 System.out.println(" Trovati: " + res);

                                 rw.writeTxt(textArea.toString());
                                 rw.flushTxt();
                                 rw.closeTxt();
                         } else {

                                 if (!Validator.validatePath(workiDir)) {
                                   pWorkDir.setBackground(Color.RED);
                                   System.out.println(" La workDir inserita non valida");
                                 }
                                 if (!Validator.validatePath(outpFile)) {
                                   pOutFile.setBackground(Color.RED);
                                   System.out.println(" Il percorso del file inserito non valido");
                                 }
                                 if (!Validator.validateWord(wordSe)) {
                                   pWord.setBackground(Color.RED);
                                   System.out.println(" Inseri una parola da cercare");
                                 }
                       }
                    } catch (SAXException e1) {
                        System.out.println(e1);
                    } catch (ParserConfigurationException e1) {
                        System.out.println(e1);
                    } catch (IOException e1) {
                        System.out.println(e1);
                    }
                }
        });
        search.setBounds(582, 205, 97, 25);
        frmSearchtool.getContentPane().add(search);

        //Console
        JInternalFrame internalFrame = new JInternalFrame("Execution Log");
        internalFrame.setBounds(0, 243, 992, 537);
        internalFrame.setVisible(true);
        frmSearchtool.getContentPane().add(internalFrame);

        textArea = new JTextArea();
        JScrollPane sp = new JScrollPane(textArea);
        sp.setEnabled(true);
        sp.setAutoscrolls(true);
        textArea.setAutoscrolls(true);
        textArea.setLineWrap(false);
        textArea.setBorder(new LineBorder(new Color(0, 0, 0)));
        textArea.setBounds(12, 243, 857, 273);
        internalFrame.getContentPane().add(sp, BorderLayout.CENTER);
        taOutputStream = new TextAreaLogger(textArea);
        System.setOut(new PrintStream(taOutputStream));     
        int timerDelay = 1000;
        new Timer(timerDelay , new ActionListener() {       
           @Override
           public void actionPerformed(ActionEvent arg0) {
                // though this outputs via System.out.println, it actually displays
                // in the JTextArea:
               String logs = log;
               if(!logs.isEmpty()) { 
                System.out.println(logs);
               }
               logs = "";
             }
          }).start();
    }

}

The problem is that when I try to click search the execute method start, but it is so long and the console don't write while execute is running, then it print fine.

I need that the console print while execute is running, for have idea of what the app is doing.

The text area logger is this:

public class TextAreaLogger  extends OutputStream {

   private final JTextArea textArea;
   private final StringBuilder sb = new StringBuilder();
   private String title;

   public TextAreaLogger(final JTextArea textArea) {
      super();
      DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss");
      this.textArea = textArea;
      this.title =  dateFormat.format(new Date());

      int timerDelay = 1000;
      new Timer(timerDelay , new ActionListener() {       
         @Override
         public void actionPerformed(ActionEvent arg0) {

              title = dateFormat.format(new Date());
         }
      }).start();
      sb.append(title + "> ");
   }

   @Override
   public void flush() {
   }

   @Override
   public void write(int b) throws IOException {

      if (b == '\r')
         return;

      if (b == '\n') {
         final String text = sb.toString() + "\n";
           SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               textArea.append(text);
            }
         });
         sb.setLength(0);
         sb.append(title + "> ");
         return;
      }

      sb.append((char) b);
   }       
}

I know that invokeLater wait that all pending AWT events have finished. Some idea?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Dodo
  • 11
  • 1
  • 1
    You are invoking s.execute() on the event dispatcher thread, so no events will be dispatched until it completes. You should extend SwingWorker and invoke the execute() of your Search class (no code included in your question) from within the doInBackground() method that you will override in your SwingWorker subclass. – Palamino Dec 13 '18 at 21:48
  • 1
    `null` layouts, `MouseListener` on buttons, long running operations on the Event Dispatching Thread. So many things wrong it's hard to know where to even start with this. You should start with [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) to better understand the issue and [Worker Threads and SwingWorker](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) for a possible solution. – MadProgrammer Dec 13 '18 at 22:03
  • 1
    I'd also recommend [How to Use Buttons, Check Boxes, and Radio Buttons](https://docs.oracle.com/javase/tutorial/uiswing/components/button.html) and [How to Write an Action Listener](https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html) for better ways with dealing with buttons – MadProgrammer Dec 13 '18 at 22:03
  • Possible duplicate [How to set output stream to TextArea](https://stackoverflow.com/questions/12945537/how-to-set-output-stream-to-textarea/12945678#12945678) – MadProgrammer Dec 13 '18 at 22:05

0 Answers0