Updating textArea inside iteration - java

i have a fun project where i need to change the content of a text area inside a iteration.
Its a character, a "projectile", moving trought a string. The string is updated and sent to the textArea inside the iteration, and the iteration stops when the character reaches a wall.
But my textArea only updates (visually) when i leave the iteration. While im inside it, textArea freezes, as if its waiting for the iteration, even with Thread.sleep() inside it.
I made an MVCE exemplifing the problem bellow, notice the text only shows after the iteration, i want it to apper in every step of the while.
public class GUIProblem extends JFrame{
public GUIProblem() {
setSize(640, 480);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
final JTextArea textArea = new JTextArea();
textArea.setRows(10);
textArea.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
int i = 0;
while(i < 10){
textArea.setText("this text only appears after the iteration, i want it to appear in each step of the iteration!");
System.out.println("iterating..." + i++);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
textArea.setColumns(30);
panel.add(textArea);
}
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUIProblem gui = new GUIProblem( );
gui.setVisible(true);
}
});
JOptionPane.showMessageDialog(null, "Click the textArea!");
}
}

You've a classic Swing threading issue where you stop the Swing event thread in its tracks with your iteration and its Thread.sleep() calls. The solution is the same as for similar questions: use a Swing Timer or background thread such as a SwingWorker. In your case, use the Timer.
For example, since you posted an MCVE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIProblem extends JFrame {
public GUIProblem() {
// setSize(640, 480);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
final JTextArea textArea = new JTextArea(20, 50);
textArea.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent mEvt) {
int i = 0;
int timerDelay = 200;
new Timer(timerDelay, new ActionListener() {
int count = 0;
private final int MAX_COUNT = 10;
#Override
public void actionPerformed(ActionEvent e) {
if (count >= MAX_COUNT) {
((Timer) e.getSource()).stop(); // stop the timer
return;
}
textArea.append("Count is: " + count + "\n");
count++;
}
}).start();
}
});
panel.add(new JScrollPane(textArea));
}
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUIProblem gui = new GUIProblem();
gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
gui.pack();
gui.setLocationRelativeTo(null);
gui.setVisible(true);
}
});
JOptionPane.showMessageDialog(null, "Click the textArea!");
}
}

Related

Why is my thread not working properly in Swing?

I am printing simple value to append JTextArea using simple for loop, and when I run it, it's properly Run if I print value in console output...
But if I append JTextArea and print value in the text area, they are appended all after whole program run.
public class SwingThread {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingThread window = new SwingThread();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SwingThread() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
JButton btnNewButton = new JButton("New button");
scrollPane.setColumnHeaderView(btnNewButton);
btnNewButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
try
{
for(int i = 0 ; i <= 5 ; i++)
{
textArea.append("Value "+i+"\n");
System.out.println("Value is" + i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println("Error : "+e);
}
}
});
}
}
I want to append one by one, but it was appended after the whole program runs.
Your problem is with your use of Thread.sleep, since when you call this on the Swing event thread (or EDT for Event Dispatch Thread) as you are doing, it will put the entire Swing event thread to sleep. When this happens the actions of this thread cannot be performed, including painting the GUI (updating it) and interacting with the user, and this will completely freeze your GUI -- not good. The solution in this current situation is to use a Swing Timer as a pseudo-loop. The Timer creates a loop within a background thread and guarantees that all code within its actionPerformed method will be called on the Swing event thread, a necessity here since we don't want to append to the JTextArea off of this thread.
Also as others have noted, if all you want to do is to perform a repeated action with delay in Swing, then yes, use this Swing Timer. If on the other hand you wish to run a long-running bit of code in Swing, then again this code will block the EDT and will freeze your program. For this situation use a background thread such as one supplied by a SwingWorker. Please check out Lesson: Concurrency in Swing for more on this.
e.g.,
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// delay between timer ticks: 1000
int timerDelay = 1000;
new Timer(timerDelay, new ActionListener() {
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e) {
// timer's stopping condition
if (counter >= MAX_VALUE) { // MAX_VALUE is a constant int = 5
((Timer) e.getSource()).stop();
} else {
textArea.append("Value " + counter + "\n");
}
counter++; // increment timer's counter variable
}
}).start();
}
});
The whole thing:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
public class SwingThread2 {
protected static final int MAX_VALUE = 5; // our constant
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingThread2 window = new SwingThread2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SwingThread2() {
initialize();
}
private void initialize() {
frame = new JFrame();
// frame.setBounds(100, 100, 450, 300); // avoid this
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea(15, 40);
scrollPane.setViewportView(textArea);
JButton btnNewButton = new JButton("New button");
scrollPane.setColumnHeaderView(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// delay between timer ticks: 1000
int timerDelay = 1000;
new Timer(timerDelay, new ActionListener() {
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e) {
// timer's stopping condition
if (counter >= MAX_VALUE) { // MAX_VALUE is a constant int = 5
((Timer) e.getSource()).stop();
} else {
textArea.append("Value " + counter + "\n");
}
counter++; // increment timer's counter variable
}
}).start();
}
});
// better to avoid setting sizes but instead to
// let the components size themselves vis pack
frame.pack();
frame.setLocationRelativeTo(null);
}
}
Just for further information, here is an example of the same program above that uses a SwingWorker to perform a long running action, and then update a JProgressBar with this action. The worker is quite simple, and simply uses a while loop to advance a counter variable by a bounded random amount. It then transmits uses this value to update its own progress property (a value that can only be from 0 to 100, and so in other situations, the value will need to be normalized to comply with this). I attach a PropertyChangeListener to the worker, and this is notified on the Swing event thread whenever the worker's progress value changes and also whenever the SwingWorker changes state, such as when it is done operating. In the latter situation, the worker's StateValue becomes StateValue.DONE. The listener then updates the GUI accordingly. Please ask if any questions.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
public class SwingThread2 {
protected static final int MAX_VALUE = 5; // our constant
private JFrame frame;
private JProgressBar progressBar = new JProgressBar();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingThread2 window = new SwingThread2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SwingThread2() {
initialize();
}
private void initialize() {
frame = new JFrame();
// frame.setBounds(100, 100, 450, 300); // avoid this
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea(15, 40);
scrollPane.setViewportView(textArea);
JButton btnNewButton = new JButton("New button");
scrollPane.setColumnHeaderView(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// delay between timer ticks: 1000
int timerDelay = 1000;
new Timer(timerDelay, new ActionListener() {
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e) {
// timer's stopping condition
if (counter >= MAX_VALUE) { // MAX_VALUE is a constant
// int = 5
((Timer) e.getSource()).stop();
} else {
textArea.append("Value " + counter + "\n");
}
counter++; // increment timer's counter variable
}
}).start();
}
});
progressBar.setStringPainted(true);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(new JButton(new MyAction("Press Me")));
bottomPanel.add(progressBar);
frame.getContentPane().add(bottomPanel, BorderLayout.PAGE_END);
// better to avoid setting sizes but instead to
// let the components size themselves vis pack
frame.pack();
frame.setLocationRelativeTo(null);
}
private class MyAction extends AbstractAction {
public MyAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
progressBar.setValue(0);
setEnabled(false);
MyWorker myWorker = new MyWorker();
myWorker.addPropertyChangeListener(new WorkerListener(this));
myWorker.execute();
}
}
private class WorkerListener implements PropertyChangeListener {
private Action action;
public WorkerListener(Action myAction) {
this.action = myAction;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
int progress = (int) evt.getNewValue();
progressBar.setValue(progress);
} else if ("state".equals(evt.getPropertyName())) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
action.setEnabled(true);
#SuppressWarnings("rawtypes")
SwingWorker worker = (SwingWorker) evt.getSource();
try {
// always want to call get to trap and act on
// any exceptions that the worker might cause
// do this even though get returns nothing
worker.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}
}
private class MyWorker extends SwingWorker<Void, Void> {
private static final int MULTIPLIER = 80;
private int counter = 0;
private Random random = new Random();
#Override
protected Void doInBackground() throws Exception {
while (counter < 100) {
int increment = random.nextInt(10);
Thread.sleep(increment * MULTIPLIER);
counter += increment;
counter = Math.min(counter, 100);
setProgress(counter);
}
return null;
}
}
}

