Why JOptionPane prevents ActionListener on JButton? - java

PreventingButtonListener.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PreventingButtonListener extends JFrame implements ActionListener{
JTextField fld = new JTextField(5) ;
PreventingButtonListener(){
super("PreventingButtonListener") ;
setSize(300, 250) ;
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) ;
setResizable(false) ;
fld.addFocusListener(
new FocusListener(){
public void focusGained(FocusEvent event) {}
public void focusLost(FocusEvent event) {
int i = (int) (Math.random() * 3) ;
switch(i){
case 0 :
System.out.println("random value : " + i);
fld.requestFocus() ;
break ;
case 1 :
System.out.println("random value : " + i);
i = (int) (Math.random() * 2) ;
if(i == 0){
System.out.println("JOptionPane not displayed, followed with button action.");
}else{
System.out.println("JOptionPane displayed, but button action not performed.");
JOptionPane.showMessageDialog(null, "Hello") ;
}
break ;
default :
System.out.println("random value : " + i);
System.out.println("Nothing to be done...");
break ;
}
}
}) ;
add(fld, "North") ;
JButton btn = new JButton("Hit me Repeatedly considering Note 1") ;
btn.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent arg0) {
System.out.println("focus gained on button.");
}
public void focusLost(FocusEvent arg0) {
System.out.println("focus removed on button.");
}
}) ;
btn.addActionListener(this) ;
add(btn, "South") ;
String str = "Note 1 : Whenever, u click on button, and if the focus" + "\n" +
"after clicking is not in the textfield, then, plz" + "\n" +
"explicitly click in the JTextField." + "\n\n" +
"Note 2 : Kindly notice the output on cmd " + "\n" +
"and related focuses of GUI." + "\n\n" ;
JTextArea area = new JTextArea(str) ;
area.setEditable(false) ;
area.setWrapStyleWord(true) ;
area.setBackground(Color.LIGHT_GRAY) ;
add(new JScrollPane(area)) ;
setVisible(true) ;
}
public void actionPerformed(ActionEvent arg0) {
System.out.println("data of txtfld : >" + fld.getText() + "<");
}
public static void main(String[] args) {
new PreventingButtonListener() ;
}
}
the problem lies in the execution of the attached program???

The JOptionPane that you bring up will be modal, and therefore action will not be processed for any component in your app outside of that JOptionPane.
from the New Modality API article from Sun:
A dialog box can be either modeless or modal. A modal dialog box is one that blocks input to some other top-level windows in the application, except for any windows created with the dialog box as their owner. The modal dialog box captures the window focus until it is closed, usually in response to a button press. A modeless dialog box, on the other hand, sits off on the side and allows you to change its state while other windows have focus. The latter is often used for a toolbar window, such as what you might find in an image-editing program.

JOptionPane methods won't return until the dialog is closed so the action code can be written after the call.

Related

How do I fix my code to count the number of clicks on each button?

