Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2009-04-23
9
Medium Priority
?
217 Views
Last Modified: 2013-11-23
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
0
Comment
Question by:coder-rl
  • 4
  • 3
7 Comments
 

Author Comment

by:coder-rl
ID: 24230398
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();
      }

   }
}
0
 
LVL 17

Expert Comment

by:Thomas4019
ID: 24234048
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

0
 

Author Comment

by:coder-rl
ID: 24245966
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
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 17

Expert Comment

by:Thomas4019
ID: 24246140
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

0
 

Author Comment

by:coder-rl
ID: 24265019
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

0
 
LVL 17

Accepted Solution

by:
Thomas4019 earned 2000 total points
ID: 24265658
First the easy question, to make it non-resizable. Just call setResizable(false) in your JFrame.

I think this.pack() does not work well with GridLayouts. Pack is not a necessary call, it just tells the frame to try and compact itself as small as possible. So really its not necessary. Also note usually you want this.setVisible(true); to be the last line of your GUI code, often at the end of the constructor.

The JPanel in your code seems superfluous (not really needed). If you look at my code earlier you can see that you can directly add the JButton and JTextArea to the window. Your JPanel way is not inefficient just probably a little longer code.

There are times when JPanel are necessary and can be very useful. There are really two instances when you use them often.

1. When you want to be able switch around the GUI like pages. So you create a JPanel panel1 add a bunch of stuff and a JPanel panel2 and add stuff. Then you can remove panel1 and add panel2 or vice versa. So to switch the GUI completely it is really simple.

2. The other case is when you want a complex layout. For example if i want Grid of 4 JButtons and 4 JLabels on the top of the screen and maybe 3 JButtons centered on the bottom of the frame. Then you create two panels. A top panel and add it to the north. A lower panel and add it to the south. You can then set the top layout to be a GridLayout and set the bottom panels layout to be a FlowLayout. So in conclusion, JPanels let you nest layouts to create complicated GUIs.
0
 

Author Closing Comment

by:coder-rl
ID: 31573947
Hi Thomas,

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

Coder-rl
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month20 days, 22 hours left to enroll

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

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

Join & Ask a Question