Java Swing--- No errors or exceptions, but program doesn't seem to be working

Before I start, I've looked over my code for literally 4 hours till I couldn't look any more, and coming here was a last resort, don't want to waste anyones time with dumb questions, but, anyways; Working on my simon game to help teach myself Java, and several problems. First off, the showPattern method seems to be all wonky. Notably, it doesn't seem to be showing the same pattern with one new color each time as intended. Also, when the correct button is clicked, the current/high score is not updating. These are the only errors I've detected so far, there may be others.
I'm only posting the entire program so that you can copy and test it. Sorry if it's a little long. I really appreciate any help, please don't be cynical like some of the other people.
package simon;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color.*;
import javax.swing.Timer;
/**
* Main Class
* #author Chris Mailloux
*/
class Simon
{
public static void main (String[] args)
{
window.setBackground(Color.BLACK);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Static object creations.
public static GameWindow window = new GameWindow();
// Variable declarations.
public static final String[] colors = {"Green", "Red", "Yellow", "Blue"};
public static ArrayList<String> pattern = new ArrayList<String>();
public static int currentScore = 0;
public static int iterator = 0;
public static boolean isPlayerTurn = false;
public static int highScore = 0; // TEMPORARY
}
/**
* Class for main game window.
* #author Chris
*/
class GameWindow extends JFrame
{
GameWindow()
{
// Set basic properties of frame.
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("Simon");
setResizable(true);
setLocation(DEFAULT_HORIZONTAL_LOCATION, DEFAULT_VERTICAL_LOCATION);
// PLACEHOLDER FOR IMAGE ICON
// Adding Border layout helper panel.
BorderPanel borderPanel = new BorderPanel();
add(borderPanel);
}
// Declaring window positioning constants.
public static final int DEFAULT_WIDTH = 800;
public static final int DEFAULT_HEIGHT = 800;
// TEMPORARY PLACEHOLDER FOR SCREENSIZE CALCULATIONS
public static final int DEFAULT_HORIZONTAL_LOCATION = 0;
public static final int DEFAULT_VERTICAL_LOCATION = 0;
}
/**
* Class to hold the buttonsPanel
* #author Chris
*/
class ButtonsPanel extends JPanel
{
// Creating JButtons for gameplay.
public static JButton greenButton = new JButton();
public static JButton redButton = new JButton();
public static JButton yellowButton = new JButton();
public static JButton blueButton = new JButton();
ButtonsPanel()
{
setBackground(Color.BLACK);
// Setting grid layout (with spaces)
setLayout(new GridLayout(2, 2, 20, 20));
// Setting background color of buttons.
greenButton.setBackground(Color.GREEN); // NEED COLOR CONSTANTS
redButton.setBackground(Color.RED);
yellowButton.setBackground(Color.YELLOW);
blueButton.setBackground(Color.BLUE);
// Add buttons to panel. (In order)
add(greenButton);
add(redButton);
add(yellowButton);
add(blueButton);
// Creating ActionListeners for 4 main buttons.
ActionListener greenAction = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
greenClicked();
}
};
ActionListener redAction = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
redClicked();
}
};
ActionListener yellowAction = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
yellowClicked();
}
};
ActionListener blueAction = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
blueClicked();
}
};
// Associate actions with buttons.
greenButton.addActionListener(greenAction);
redButton.addActionListener(redAction);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
}
public static final int delay = 400;
// Handling button activations.
public static void greenClicked()
{
// Handling button Coloring/timing.
greenButton.setBackground(Color.WHITE);
greenButton.repaint();
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
greenButton.setBackground(Color.GREEN);
}
};
Timer timer = new Timer(delay, taskPerformer);
timer.setRepeats(false);
timer.start();
// Handling button Action
if(Game.isPlayerTurn == true)
{
Game.check("Green");
}
}
public static void redClicked()
{
// Handling button color and timing.
redButton.setBackground(Color.WHITE);
redButton.repaint();
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
redButton.setBackground(Color.RED);
}
};
Timer timer = new Timer(delay, taskPerformer);
timer.setRepeats(false);
timer.start();
// Handling button actions.
if(Game.isPlayerTurn == true)
{
Game.check("Red");
}
}
public static void yellowClicked()
{
// Handling button color and timing.
yellowButton.setBackground(Color.WHITE);
yellowButton.repaint();
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
yellowButton.setBackground(Color.YELLOW);
}
};
Timer timer = new Timer(delay, taskPerformer);
timer.setRepeats(false);
timer.start();
// Handling button actions.
if(Game.isPlayerTurn == true)
{
Game.check("Yellow");
}
}
public static void blueClicked()
{
// Handling button color and timing.
blueButton.setBackground(Color.WHITE);
blueButton.repaint();
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
blueButton.setBackground(Color.BLUE);
}
};
Timer timer = new Timer(delay, taskPerformer);
timer.setRepeats(false);
timer.start();
// Handling button actions.
if(Game.isPlayerTurn == true)
{
Game.check("Blue");
}
}
}
/**
* Menu buttons panel.
* #author Chris Mailloux
*/
class MenuPanel extends JPanel
{
static JButton startButton;
static JButton scoreDisplay;
static JButton highScoreDisplay;
public MenuPanel()
{
setBackground(Color.BLACK);
// Menu panel buttons.
startButton = new JButton("Start");
scoreDisplay = new JButton(String.valueOf(Simon.currentScore));
highScoreDisplay = new JButton(String.valueOf(Simon.highScore));
// Adding Buttons
add(startButton);
add(scoreDisplay);
add(highScoreDisplay);
// Setting background colors
scoreDisplay.setBackground(Color.BLACK);
highScoreDisplay.setBackground(Color.BLACK);
startButton.setBackground(Color.BLUE);
// Disabling displays
scoreDisplay.setEnabled(false);
highScoreDisplay.setEnabled(false);
// ActionListeners for menu buttons.
ActionListener startButtonAction = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Game.startGame();
}
};
startButton.addActionListener(startButtonAction);
startButton.setFocusable(false);
}
}
/**
* Border Panel support class.
* #author Chris Mailloux
*/
class BorderPanel extends JPanel
{
BorderPanel()
{
setLayout(new BorderLayout());
add(new MenuPanel(), BorderLayout.NORTH);
add(new ButtonsPanel(), BorderLayout.CENTER);
}
}
/**
* Main game logic class.
* #author Chris
*/
class Game extends Simon
{
// Resets variables for new game.
public static void startGame()
{
isPlayerTurn = false;
pattern.clear();
currentScore = 0;
iterator = 0;
gamePlay(); // Should Start game
}
public static void gamePlay()
{
if (isPlayerTurn == false)
{
computerTurn();
}
else
{
playerTurn();
}
}
public static void computerTurn()
{
// Isn't working.
ButtonsPanel.greenButton.setEnabled(false);
ButtonsPanel.redButton.setEnabled(false);
ButtonsPanel.yellowButton.setEnabled(false);
ButtonsPanel.blueButton.setEnabled(false);
iterator = 0; // So CPU can use iterator to show pattern.
Random generator = new Random();
int randInt = generator.nextInt(4);
String randColor = colors[randInt];
System.out.println(randColor); // For testing.
pattern.add(new String(randColor));
showPattern();
}
public static void playerTurn()
{
iterator = 0;
ButtonsPanel.greenButton.setEnabled(true);
ButtonsPanel.redButton.setEnabled(true);
ButtonsPanel.yellowButton.setEnabled(true);
ButtonsPanel.blueButton.setEnabled(true);
}
/**
* Handles scoring and checks inputs for correctness.
* #author Chris Mailloux
*/
public static void check(String lastInput)
{
if (lastInput.equals(pattern.get(iterator)))
{
iterator++;
if(iterator > currentScore)
{
currentScore++;
MenuPanel.scoreDisplay.repaint();
if(currentScore > highScore)
{
highScore++;
// PLACEHOLDER TO WRITE HIGHSCORE TO FILE.
}
}
if (iterator == pattern.size());
{
isPlayerTurn = false;
computerTurn();
}
}
else
{
gameOver();
}
}
public static void showPattern()
{
int j = 0;
while (j < pattern.size())
{
String showerHelper = pattern.get(j); // Helper variable.
switch (showerHelper)
{
case "Green" : ButtonsPanel.greenClicked();
case "Red" : ButtonsPanel.redClicked();
case "Yellow" : ButtonsPanel.yellowClicked();
case "Blue" : ButtonsPanel.blueClicked();
break; // Fallthrough handler.
default: System.out.println("Error: Invalid value for pattern"
+ " ArrayList, or improper storage of variable in the"
+ " showerHelper variable.");
}
j++;
}
isPlayerTurn = true;
gamePlay();
}
public static void gameOver()
{
System.out.println("YOU LOSE!");
// PLACEHOLDER TO PLAY GAMEOVER SOUND
}
} // End of game class.
As a side question, how would I go about playing a tone when a button is activated, like the simon handheld game? Also, how can I save highscore in some way that when the program closes, highscore is saved for next use?
The Thread will block the UI. You should use Timer. So instead of using Thread
try
{
Thread.sleep(400);
}
catch(InterruptedException e)
{
}
blueButton.setBackground(Color.BLUE);
the code could be:
int delay = 400; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
blueButton.setBackground(Color.BLUE);
}
};
Timer timer = new Timer(delay, taskPerformer);
timer.setRepeats(false);
timer.start();