I have written a program with two buttons for a Java class that I am taking. I now need to count and display the number of clicks each button gets. I have some code for counting clicks but am fairly certain that it is wrong.
The error I have is "identifier expected", how can I fix this?
Here is my updated code:
import java.awt.*;
import java.awt.event.*;
public class FinalProj1 extends Frame implements ActionListener,WindowListener {
FinalProj1() {
setTitle("Click Counter");
setSize(400,400);
show();
}
public static void main(String args[]) {
Frame objFrame;
Button objButton1;
Button objButton2;
TextField count = new TextField(20);
TextField count2 = new TextField(20);
Label objLabel;
Label objLabel2;
objFrame= new FinalProj1();
objButton1= new Button("Agree");
objButton2= new Button("Dissagree");
objLabel= new Label();
objLabel2= new Label();
objLabel2.setText("Mexican Food Is Better Than Chineese Food");
objButton1.setBounds(110,175,75,75);
objButton2.setBounds(190,175,75,75);
objLabel2.setBounds(80,95, 250,25);
objFrame.add(objButton2);
objFrame.add(objButton1);
objFrame.add(objLabel2);
objFrame.add(objLabel);
}
private int numClicks = 0;
private int numClicks2 = 0;
objButton1.addActionListener(this)
objButton2.addActionListener(this)
public void actionPerformed(ActionEvent e) {
numClicks++;
numClicks2++;
count.setText("There are " + numClicks + " who agree");
count2.setText("There are " + numClicks2 + " who dissagree");
}
}
The error he's having ("identifier expected") is specified in the previous question.
You're getting this error because these two lines of code are outside any method or initializer block:
objButton1.addActionListener(this)
objButton2.addActionListener(this)
Put them in your constructor after creating the two controls and you should be fine.
One approach is to have one actionListener for every button. Try this:
objButton1.addActionListener(myFirstActionListener)
objButton2.addActionListener(mySecondActionListener)
ActionListener myFirstActionListener = new ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
numClicks++;
}
}
ActionListener mySecondActionListener = new ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
numClicks2++;
}
}
First you should add the action listeners to each button,(explained above).
However,you are incrementing both counts whenever you press one of the two buttons,which is wrong.
So you should modify your action performed method to smthg like this
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals("Agree"))//if you push the button agree,increment only numClicks
numClicks++;
if(e.getSource().equal("Disagree"))//if you click on disagree,increment numClicks2
numClicks2++;
count.setText("There are " + numClicks + " who agree");
count2.setText("There are " + numClicks2 + " who dissagree");
}
EDIT-Btw,are you implementing the windows listener methods?You have to.
Jeroen's answer is correct for solving your compilation error, so definitely do that first before you proceed.
In regards to your actual counters, the problem you're having is that both your numClicks and numClicks2 variables are being incremented simultaneously whenever either objButton1 or objButton2 is clicked. This is because they are being handled by the same event handler method. You have two choices:
Option 1: let the single event handler method handle both clicks, but distinguish between the two, and only increment the relevant counter, like so:
public void actionPerformed(ActionEvent e){
if(e.getSource() == objButton1){
numClicks++;
} else {
numClicks++;
}
// the rest if your method
}
Option 2: specify separate event handlers for each button, something like this:
objButton1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
numClicks++;
// display your message to user
}
});
objButton2.addActionListener(new ActionListrner(){
public void actionPerformed(ActionEvent e){
numClicks2++;
// display your message to user;
}
});

JavaFX System out Println

