Link to home
Start Free TrialLog in
Avatar of coder-rl
coder-rl

asked on

How can I display messages in running an application to a dialog box with a OK button?

For an program that opens and reads a list of files. How can I have dialog box with only a OK button and an area that displays:

<file1> opened...
...<file1> read.

<file2> opened...
...<file2> read.

etc
as the program runs, not displaying the entire message at the end of running the program and then the OK button will do system.exit(0)?

Thanks,

coder-rl
Avatar of coder-rl
coder-rl

ASKER

I can use the enclosed code to output messages from time to time by adding text to textarea while the textarea is up, but without the dialog window with the OK button as in JOptionPane.

But how can I achieve the same effect with the textarea inside the JOptionPane?

Thanks,

Coder-RL

import java.awt.*;
import javax.swing.*;

public class TextAreaDemoB extends JFrame {

    //============================================== instance variables
    // JTextArea _resultArea = new JTextArea(6, 20);
    JTextArea a_resultArea = new JTextArea(20, 30);
    String str = "this is a test.";
       
    //====================================================== constructor
    public TextAreaDemoB() {

        //... Set textarea's initial text, scrolling, and border.
        this.a_resultArea.setText("Enter more text to see scrollbars");
        JScrollPane scrollingArea = new JScrollPane(this.a_resultArea);
       
        //... Get the content pane, set layout, add to center
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(scrollingArea, BorderLayout.CENTER);
       
        //... Set window characteristics.
        this.setContentPane(content);
        this.setTitle("TextAreaDemo B");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();

    }
   
    //======================================================
    public JTextArea getAreaDemoB() {
      return this.a_resultArea ;
    }
    //======================================================
    public String getStr() {
      return this.str ;
    }
   //============================================================= main
    public static void main(String[] args) {
    // static void main(String[] args) {
      try {

        // JFrame win = new TextAreaDemoB();
        // win.setVisible(true);

      Long stoptime = 5000L; //5 Seconds
        TextAreaDemoB win = new TextAreaDemoB();
        win.setVisible(true);

      Thread.sleep(stoptime);
      win.a_resultArea.append ("\nadd text 1");
      Thread.sleep(stoptime);
      win.a_resultArea.append ("\nadd text 2");
      Thread.sleep(stoptime);
      win.a_resultArea.append ("\nadd text 3");

        win.setVisible(false);
         // display results
      // JOptionPane.showMessageDialog(
      //       null, win.getAreaDemoB() , "Status" , JOptionPane.INFORMATION_MESSAGE );

      JOptionPane.showMessageDialog(
            null, win.a_resultArea  , "Status" , JOptionPane.INFORMATION_MESSAGE );

      String str_1 = win.getStr();
      System.out.println(str_1);
      System.exit( 0 ); // terminate application

      } catch (InterruptedException e) {
      e.printStackTrace();
      }

   }
}
You could make a class something like this, except without the main method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
class Log extends JFrame implements ActionListener
{
	JTextArea area;
 
	Log()
	{
		setSize(320,240);
 
		area = new JTextArea();
 
		JScrollPane jsp = new JScrollPane(area);
		add(jsp,BorderLayout.CENTER);
 
		JButton ok = new JButton("OK");
		add(ok,BorderLayout.SOUTH);
	}
 
	void post(String s)
	{
		area.setText(area.getText() + (area.getText().length() != 0?"\n":"") + s);
		area.setCaretPosition(area.getText().length());//Scrolls pane to bottom
	}
 
	public void actionPerformed(ActionEvent evt)
	{
		setVisible(false);
	}
 
	public static void main(String args[])
	{
		Log l = new Log();
		l.setVisible(true);
 
		l.post("Started");
 
		try
		{
			Thread.sleep(1000);
		}
		catch(InterruptedException e){}
 
		l.post("Running");
	}
}

Open in new window

Hi Thomas,

A few more questions:
How can I make the event on clicking the OK button to close the window to return the control to the program so that I can then call System.exit( 0 )?

How can I make the text area non-editable? Currently, I can go in and do backspace to erase the output message?