How to update the JTextField when the variable value is changed?

I have two Java(.java) files. One has a JButton and JTextField and the other has a Thread. In first Java file, I have added an ActionListener to the JButton so that, when the button is pressed, a thread (object for 2nd .java file in created and thread is initiated) runs which modifies an integer variable continuously. How to display the value of that integer variable (of 2nd .java file) in the JTextField (of 1st .java file) ?
Detection.java
package sample;
public class Detection implements Runnable
{
public String viewers;
public int count;
public void run()
{
try
{
while (true)
{
// i have written code for displaying video.
// and it say how many no. of people in the video
// the no of people is stored in a variable "count"
viewers=""+count; //storing count as string so as to display in the JTextField
}
}
catch (Exception e)
{
System.out.println("Exception: "+e);
}
}
}
UsrInterfac.java
//build using WindowBuilder eclipse juno
package sample;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UsrInterfac
{
private JFrame frame;
private JTextField textField;
Detection dd = new Detection();
Thread th = new Thread(dd);
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
UsrInterfac window = new UsrInterfac();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UsrInterfac()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnStartThread = new JButton("Start Thread");
btnStartThread.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
th.start();
}
});
btnStartThread.setBounds(59, 133, 117, 23);
frame.getContentPane().add(btnStartThread);
textField = new JTextField();
textField.setBounds(270, 134, 104, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
}
}
Starting from the basics, while using Swing, it is always best to use LayoutManagers, which can make your work much more easier, in comparison to using Absolute Positioning.
Whenever one needs to change something in the View from some another thread, it is always advisable to do that using EventQueue.invokeLater(...)/EventQueue.invokeAndWait(...).
This small sample program, might be able to help you get an idea, how to accomplish what you so desire :-)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ThreadCounter
{
private CustomThread cThread;
private JTextField tField;
private JButton button;
private int counter;
public ThreadCounter()
{
counter = 0;
}
private void displayGUI()
{
JFrame frame = new JFrame("Thread Counter Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
tField = new JTextField(10);
tField.setText("0");
button = new JButton("Start");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (counter == 0)
{
cThread = new CustomThread(tField);
cThread.setFlagValue(true);
cThread.start();
counter = 1;
button.setText("Stop");
}
else
{
try
{
cThread.setFlagValue(false);
cThread.join();
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
counter = 0;
button.setText("Start");
}
}
});
contentPane.add(tField);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ThreadCounter().displayGUI();
}
});
}
}
class CustomThread extends Thread
{
private int changingVariable;
private JTextField tField;
private boolean flag = true;
public CustomThread(JTextField tf)
{
changingVariable = 0;
tField = tf;
}
public void setFlagValue(boolean flag)
{
this.flag = flag;
}
#Override
public void run()
{
while (flag)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
tField.setText(
Integer.toString(
++changingVariable));
}
});
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
System.out.println("I am OUT of WHILE");
}
}
Ideally you should post your code. Anyway, when you are calling the thread code, either pass the instance of the first class (object) or an instance of JTextField, so that the thread can set the new value in the text field.