I'm doing an interface to show the progress of my simulation (elevators simulating job on a building).
The thing is, I already did this on the console with System.out.println()s and I wanted to show the exact same thing on a javaFX window. Is there any way where I can set the text of a TextArea or a Label or something to match the output of the console? Just printing the same thing but instead of printing on the console I wanted to print on a window.
I was dumb enough to try and set the Text of a TextAreato the toString() of my simulator but ofc if it is System.out.println(), it shows on the console and not in the ThextArea.
EDIT: This is what I want to print:
#Override
public String toString() {
for (int y = 0; y < 50; y++) {
System.out.println("");
}
for (int i = pisos.size() - 1; i >= 0; i--) {
System.out.print(pisos.get(i).getPiso());
System.out.print(pisos.get(i).pQueue().toString());
System.out.print(" " + percorrerElevadores2(i));
System.out.print(" " + pisos.get(i).pessoasServidas() + "\n");
}
System.out.println("Numero total de passageiros à espera:" + " " + Predio.getPredio().getNPessoasEmEspera());
System.out.println("Numero total de pessageiros servidos:" + " " + Predio.getPredio().getNPessoasServidas());
for (int z = 0; z < getElevadores().size(); z++) {
System.out.println("Distancia percorrida pelo elevador" + " " + z + ":" + " " + Predio.getPredio().getElevadores().get(z).getDistanciaPercorrida() + " " + "Pisos");
System.out.println("Piso destino do elevador" + " " + z + ":" + " " + Predio.getPredio().getElevadores().get(z).getPisoDestino());
}
return "";
}
It is better to use the MessageDialogBox to print the message on window with reference of the panel on which you are working.
I don't really understand your question but it would be easier to rename the println calls than to redirect them. Use some code like this in your main class (the one that extends Application) or really in any class, but you need to add the textArea to the scene graph somewhere.
private static final TextArea textArea = new TextArea();
//add textArea to your scene somewhere in the start method
public static void println(String s){
Platform.runLater(new Runnable() {//in case you call from other thread
#Override
public void run() {
textArea.setText(textArea.getText()+s+"\n");
System.out.println(s);//for echo if you want
}
});
}
Then just use the IDE's search and replace to rename System.out.println to MainClassName.println.
From what I understand, you just want to print text in a location to investigate things, ie the results. Everything you want is just like you print a text on the console, you also want to print this text somewhere in a JavaFX application. Despite its formatting done in their toString method, you can catch the return of the method and print to a JavaFX application (within a control node, for example), right?
If this is the case ...
I created a simple application that works with two text areas. In the middle of application, you will find buttons that manipulate both areas. Basically, the buttons sends the contents of a text area to another. Note:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class AreaTextual extends Application
{
// #########################################################################################################
// MAIN
// #########################################################################################################
public static void main(String[] args)
{
Application.launch(args);
}
// #########################################################################################################
// INSTÂNCIAS
// #########################################################################################################
// Controles.
private Label lab_receptor;
private Label lab_emissor;
private TextArea tArea_receptor;
private TextArea tArea_emissor;
private Button bot_enviar;
private Button bot_enviarLinha;
private Button bot_substituir;
private Button bot_apagar;
// Layout.
private HBox hbox_raiz;
private VBox vbox_oeste;
private VBox vbox_centro;
private VBox vbox_leste;
// #########################################################################################################
// INÍCIO FX
// #########################################################################################################
#Override public void start(Stage estagio) throws Exception
{
this.iniFX();
this.confFX();
this.adFX();
this.evFX();
Scene cenario = new Scene(this.hbox_raiz , 640 , 480);
estagio.setScene(cenario);
estagio.setTitle("Programa JavaFX");
estagio.show();
}
/** Inicia nós FX.*/
protected void iniFX()
{
// Controles.
this.lab_receptor = new Label();
this.lab_emissor = new Label();
this.tArea_receptor = new TextArea();
this.tArea_emissor = new TextArea();
this.bot_enviar = new Button();
this.bot_enviarLinha = new Button();
this.bot_substituir = new Button();
this.bot_apagar = new Button();
// Layout.
this.hbox_raiz = new HBox();
this.vbox_oeste = new VBox();
this.vbox_centro = new VBox();
this.vbox_leste = new VBox();
}
/** Configura nós FX.*/
protected void confFX()
{
// Controles.
this.lab_receptor.setText("RECEPTOR");
this.lab_receptor.setFont(new Font(32));
this.lab_emissor.setText("EMISSOR");
this.lab_emissor.setFont(new Font(32));
this.bot_enviar.setText("<- ENVIAR");
this.bot_enviar.setPrefSize(150 , 60);
this.bot_enviarLinha.setText("<- ENVIAR+");
this.bot_enviarLinha.setPrefSize(150 , 60);
this.bot_substituir.setText("<- SUBSTITUIR");
this.bot_substituir.setPrefSize(150 , 60);
this.bot_apagar.setText("<- APAGAR TUDO ->");
this.bot_apagar.setPrefSize(150 , 60);
// Layout.
this.hbox_raiz.setSpacing(20);
this.hbox_raiz.setPadding(new Insets(30 , 30 , 30 , 30));
this.hbox_raiz.setAlignment(Pos.CENTER);
this.vbox_oeste.setSpacing(10);
this.vbox_oeste.setAlignment(Pos.CENTER);
this.vbox_centro.setSpacing(10);
this.vbox_centro.setAlignment(Pos.CENTER);
this.vbox_centro.setPrefSize(400 , 200);
this.vbox_leste.setSpacing(10);
this.vbox_leste.setAlignment(Pos.CENTER);
}
/** Adiciona e organiza em layout os nós FX.*/
protected void adFX()
{
this.vbox_leste.getChildren().addAll(this.lab_emissor , this.tArea_emissor);
this.vbox_centro.getChildren().addAll(this.bot_enviar , this.bot_enviarLinha , this.bot_substituir , this.bot_apagar);
this.vbox_oeste.getChildren().addAll(this.lab_receptor , this.tArea_receptor);
this.hbox_raiz.getChildren().addAll(this.vbox_oeste , this.vbox_centro , this.vbox_leste);
}
/** Configura eventos de nós FX.*/
protected void evFX()
{
this.bot_enviar.setOnAction(new EventHandler<ActionEvent>()
{
#Override public void handle(ActionEvent e)
{
tArea_receptor.appendText(tArea_emissor.getText());
}
});
this.bot_enviarLinha.setOnAction(new EventHandler<ActionEvent>()
{
#Override public void handle(ActionEvent e)
{
tArea_receptor.appendText(String.format("%n%s" , tArea_emissor.getText()));
}
});
this.bot_substituir.setOnAction(new EventHandler<ActionEvent>()
{
#Override public void handle(ActionEvent e)
{
tArea_receptor.replaceText(0 , tArea_receptor.getLength() , tArea_emissor.getText());
}
});
this.bot_apagar.setOnAction(new EventHandler<ActionEvent>()
{
#Override public void handle(ActionEvent e)
{
tArea_receptor.setText("");
tArea_emissor.setText("");
}
});
}
}
OBS (PT-BR): Eu notei que você fala português, portanto deixei o código na linguagem para que você entenda-o melhor.
This class has nothing exceptional. It just shows you how you can manipulate the text of a TextArea. You can find other types of handlers of a TextArea right here, and also here.
Regarding your problem seen where you call the JavaFX methods from another thread, this can be happening just because you're not using the JavaFX Application Thread. Like the Swing library has the Event Dispatch Thread (EDT), JavaFX also has its own thread responsible for handling the JavaFX elements. Whenever you need to manipulate any JavaFX element, be to setup something or to obtain some data, you need to do this using the JavaFX Application Thread, and not another.
For you to call methods of the JavaFX Application Thread, use the Platform runLater method. For more information about the JavaFX threads system, visit the following links:
http://docs.oracle.com/javafx/2/architecture/jfxpub-architecture.htm
http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
In the first link, read the part that talks about threads. If you have any more questions, come back here and ask.
Good luck.