Thanks for your response,

coder-rl
to make a text area non editable just use "area.setEditable(false)". Currently with the code i posted, the window was designed to be "non modal". A modal window is a window like a JOptionPane that suspends the current thread and wont resume the program until the window is finished. The Log viewer i wrote was designed not to block the thread so that it runs mostly independent of the other code.
So ideally, your program creates the "Log", then sets it visible. Then your program does its task and peridically posts new events to the log and then once its done calls System.exit(0); During this whole process the log window would be visible and updating.
To make the window stay open until the user click "OK" even if the tasks have been completed. i would add the attached method to Log. Then at the end of your program you call "waitUntilClosed()" and then System.exit()

public void waitUntilClosed()
{
	while(isVisible())
	{
		try
		{
			Thread.sleep(30);
		}
		catch(InterruptedException e){}
	}
}

Open in new window

Hi Thomas,

Thanks for the code and I am happy to accept it as solution.

May I ask a few more question before doing that? I am afraid that I cannot continue to ask related question once I click "Accept as Solution".

To try to understand more, I was reading and experimenting with the code and here I have now:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class logGUI extends JFrame
{
       // JTextArea log_msg_area = new JTextArea();
       // JTextArea log_msg_area = new JTextArea(20, 30);
       JTextArea log_msg_area = new JTextArea(20, 40);
      JScrollPane log_msg_area_scrolling_area = new JScrollPane( this.log_msg_area );

      JButton run = new JButton("Run the application");
      JButton exit = new JButton("Exit");

      JPanel log_content_P = new JPanel();

      logGUI() // the constructor
      {

            // this.log_content_P.setLayout(new GridLayout(4,1,2,2));
            // this.log_content_P.setLayout(new BorderLayout()); // strange combination effect with this.pack()

            //... Set text area characteristics.
            this.log_msg_area.setEditable(false);
            this.log_content_P.add( this.log_msg_area_scrolling_area , BorderLayout.CENTER);

            //... Set button characteristics.
            this.exit.addActionListener(new ExitHandler());
            this.log_content_P.add( this.exit , BorderLayout.SOUTH );

            // ... set this JFrame window characteristics.
            // "this" is a JFrame object as it is an extension of it.
            // super("Status");
            // this.setBounds(100,100,250,150);
            this.setVisible(true);
            this.setSize(320,240);
            this.setTitle("Status of Running Application");
            this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            // this.setDefaultCloseOperation( EXIT_ON_CLOSE );
            this.setContentPane( this.log_content_P );
            // do not use this/ this.getContentPane().add("Center" , this.log_content_P);
            this.pack(); // this line counter-act the this.log_content_P.setLayout(new BorderLayout()); line

      }

      void post(String s)
      {
            log_msg_area.setText(log_msg_area.getText() + (log_msg_area.getText().length() != 0?"\n":"") + s);
            log_msg_area.setCaretPosition(log_msg_area.getText().length());//Scrolls pane to bottom
      }

      // add inner class event handler for each button here
      class ExitHandler implements ActionListener
      {
         public void actionPerformed(ActionEvent e)
         {
            System.exit(0);
         }
      }

      void take_a_break (int t)
      {
            try
            {
                  Thread.sleep(t);
            }
            catch(InterruptedException e){}
      }

      public static void main(String args[])
      {
               // new logGUI();

            logGUI l = new logGUI();
            l.setVisible(true);
 
            l.post("Started");
 
            l.take_a_break (2000);
 
            l.post("Running");

            l.take_a_break (2000);
 
            l.post("take a break ...");
 
            l.take_a_break (2000);
 
            l.post("Done!");
      }
}

In this code I added the textarea and the button onto a JPanel. It works about the same way. So my first question is when will a JPanel really be needed in making a UI?

At the moment, users can resize the window by using the mouse to drag the edge of the window. How can I make the window not resizeable?

Thanks again,

Robert

ASKER CERTIFIED SOLUTION
Avatar of Thomas4019
Thomas4019
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Thomas,

I got it. Thanks very much for your patience in teaching me about the topic.

Coder-rl