Swing rendering problem of busy cursors when using modal dialogs on Linux

When setting a busy cursor on the glass pane of the application frame after closing a modal dialog, the busy cursor is not always displayed. Sometimes it works (the first time it is mostly always working), sometimes not.
Even better, when setting the busy cursor before opening the dialog. The busy cursor get displayed but when moving the mouse inside and then outside the dialog the busy cursor is not displayed anymore.
Note that I observe the following bug on Linux only. On Mac OS X or Windows the behavior is deterministic and consistent.
Another hint, in the first case of the code sample, when the mouse is NOT entering the dialog and the YES_OPTION is selected using the keyboard, the busy mouse cursor is always shown. Also in this case, the "Please wait..." label on the glass pane get never painted.
Here a SSCCE demonstrating these bugs:
import java.awt.event.*;
import javax.swing.*;
public class TestFrame extends JFrame {
private JPanel panel;
private JPanel glassPane;
public TestFrame() {
final JButton button1 = new JButton(new AbstractAction("Start activity indicator after closing the dialog") {
#Override
public void actionPerformed(ActionEvent e) {
doAction1();
}
});
final JButton button2 = new JButton(new AbstractAction("Start activity indicator before opening the dialog") {
#Override
public void actionPerformed(ActionEvent e) {
doAction2();
}
});
panel = new JPanel();
panel.add(button1);
panel.add(button2);
getContentPane().add(panel, BorderLayout.NORTH);
glassPane = (JPanel) getGlassPane();
glassPane.setLayout(new BorderLayout());
glassPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
glassPane.add(new JLabel("Please Wait..."), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setVisible(true);
}
public void doAction1() {
System.out.println("IsStartingInEDT?: "+ SwingUtilities.isEventDispatchThread());
final int response = JOptionPane.showConfirmDialog(this, "Click on the YES_OPTION, busy indicator must start (if it does, try again).");
if (JOptionPane.YES_OPTION == response) {
startActivity();
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
}
stopActivity();
}
}
public void doAction2() {
startActivity();
System.out.println("IsStartingInEDT?: "+ SwingUtilities.isEventDispatchThread());
final int response = JOptionPane.showConfirmDialog(this, "Move the mouse inside the dialog (me) and then outside, the busy indicator is not shown anymore");
if (JOptionPane.YES_OPTION == response) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
}
}
stopActivity();
}
public void startActivity() {
System.out.println("TestFrame.startActivity()");
glassPane.setVisible(true);
}
public void stopActivity() {
System.out.println("TestFrame.stopActivity()");
glassPane.setVisible(false);
}
/**
* #param args
*/
public static void main(String[] args) {
new TestFrame();
}
}
At the moment I did not find any related issues in the JavaBug parade. I will search further before opening a new one.
I also already read the following article but it is not very convenient as making a good modal dialog from a non-modal one is not straightforward:
http://www.javaspecialists.eu/archive/Issue065.html
Can anyone provide some help?
Thanks in advance, Pierre
You have some threading issue here.
Is IsStartingInEDT true?
If yes, you are doing it wrong because:
You should not sleep in UI thread. This would stop the screen update.
If no, you are doing it wrong because:
OptionPane.showConfirmDialog() must be called from the UI thread.
you should do something like this:
public void doAction1() {
if (!SwingUtilities.isEventDispatchThread()) {
System.err.println("error, must be edt");
return;
}
final int response = JOptionPane.showConfirmDialog(this, "Click on the YES_OPTION, busy indicator must start (if it does, try again).");
if (JOptionPane.YES_OPTION == response) {
startActivity(); // change glass panel in edt
// new thread for long standing task
new Thread( new Runnable() { public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
}
SwingUtilities.invokeAndWait(new Runnable(){ public void run() {
// changing glass panel need edt
stopActivity();
});
}).start();
}
}
1st. by using Tread.sleep(int) pretty sure to block EDT, with all issues desribed about Concurrency in Swing
2.nd works because initializations for JOptionPane create a new EDT
here is simple demonstrations about ...., please that only example and be sure that is against all Swing rules, but demostrated lock and unlock EDT by usage Tread.sleep(int) during EDT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ShakeComponents1 {
private JFrame frame = new JFrame();
private final String items[] = {"One", "Two", "Three"};
private Timer timer;
private JPanel panel = new JPanel();
private JPanel buttonPanel = new JPanel();
private JButton button = new JButton(" Exit ");
private boolean repeats = true;
private boolean runs = false;
private Color clr[] = {Color.red, Color.blue, Color.magenta};
private Insets initMargin;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ShakeComponents1().makeUI();
}
});
}
public void makeUI() {
buttonPanel = new JPanel();
buttonPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
buttonPanel.setLayout(new BorderLayout());
button.setPreferredSize(new Dimension(100, 45));
button.setForeground(Color.darkGray);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
Runnable doRun = new Runnable() {
#Override
public void run() {
System.exit(0);
}
};
SwingUtilities.invokeLater(doRun);
}
});
button.addMouseListener(new java.awt.event.MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
if (runs) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
runs = false;
timer.stop();
changePnlBorder(new EmptyBorder(5, 5, 5, 5));
changeBtnForegroung(Color.darkGray);
}
});
}
}
#Override
public void mouseExited(MouseEvent e) {
if (!runs) {
timer.start();
runs = true;
}
}
});
buttonPanel.add(button);
final Insets margin = button.getMargin();
panel.add(buttonPanel);
for (int i = 0; i < 2; i++) {
JComboBox combo = new JComboBox(items);
combo.setMinimumSize(new Dimension(50, 25));
combo.setMaximumSize(new Dimension(150, 25));
combo.setPreferredSize(new Dimension(100, 25));
combo.addActionListener(new ShakeAction());
panel.add(combo);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocation(50, 50);
frame.setVisible(true);
timer = new Timer(500, new ShakeAction());
timer.setRepeats(repeats);
initMargin = button.getMargin();
}
private class ShakeAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private int noColor = 0;
private Border border;
private int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
if (count > 5) {
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
changeBtnForegroung(Color.darkGray);
Thread.sleep(500);
count = 0;
Thread.sleep(750);
} catch (Exception e) {
System.out.println(e);
}
}
}).start();
} else {
new Thread(new Runnable() {
#Override
public void run() {
try {
runs = true;
if (noColor < 2) {
noColor++;
changeBtnForegroung(clr[noColor]);
} else {
noColor = 0;
changeBtnForegroung(clr[noColor]);
}
changeBtnMargin(new Insets(initMargin.top, initMargin.left + 10, initMargin.bottom, initMargin.right - 10));
border = new EmptyBorder(0, 5, 10, 5);
changePnlBorder(border);
Thread.sleep(100);
changeBtnMargin(new Insets(initMargin.top, initMargin.left - 10, initMargin.bottom, initMargin.right + 10));
border = new EmptyBorder(0, 0, 10, 10);
changePnlBorder(border);
Thread.sleep(100);
changeBtnMargin(new Insets(initMargin.top, initMargin.left + 10, initMargin.bottom, initMargin.right - 10));
border = new EmptyBorder(5, 10, 5, 0);
changePnlBorder(border);
Thread.sleep(100);
changeBtnMargin(new Insets(initMargin.top, initMargin.left - 10, initMargin.bottom, initMargin.right + 10));
border = new EmptyBorder(10, 10, 0, 0);
changePnlBorder(border);
Thread.sleep(100);
changeBtnMargin(new Insets(initMargin.top, initMargin.left, initMargin.bottom, initMargin.right));
border = new EmptyBorder(5, 5, 5, 5);
changePnlBorder(border);
Thread.sleep(100);
count++;
} catch (Exception e) {
System.out.println(e);
}
}
}).start();
}
}
}
private void changePnlBorder(final Border b) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
buttonPanel.setBorder(b);
buttonPanel.revalidate();
buttonPanel.repaint();
}
});
}
private void changeBtnForegroung(final Color c) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
button.setForeground(c);
}
});
}
private void changeBtnMargin(final Insets margin) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
button.setMargin(margin);
}
});
}
}
conclusion -> you can create new Thread as BackGroung Task(s) wrapped into Runnable, if you wnat to simulate LongRunning Task and with Thread.sleep(int), maybe answer to your question is here
sure correct way would be by using SwingWorker for that, with Thread.sleep(int) too