Input Dialog [Information Needed]

So I have a program that launches an input dialog when I click a button. What I need help on is that once I gather the information from the input dialog and they are gone, I press the Enter key and the input dialogs re-appear. Why?
Also, How can I have it so that if the input dialog is left empty, it comes out as an error and then repeats until it is not empty?
public static String fn;
public static String sn;
public void actionPerformed (ActionEvent e){
fn = JOptionPane.showInputDialog("What is your first name?");
sn = JOptionPane.showInputDialog("What is your second name");
//JOptionPane.showMessageDialog(null, "Welcome " + fn + " " + sn + ".", "", JOptionPane.INFORMATION_MESSAGE);
text.setText("Welcome " + fn + " " + sn + ".");
b.setVisible(false);
text.setVisible(true);
text.setBounds(140,0,220,20);
text.setHorizontalAlignment(JLabel.CENTER);
text.setEditable(false);
text.setBackground(Color.YELLOW);
writeToFile();
}
public BingoHelper(){
super("BINGO");
add(text);
text.setVisible(false);
add(b);
this.add(pnlButton);
pnlButton.setBackground(Color.BLUE);
//pnlButton.add(b);+
b.setVisible(true);
b.setBounds(145,145,145,20);
//b.setPreferredSize(new Dimension(150,40));
b.addActionListener(this);
b.setBackground(Color.GREEN);
rootPane.setDefaultButton(b);
}
When you call rootPane.setDefaultButton you are specifying the button which is activated by the Enter key.
To prevent a JOptionPane from closing when the input is not acceptable, create an actual JOptionPane instance, then create your own button and specify it as an option. The button's Action or ActionListener must call the JOptionPane's setValue method:
final JOptionPane optionPane = new JOptionPane("What is your first name?",
JOptionPane.QUESTION_MESSAGE);
optionPane.setWantsInput(true);
Action accept = new AbstractAction("OK") {
private static final long serialVersionUID = 1;
public void actionPerformed(ActionEvent event) {
Object value = optionPane.getInputValue();
if (value != null && !value.toString().isEmpty()) {
// This dismisses the JOptionPane dialog.
optionPane.setValue(JOptionPane.OK_OPTION);
}
}
};
Object acceptButton = new JButton(accept);
optionPane.setOptions(new Object[] { acceptButton, "Cancel" });
optionPane.setInitialValue(acceptButton);
// Waits until dialog is dismissed.
optionPane.createDialog(null, "First Name").setVisible(true);
if (!Integer.valueOf(JOptionPane.OK_OPTION).equals(optionPane.getValue())) {
// User canceled dialog.
return;
}
String fn = optionPane.getInputValue().toString();

How to call different actionListeners?

My program has one button, and the other one is a JTextField. The action listener for the button and the textfield are different. I'm using:
textfield.addActionListener(this);
button.addActionListener(this);
... inside my constructor.
They both do the same actionListener. How can I call their respective methods?
You are implementing ActionListener in the class of both components. So, when an action happens, actionPerformed method of the class is called for both of them. You can do following to separate them:
1-Create a separate class and implement ActionListener interface in it and add it as a actionListener for one of the components.
2-In actionPerformed method, there is a parameter with ActionEvent type. Call getSource method of it and check if it returns the object of JTextField or JButton by putting an if statement and do separate things accordingly.
Obviously both components share an ActionListener. If you want to determine which component generated the ActionEvent, invoke getSource(). And from there, you can typecast (if needed), and then invoke that particular component's methods.
For me the easiest way to do what is asked is the following:
textfield.addActionListener(this);
button.addActionListener(this);
...
public void actionPerformed(ActionEvent e){
if( e.getSource().getClass().equals(JTextField.class) ){
System.out.println("textfield");
//Código para el textfield
}
if( e.getSource().getClass().equals(JButton.class) ){
System.out.println("JButton");
//Código para el JButton
}
}
When an action listener is activated, because someone click your button, the method actionPerformed is called. As you havae set this as an action listener, you should have a method actionPerformed in your class. This is the method called in both cases.
Something like:
class MyClass implements ActionListener {
public MyClass() {
...
textfield.addActionListener(this) ;
button.addActionListener(this) ;
...
}
public void actionPerformed(ActionEvent e) {
// This is the method being called when:
// - the button is clicked and
// - the textfield activated
}
}
Though if you have not given your sample code, but I can understand what is there.
Here is an example of how to add listener to any JComponent. (Dont try to run this code!!!)
import java.awt.Button;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class EventListeners extends JFrame implements ActionListener {
TextArea txtArea;
String Add, Subtract, Multiply, Divide;
int i = 10, j = 20, sum = 0, Sub = 0, Mul = 0, Div = 0;
public void init() {
txtArea = new TextArea(10, 20);
txtArea.setEditable(false);
add(txtArea, "center");
Button b = new Button("Add");
Button c = new Button("Subtract");
Button d = new Button("Multiply");
Button e = new Button("Divide");
// YOU ARE DOING SOMETHING LIKE THIS
// THIS WILL WORK, BUT CAN BE A BAD EXMPLE
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
add(b);
add(c);
add(d);
add(e);
}
public void actionPerformed(ActionEvent e) {
sum = i + j;
txtArea.setText("");
txtArea.append("i = " + i + "\t" + "j = " + j + "\n");
Button source = (Button) e.getSource();
// you can work with them like shown below
Button source = (Button) e.getSource();
if (source.getLabel() == "Add") {
txtArea.append("Sum : " + sum + "\n");
}
if (source.getLabel() == "Subtract") {
txtArea.append("Sub : " + Sub + "\n");
}
if (source.getLabel() == "Multiply") {
txtArea.append("Mul = " + Mul + "\n");
}
if (source.getLabel() == "Divide") {
txtArea.append("Divide = " + Div);
}
}
}
UPDATE
You should do something like below
Button b = new Button("Add");
Button c = new Button("Subtract");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// implement what is expected for b button
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// implement what is expected for c button
}
});
// and so on...
// but yes we can improve it
Just set different ActionCommands on each component.
In the actionPerformed method you can check the ActionCommand of the event:
private static final String TEXT_CMD = "text"; // or something more meaningful
private static final String BUTTON_CMD = "button";
...
textfield.setActionCommand(TEXT_CMD);
textfield.addActionListener(this);
button.setActionCommand(BUTTON_CMD);
button.addActionListener(this);
...
public void actionPerformed(ActionEvent ev) {
switch (ev.getActionCommand()) {
case TEXT_CMD:
// do textfield stuff here
break;
case BUTTON_CMD:
// do button stuff here
break;
default:
// error message?
break;
}
}