Remove Top-Level Container on Runtime

Unfortunately, it looks like this recently closed question was not well understood. Here is the typical output:
run:
Trying to Remove JDialog
Remove Cycle Done :-)
Checking if still exists any of TopLayoutContainers
JFrame
JDialog
Will Try Remove Dialog again, CycleNo. 1
-----------------------------------------------------------
Trying to Remove JDialog
Remove Cycle Done :-)
Checking if still exists any of TopLayoutContainers
JFrame
JDialog
Will Try Remove Dialog again, CycleNo. 2
-----------------------------------------------------------
Trying to Remove JDialog
Remove Cycle Done :-)
Checking if still exists any of TopLayoutContainers
JFrame
JDialog
Will Try Remove Dialog again, CycleNo. 3
-----------------------------------------------------------
Trying to Remove JDialog
Remove Cycle Done :-)
Checking if still exists any of TopLayoutContainers
JFrame
JDialog
*** End of Cycle Without Success, Exit App ***
BUILD SUCCESSFUL (total time: 13 seconds)
I'll try asking this question again: How can I kil*l on Runtime the first-opened top-Level Container, and help with closing for me one of Swing NightMares?
import java.awt.*;
import java.awt.event.WindowEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class RemoveDialogOnRuntime extends JFrame {
private static final long serialVersionUID = 1L;
private int contID = 1;
private boolean runProcess;
private int top = 20;
private int left = 20;
private int maxLoop = 0;
public RemoveDialogOnRuntime() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 300));
setTitle("Remove Dialog On Runtime");
setLocation(150, 150);
pack();
setVisible(true);
Point loc = this.getLocation();
top += loc.x;
left += loc.y;
AddNewDialog();
}
private void AddNewDialog() {
DialogRemove firstDialog = new DialogRemove();
remWins();
}
private void remWins() {
runProcess = true;
Thread th = new Thread(new RemTask());
th.setDaemon(false);
th.setPriority(Thread.MIN_PRIORITY);
th.start();
}
private class RemTask implements Runnable {
#Override
public void run() {
while (runProcess) {
Window[] wins = Window.getWindows();
for (int i = 0; i < wins.length; i++) {
if (wins[i] instanceof JDialog) {
System.out.println(" Trying to Remove JDialog");
wins[i].setVisible(false);
wins[i].dispose();
WindowEvent windowClosing = new WindowEvent(wins[i], WindowEvent.WINDOW_CLOSING);
wins[i].dispatchEvent(windowClosing);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowClosing);
Runtime runtime = Runtime.getRuntime();
runtime.gc();
runtime.runFinalization();
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(RemoveDialogOnRuntime.class.getName()).log(Level.SEVERE, null, ex);
}
}
wins = null;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println(" Remove Cycle Done :-)");
Runtime.getRuntime().runFinalization();
Runtime.getRuntime().gc();
runProcess = false;
}
});
}
pastRemWins();
}
}
private void pastRemWins() {
System.out.println(" Checking if still exists any of TopLayoutContainers");
Window[] wins = Window.getWindows();
for (int i = 0; i < wins.length; i++) {
if (wins[i] instanceof JFrame) {
System.out.println("JFrame");
wins[i].setVisible(true);
} else if (wins[i] instanceof JDialog) {
System.out.println("JDialog");
wins[i].setVisible(true);
}
}
if (wins.length > 1) {
wins = null;
maxLoop++;
if (maxLoop <= 3) {
System.out.println(" Will Try Remove Dialog again, CycleNo. " + maxLoop);
System.out.println(" -----------------------------------------------------------");
remWins();
} else {
System.out.println(" -----------------------------------------------------------");
System.out.println("*** End of Cycle Without Success, Exit App ***");
closeMe();
}
}
}
private void closeMe() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
System.exit(0);
}
});
}
private class DialogRemove extends JDialog {
private static final long serialVersionUID = 1L;
DialogRemove(final Frame parent) {
super(parent, "SecondDialog " + (contID++));
setLocation(top, left);
top += 20;
left += 20;
setPreferredSize(new Dimension(200, 200));
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.MODELESS);
pack();
setVisible(true);
}
private DialogRemove() {
setTitle("SecondDialog " + (contID++));
setLocation(top, left);
top += 20;
left += 20;
setPreferredSize(new Dimension(200, 200));
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.MODELESS);
pack();
setVisible(true);
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
RemoveDialogOnRuntime superConstructor = new RemoveDialogOnRuntime();
}
});
}
}
Invoking dispose() allows the host platform to reclaim memory consumed by the heavyweight peer, but it can't do so until after the WINDOW_CLOSING event is processed on the EventQueue. Even then, gc() is a suggestion.
Addendum: Another way to see the nightmare is via a profiler. Running the example below with jvisualvm, one can see that periodic collection never quite returns to baseline. I've exaggerated the vertical axis by starting with an artificially small heap. Additional examples are shown here. When memory is very limited, I've used two approaches:
Emergent: Loop from the command line, starting a new VM each time.
Urgent: Eliminate the heavyweight component entirely, running headless and composing in a BufferedImage using 2D graphics and lightweight components only.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.WindowEvent;
import javax.swing.JDialog;
/** #see https://stackoverflow.com/questions/6309407 */
public class DialogClose extends JDialog {
public DialogClose(int i) {
this.setTitle("Dialog " + String.valueOf(i));
this.setPreferredSize(new Dimension(320, 200));
}
private void display() {
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
passSomeTime();
this.setVisible(false);
this.dispatchEvent(new WindowEvent(
this, WindowEvent.WINDOW_CLOSING));
this.dispose();
passSomeTime();
}
private void passSomeTime() {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace(System.err);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
int count = 0;
while (true) {
new DialogClose(count++).display();
}
}
});
}
}
I have completely reworked your example:
I have simplified what was not needed (setLocation(), unused constructor...)
I have removed the code that triggers a WINDOW_CLOSING event (useless)
I have removed code that resets all windows to visible again (which would prevent GC on them)
I have used a javax.swing.Timer instead of a Thread for disposing of the dialog
I have used a Thread for forcing GC (not a good idea in the EDT)
I have modified the final success criterion to check that Window.getWindows() is 2 (not 1), because in Swing, if you open a dialog with no parent, then a special invisible frame will be created to use it as parent (for all ownerless dialogs actually), once created, that frame cannot be removed.
The resulting snippet follows:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class RemoveDialogOnRuntime extends JFrame {
private static final long serialVersionUID = 1L;
private boolean runProcess;
private int maxLoop = 0;
private Timer timer;
public RemoveDialogOnRuntime() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 300));
setTitle("Remove Dialog On Runtime");
setLocation(150, 150);
pack();
setVisible(true);
addNewDialog();
}
private void addNewDialog() {
DialogRemove firstDialog = new DialogRemove();
remWins();
}
private void remWins() {
runProcess = true;
timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (runProcess) {
for (Window win: Window.getWindows()) {
if (win instanceof JDialog) {
System.out.println(" Trying to Remove JDialog");
win.dispose();
}
}
System.out.println(" Remove Cycle Done :-)");
runProcess = false;
new Thread() {
#Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Runtime.getRuntime().gc();
}
}.start();
} else {
pastRemWins();
runProcess = true;
}
}
});
timer.setRepeats(true);
timer.start();
}
private void pastRemWins() {
System.out.println(" Checking if still exists any of TopLayoutContainers");
Window[] wins = Window.getWindows();
for (int i = 0; i < wins.length; i++) {
if (wins[i] instanceof JFrame) {
System.out.println("JFrame");
} else if (wins[i] instanceof JDialog) {
System.out.println("JDialog");
} else {
System.out.println(wins[i].getClass().getSimpleName());
}
}
// We must expect 2 windows here: this (RemoveDialogOnRuntime) and the parent of all parentless dialogs
if (wins.length > 2) {
wins = null;
maxLoop++;
if (maxLoop <= 3) {
System.out.println(" Will Try Remove Dialog again, CycleNo. " + maxLoop);
System.out.println(" -----------------------------------------------------------");
remWins();
} else {
System.out.println(" -----------------------------------------------------------");
System.out.println("*** End of Cycle Without Success, Exit App ***");
closeMe();
}
} else {
timer.stop();
}
}
private void closeMe() {
System.exit(0);
}
private class DialogRemove extends JDialog {
private static final long serialVersionUID = 1L;
private DialogRemove() {
setTitle("SecondDialog");
setPreferredSize(new Dimension(200, 200));
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.MODELESS);
pack();
setVisible(true);
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
RemoveDialogOnRuntime superConstructor = new RemoveDialogOnRuntime();
}
});
}
}
The important conclusions are:
You can't remove the invisible frame created by Swing as parent of all ownerless dialogs
You have to force a GC for the disposed dialog to be removed from Window.getWindows() (that one looks like a bug to me but I think the reason is that Swing keeps a WeakReference to all windows, and this WeakReference is not released until a GC has occurred.
Hope this gives a clear and complete answer to your problem.
with the intent to blow away all doubts about EDT and confirm trashgod Updated suggestion, then output to the console is
run:
7163 KB used before GC
Trying to Remove JDialog
Remove Cycle Done :-)
405 KB used after GC
Checking if still exists any of TopLayoutContainers
JFrame
JDialog
Will Try Remove Dialog again, CycleNo. 1
-----------------------------------------------------------
3274 KB used before GC
Trying to Remove JDialog
Remove Cycle Done :-)
403 KB used after GC
Checking if still exists any of TopLayoutContainers
JFrame
JDialog
Will Try Remove Dialog again, CycleNo. 2
-----------------------------------------------------------
3271 KB used before GC
Trying to Remove JDialog
Remove Cycle Done :-)
406 KB used after GC
Checking if still exists any of TopLayoutContainers
JFrame
JDialog
Will Try Remove Dialog again, CycleNo. 3
-----------------------------------------------------------
3275 KB used before GC
Trying to Remove JDialog
Remove Cycle Done :-)
403 KB used after GC
Checking if still exists any of TopLayoutContainers
JFrame
JDialog
-----------------------------------------------------------
*** End of Cycle Without Success, Exit App ***
BUILD SUCCESSFUL (total time: 26 seconds)
from code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class RemoveDialogOnRuntime extends JFrame {
private static final long serialVersionUID = 1L;
private int contID = 1;
private boolean runProcess;
private int top = 20;
private int left = 20;
private int maxLoop = 0;
private javax.swing.Timer timer = null;
public RemoveDialogOnRuntime() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 300));
setTitle("Remove Dialog On Runtime");
setLocation(150, 150);
pack();
setVisible(true);
Point loc = this.getLocation();
top += loc.x;
left += loc.y;
AddNewDialog();
}
private void AddNewDialog() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
DialogRemove firstDialog = new DialogRemove();
startAA();
}
});
}
private void startAA() {
timer = new javax.swing.Timer(5000, updateAA());
timer.setRepeats(false);
timer.start();
}
public Action updateAA() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
if (SwingUtilities.isEventDispatchThread()) {
Runnable doRun = new Runnable() {
#Override
public void run() {
remWins();
}
};
SwingUtilities.invokeLater(doRun);
} else {
Runnable doRun = new Runnable() {
#Override
public void run() {
remWins();
}
};
SwingUtilities.invokeLater(doRun);
}
}
};
}
private void remWins() {
Runtime runtime = Runtime.getRuntime();
long total = runtime.totalMemory();
long free = runtime.freeMemory();
long max = runtime.maxMemory();
long used = total - free;
System.out.println(Math.round(used / 1e3) + " KB used before GC");
Window[] wins = Window.getWindows();
for (int i = 0; i < wins.length; i++) {
if (wins[i] instanceof JDialog) {
System.out.println(" Trying to Remove JDialog");
wins[i].setVisible(false);
wins[i].dispose();
WindowEvent windowClosing = new WindowEvent(wins[i], WindowEvent.WINDOW_CLOSING);
wins[i].dispatchEvent(windowClosing);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowClosing);
runtime = Runtime.getRuntime();
runtime.gc();
runtime.runFinalization();
}
}
wins = null;
System.out.println(" Remove Cycle Done :-)");
runtime.runFinalization();
runtime.gc();
runtime = Runtime.getRuntime();
total = runtime.totalMemory();
free = runtime.freeMemory();
max = runtime.maxMemory();
used = total - free;
System.out.println(Math.round(used / 1e3) + " KB used after GC");
startOO();
}
private void startOO() {
timer = new javax.swing.Timer(5000, updateOO());
timer.setRepeats(false);
timer.start();
}
public Action updateOO() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
timer.stop();
if (SwingUtilities.isEventDispatchThread()) {
Runnable doRun = new Runnable() {//really contraproductive just dealayed
#Override
public void run() {
pastRemWins();
}
};
SwingUtilities.invokeLater(doRun);
} else {
Runnable doRun = new Runnable() {
#Override
public void run() {
pastRemWins();
}
};
SwingUtilities.invokeLater(doRun);
}
}
};
}
private void pastRemWins() {
System.out.println(" Checking if still exists any of TopLayoutContainers");
Window[] wins = Window.getWindows();
for (int i = 0; i < wins.length; i++) {
if (wins[i] instanceof JFrame) {
System.out.println("JFrame");
wins[i].setVisible(true);
} else if (wins[i] instanceof JDialog) {
System.out.println("JDialog");
wins[i].setVisible(true);
}
}
if (wins.length > 1) {
wins = null;
maxLoop++;
if (maxLoop <= 3) {
System.out.println(" Will Try Remove Dialog again, CycleNo. " + maxLoop);
System.out.println(" -----------------------------------------------------------");
remWins();
} else {
System.out.println(" -----------------------------------------------------------");
System.out.println("*** End of Cycle Without Success, Exit App ***");
closeMe();
}
}
startAA();
}
private void closeMe() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
System.exit(0);
}
});
}
private class DialogRemove extends JDialog {
private static final long serialVersionUID = 1L;
DialogRemove(final Frame parent) {
super(parent, "SecondDialog " + (contID++));
setLocation(top, left);
top += 20;
left += 20;
setPreferredSize(new Dimension(200, 200));
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.MODELESS);
pack();
setVisible(true);
}
private DialogRemove() {
setTitle("SecondDialog " + (contID++));
setLocation(top, left);
top += 20;
left += 20;
setPreferredSize(new Dimension(200, 200));
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.MODELESS);
pack();
setVisible(true);
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
RemoveDialogOnRuntime superConstructor = new RemoveDialogOnRuntime();
}
});
}
}
I'm not sure if you question is about "garbage collection" or about how to identify dialogs that are visible.
You can't control when garbage collection is done. Invoking the gc() method is only a suggestion.
If you want to ignore "disposed" dialogs then you can use the isDisplayable() method to check its status.
With the following program I got some interesting results. First change I made was to add some components to the dialog so that more resources would be used for each dialog which would increase the chance that the resources would be garbage collected.
On my machine I found that if I
a) create 5 dialogs
b) close the dialogs
c) create 5 dialogs
Then the first 5 appear to be garbage collected.
However if I create 5, then close then create 1, then close, it doesn't seem to work.
Bottom line is you can't depend on when garbage collection will be done, so I suggest you use the isDisplayable() method to determine how to do your processing. The "Display Dialogs" button uses this method as part of the displayed output.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogSSCCE extends JPanel
{
public static int count;
public DialogSSCCE()
{
JButton display = new JButton("Display Dialogs");
display.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println();
System.out.println("Display Dialogs");
for (Window window: Window.getWindows())
{
if (window instanceof JDialog)
{
JDialog dialog = (JDialog)window;
System.out.println("\t" + dialog.getTitle() + " " + dialog.isDisplayable());
}
}
}
});
add( display );
JButton open = new JButton("Create Dialog");
open.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println();
System.out.println("Create Dialog");
JDialog dialog = new JDialog();
dialog.getContentPane().setLayout(null);
for (int i = 0; i < 200; i++)
{
dialog.add( new JTextField("some text") );
}
dialog.setTitle("Dialog " + count++);
dialog.setLocation(count * 25, count * 25);
dialog.setVisible(true);
System.out.println("\tCreated " + dialog.getTitle());
}
});
add( open );
JButton close = new JButton("Close Dialogs");
close.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println();
System.out.println("Close Dialogs");
for (Window window: Window.getWindows())
{
if (window instanceof JDialog)
{
JDialog dialog = (JDialog)window;
System.out.println("\tClosing " + dialog.getTitle());
dialog.dispose();
}
}
Runtime.getRuntime().gc();
}
});
add( close );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("DialogSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new DialogSSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
There is a timeout defined in the AppContext before some resources will be released finally. This is set to something like 5 seconds. Thus if you wait for another five seconds also the context will dispose the (last) reference to your dialog.
wins = null;
Thread.sleep(5000);

Categories