Java this.dispose not closing window when called

I am writing a program from class, and I am attempting to have it set up so a window is created which shows search results in the form of buttons. I would like it if there are no search results, that the window would call a pop-up warning stating such and then just close the window.
I have it setup that whenever I want to make the window close, I call a CloseWindow() method that just contains a this.dispose(); command. If I call it from the actionEvent method once a button is pushed, the window closes fine, but if I try to call it almost anywhere else in the method, it will not close the window. Is there some basic Java concept I am missing? I know the JFrame has the dispose method from the Window class, but "this" seems to only work under certain conditions.
The relevant code is below:
public class MovieSearch extends JFrame implements ActionListener, Serializable{
private static final long serialVersionUID = 7526471155622776147L;
private Container con = getContentPane();
int llSize, searchResults = 0;
MovieNode currentNode;
String searchText;
JPanel listPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JScrollPane scrollPane = new JScrollPane(listPanel);
public MovieSearch(String searchText){
super("Search Results");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.searchText = searchText;
con.add(scrollPane);
currentNode = MovieView.firstNode;
for(int i = 0; i < llSize; i++){
if (currentNode.getTitle().indexOf(searchText) != -1) {
BufferedImage Thumbnail = new BufferedImage(200, 300, BufferedImage.TYPE_INT_ARGB);
Thumbnail.getGraphics().drawImage(currentNode.getImage().getImage(), 0, 0, 200, 300, null);
ImageIcon icon = new ImageIcon(Thumbnail);
JButton button = new JButton("Go to " + currentNode.getTitle());
button.addActionListener(this);
button.setVerticalTextPosition(AbstractButton.BOTTOM);
button.setHorizontalTextPosition(AbstractButton.CENTER);
button.setIcon(icon);
listPanel.add(button);
searchResults++;
currentNode = currentNode.getLink();
} else {
System.out.println("String " + currentNode.getTitle() + " does not contain String " + searchText);
currentNode = currentNode.getLink();
}
}
if(searchResults == 0){
int messageType = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(null, "No results match that query.", "NO RESULTS!", messageType);
CloseWindow();
}else{
currentNode = MovieView.firstNode;
repaint();
}
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
for(int i = 0; i < llSize; i++){
JButton button;
button = (JButton) source;
if(button.getText().equals(("Go to " + currentNode.getTitle()))){
MovieView.currentNode = currentNode;
MovieView.searchTextField.setText("");
CloseWindow();
}
System.out.println("button is " + button.getText());
System.out.println("text is: " + "Go to " + currentNode.getTitle());
currentNode = currentNode.getLink();
}
}
private void CloseWindow(){
System.out.println("Closing Window");
this.dispose();
}
}
Again, the CloseWindow() method [and hence the this.dispose() method] works when called form the ActionEvent method but not from anywhere else. [I have inserted it into other places just to test and it is reached but it still does not close the window.]
As you can see, I put a println in the CloseWindow() method to make sure that it was being reached and it is reached every time, it just isn't working.
Any insight into this would be very appreciated. Thank you for your time.
A JOptionPane creates a "modal dialog" which means that the statements after the "showMessageDialog" to not execute until after the dialog is closed.
You have two options:
a) create you own custom "non modal dialog" that displays your message and then closes.
b) Read the JOptionPane API. It shows you how to manually access the dialog that is create by the JOptionPane class so you have a reference to the dialog.
In both cases you would need to start a Swing Timer before you display the dialog. Then when the Timer fires you can dispose the dialog.

Categories

Resources