Create independent objects of a class - java

I want to create more than one object of a class that are independent one from the other.
I call class constructor multiple time in a for loop, but how can I identify this objects?
I tried using a static variable that takes the value of the for loop index, but this variable assume the value of last index of the for loop.
Here is the code:
Maingui.java
public class Maingui extends JFrame {
public static JFrame frame;
public static JButton runButton;
public Maingui() throws IOException {
frame = new JFrame("maingui");
setSize(1024,700);
setTitle("maingui");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
runButton = new JButton("Run");
runButton.addActionListener(new RunBtnListener());
add(runButton);
}
}
RunBtnListener.java
public class RunBtnListener implements ActionListener {
ArrayList<SecondGui> menus = new ArrayList<SecondGui>();
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 2; i++) {
menus.add(new SecondGui(i));
}
}
}
SecondGui.java
public class SecondGui extends JFrame {
public static int c;
JFrame frame;
JButton button;
public SecondGui(int i) {
this.c = i;
frame = new JFrame("Test");
setSize(1024,700);
setTitle("Menu");
setLocationRelativeTo(null);
setVisible(true);
this.setLocation(50*i, 50*i);
// Set layout manager
setLayout(new BorderLayout());
button = new JButton("B");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("C: " + c);
}
});
add(button);
}
}
When I click on the button button in SecondGui GUI, the output is always 1.
But I want that the output will be 0 or 1 based on in which GUI I select the button.

I want to create more than one object of a class that are independent
one from the other.
Your current code creates 2 independent objects inside this loop
for(int i = 0; i < 2; i++) {
menus.add(new SecondGui(i));
}
But as you made it static, it is not bounded to any instance you creates.
What you need is an instance variable to keep the ID for the SecondGui instance. You can create a new constructor and pass the index of the loop.
public class SecondGui extends JFrame {
private int c = 0;
private JFrame frame;
private JButton button;
public SecondGui(int i) {
this.c = i;
initialize();
}
void initialize() {
frame = new JFrame("Test");
setSize(1024,700);
setTitle("Menu");
setLocationRelativeTo(null);
setVisible(true);
this.setLocation(50*i, 50*i);
// Set layout manager
setLayout(new BorderLayout());
button = new JButton("B");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("C: " + c);
}
});
add(button);
}
}

Related

How to refer to the object on which an action was performed

I created an ArrayList of JButtons using a for loop, so I don't have a specific name for each object. In the actionPerformed() method, I want to get the index of the button that was just pressed. Using the this keyword, it refers to the overall class this is defined in, not the object that was pressed.
public class Game implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int temp = this.buttons.indexOf(this);
}
}
Here is first solution. In this case you can use the internal ActionEvent getSource() methods
private static List<JButton> buttons = new ArrayList<>();
static class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int buttonIndex = buttons.indexOf(e.getSource());
JButton pressedButton = buttons.get(buttonIndex);
// buttonIndex and pressedButton. You can do whatever you want
System.out.println(buttonIndex); // Just for testing
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Test Buttons");
// set frame site
frame.setMinimumSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for(int i = 0; i< 10; i++)
{
JButton btn = new JButton();
btn.setText(Integer.valueOf(i).toString());// Just to display for testing
MyButtonListener myListener = new MyButtonListener();
btn.addActionListener(myListener);
buttons.add(btn);
frame.setLayout(new FlowLayout());
frame.add(btn);
}
frame.pack();
frame.setVisible(true);
}
==================================================
This is second solution. This time you set the index on the creation of the Button Listener (inside the constructor). Here you use class parameter which will memorize which was the button index. Then when you are using it and it will know already which is the button.
private static List<JButton> buttons = new ArrayList<>();
static class MyButtonListener implements ActionListener {
int buttonIndex;
public MyButtonListener(int i) {
buttonIndex = i;
}
#Override
public void actionPerformed(ActionEvent e) {
JButton pressedButton = buttons.get(buttonIndex);
//... Work here with pressedButton or buttonIndex
}
}
public static void main(String[] args) {
for(int i = 0; i< 10; i++)
{
JButton btn = new JButton();
MyButtonListener myListener = new MyButtonListener(i); //Here set the index in the constructor
btn.addActionListener(myListener);
buttons.add(btn);
}
}
Best of luck to all!
The actionPerformed() method has the ActionEvent as parameter.
Use the getSource() method to find out which object fired the event.
With that, your ActionListener can look like this (I assume you attach this ActionListener only to JButtons):
public void actionPerformed(ActionEvent e) {
JButton pressedButton = (JButton)e.getSource();
// do whatever you need to do with that button
}

How to return an int to another class

I'm trying to learn how to use variables from 1 class in another one. What the first class does is that it sets the int testInt to 0 and once a value is inserted in the textField and then pressed the button it is changing the value to that number. But here is the problem, when I try to use the variable in the other class I print out a 0 instead of the number i typed.
First class that creates the variable and should change it too.
public class RouletteGui extends JPanel {
private JTextField tfInput = new JTextField();
private JPanel center = new JPanel(new BorderLayout());
private JPanel South = new JPanel(new BorderLayout());
private JButton btnSearch = new JButton("Change int value");
private int testInt = 0;
public RouletteGui() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(400, 400));
center.add(tfInput, BorderLayout.CENTER);
add(South, BorderLayout.SOUTH);
add(center, BorderLayout.CENTER);
South.add(btnSearch, BorderLayout.SOUTH);
center.add(tfInput, BorderLayout.CENTER);
createListeners();
}
public void createListeners() {
button b = new button();
btnSearch.addActionListener(b);
}
private class button implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSearch) {
testInt = Integer.parseInt(tfInput.getText());
System.out.println(testInt);
}else{}
}
}
public int getTestInt(){
return testInt;
}
public static void main(String[] a) {
JFrame frame = new JFrame("Kalkylator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new RouletteGui());
frame.pack();
frame.setVisible(true);
}
}
Second class that will write out the int.
public class WritingInt {
private RouletteGui rg = new RouletteGui();
public WritingInt(){
System.out.println(rg.getTestInt());
}
public static void main (String args[]){
WritingInt wi = new WritingInt();
}
}

Cannot find a way to create a loading screen

I was just messing around with GUI in Java and created a little game. In it, 105 randomly placed buttons are created and then an instruction screen pops up, telling the user which button to find. I've tried to figure out how to program a "Loading..." JDialog, which will pop up while the buttons are being created in the background. The trouble is, when I run the program the JDialog doesn't load until AFTER all the buttons have been created, which kind of defeats the purpose of the box in the first place. How can I force the "Loading..." box to load BEFORE the buttons begin to be created??? Thanks in advance.
Because I've just been tinkering, my code is not perfect but here it is:
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.ProgressMonitor;
public class ButtonGame {
private static int butNum = 1;
private static JFrame frame;
private static ActionListener notIt;
private static ActionListener it;
private static Random rand = new Random();
private static int butToFind = rand.nextInt(105);
private static JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
//actionlistener for all incorrect buttons (buttons that are "not it")
notIt = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame5 = (JFrame) SwingUtilities.getRoot(component);
frame5.dispose();
}
};
//actionlistener for the correct button (the button that's "it")
it = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame youWin = new JFrame("YOU WON!");
//removes all panels to begin game again
JButton again = new JButton("Play again");
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
java.awt.Window windows[] = java.awt.Window.getWindows();
for(int i=0;i<windows.length;i++){
if (windows[i] != frame) { windows[i].dispose(); }
butToFind = rand.nextInt(105);
butNum = 1;
youWin.dispose();
}
frame.setVisible(true);
}
});
//quits game
JButton win = new JButton("Quit");
win.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//layout
youWin.setSize(775, 300);
youWin.setLayout(new FlowLayout());
JLabel label1 = new JLabel("Fantastic!");
Font font1 = new Font("Courier", Font.BOLD,120);
label1.setFont(font1);
label1.setHorizontalAlignment(JLabel.CENTER);
JLabel label2 = new JLabel("You beat the game!");
Font font2 = new Font("Courier", Font.BOLD,60);
label2.setFont(font2);
label2.setHorizontalAlignment(JLabel.CENTER);
youWin.add(label1);
youWin.add(label2);
JPanel panel = new JPanel();
youWin.add(panel);
panel.add(again);
panel.add(win);
youWin.setLocation(260, 100);
youWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
youWin.setVisible(true);
java.awt.Window windows[] = java.awt.Window.getWindows();
}
};
//start window
frame = new JFrame("Window");
frame.setLocation(400, 200);
JButton button1 = new JButton("Click to begin");
//button to begin game
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JDialog load = new JDialog();
// load.setAlwaysOnTop(true);
// load.setSize(500,500);
// load.setVisible(true);
// load.add(new Label("Loading..."));
// load.pack();
frame.setVisible(false); // "start" window's visibility
// try {
// Thread.sleep(100000);
// } catch (Exception t) {
// }
// creates buttons
for (int i = 0; i < 105; i++) {
JFrame nextFrame = newFrame(butNum);
nextFrame.setVisible(true);
butNum++;
}
//creates instructions and tells user what button to find
JFrame instructions = new JFrame("How to play");
instructions.setSize(300,175);
instructions.setLayout(new GridLayout(4,1));
JPanel instPanel = new JPanel();
//button to remove instruction panel
JButton ok = new JButton("Ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
instructions.dispose();
}
});
instPanel.add(ok);
instructions.setLocation(400,200);
//layout of instruction panel
JLabel find = new JLabel("Your goal is to find Button " + butToFind + ".");
find.setHorizontalAlignment(JLabel.CENTER);
JLabel find2 = new JLabel("Click a button to make it disappear.");
find2.setHorizontalAlignment(JLabel.CENTER);
JLabel find3 = new JLabel("Good luck!");
find3.setHorizontalAlignment(JLabel.CENTER);
instructions.add(find);
instructions.add(find2);
instructions.add(find3);
instructions.add(instPanel);
instructions.setVisible(true);
}
});
frame.add(button1);
frame.setSize(150,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//creates frame with button in it
public static JFrame newFrame(int num) {
JFrame frame2 = new JFrame();
JButton button = new JButton("Button " + num);
if (num == butToFind) {
button.addActionListener(it);
frameToClose = frame2;
} else {
button.addActionListener(notIt);
}
frame2.add(button);
frame2.setSize(randNum(90,200), randNum(50,100));
frame2.setLocation(rand.nextInt(1200), rand.nextInt(800));
frame2.getContentPane().setBackground(new Color(rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255)));
frame2.setVisible(true);
return frame2;
}
//provides random number between high and low
public static int randNum(int low, int high) {
int result = -1;
while (result < low || result > high) {
result = rand.nextInt(high);
}
return result;
}
}
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static? Thanks!
First take a look at The Use of Multiple JFrames, Good/Bad Practice? and understand why I freaked out when I ran your code...
Instead of creating a bunch of frames, why not use something like JButton on another JPanel and add it to the current frame (this would also be a good use for a CardLayout)
JPanel panel = new JPanel(new GridLayout(10, 0));
Random rnd = new Random();
// creates buttons
for (int i = 0; i < 105; i++) {
JButton btn = new JButton(String.valueOf(i));
panel.add(btn);
//JFrame nextFrame = newFrame(butNum);
//nextFrame.setVisible(true);
//butNum++;
}
frame.getContentPane().removeAll();
frame.add(panel);
frame.revalidate();
frame.pack();
Alternatively, if you're really hell bent on using "frames", consider using a JDesktopPane and JInternalFrame instead.
See How to Use Internal Frames for more details
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static?
As much as possible, none. Instead of trying to create the whole thing in the main method, use the classes constructor to initialise the UI and use another method to actually get the game rolling...
public class ButtonGame {
private int butNum = 1;
private JFrame frame;
private ActionListener notIt;
private ActionListener it;
private Random rand = new Random();
private int butToFind = rand.nextInt(105);
private JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
ButtonGame game = new ButtonGame();
game.start();
}
public ButtonGame() {
//... All the code that was once in main...
frame.add(button1);
frame.setSize(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
frame.setVisible(true);
}
Answering to your side questions:
a static method can only accept static global variables
You can put all your code in the constructor and use main to only run the program.
Constructor:
public ButtonGame() {
// All of your code goes here - except the static methods
}
You should also make all other methods non-static.
To run the program:
public static void main(String[] args) {
new ButtonGame();
}

Counting click on button

I want to ask what function or another have to write so that every time I pressed the Start button (function:addbutton), the other button to exit (function:addButton2) to change its title to how many times I press the start?
class DroppingFrame extends JFrame {
public DroppingFrame() {
int clicked=0;
String b="a";
setSize(1400, 700);
setTitle("Dropping");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = getContentPane();
canvas = new JPanel();
contentPane.add(canvas, "Center");
JPanel p = new JPanel();
addButton(p, "Drop ball", clicked, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//addButton.setText(String.valueOf(++clicked));
Ball b = new Ball(canvas);
// if(b== new Ball(canvas)){
// clicked++;
// }
b.start();
}
});
addButton2(p, b, clicked, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
canvas.setVisible(false);
System.exit(0);
}
});
contentPane.add(p, "South");
}
public void addButton(Container c, String title, int i, ActionListener a) {
//i++;
//title = Integer.toString(i);
JButton b = new JButton(title);
c.add(b);
b.addActionListener(a);
}
public void addButton2(Container c, String title, int i, ActionListener a ) {
i++;
title = Integer.toString(i);
JButton b = new JButton(title);
c.add(b);
b.addActionListener(a);
}
private JPanel canvas;
}
My preference would be:
Make clicked a class field - that way you can access it and mutate it inside the event handler
Create a class field for a button
Refactor the addButton method so there is only one of them - this makes your code tidier:
Change the method return type to return the button created, then you decide if you store it or not from the caller. This just smells nicer.
The code looks like:
class DroppingFrame extends JFrame {
final JPanel canvas = new JPanel();
JButton button2;
int clicked = 0;
public DroppingFrame() {
setSize(1400, 700);
setTitle("Dropping");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = getContentPane();
contentPane.add(canvas, "Center");
JPanel p = new JPanel();
addButton(p, "Drop ball", clicked, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Ball b = new Ball(canvas);
b.start();
button2.setText(String.valueOf(++clicked));
}
});
button2 = addButton(p, String.valueOf(clicked), clicked, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
canvas.setVisible(false);
System.exit(0);
}
});
contentPane.add(p, "South");
}
public JButton addButton(Container c, String title, int i, ActionListener a) {
JButton b = new JButton(title);
c.add(b);
b.addActionListener(a);
return b;
}
}
It requires the reference of the second button so that start button can update its text.
Keep it simple:
Use setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); instead of adding WindowListener to close the window.
Use JFrame#dispose to close the JFrame programmatically.
Favor Composition over Inheritance It means if you are not overriding any logic/implementation of the existing class then don't extend it.
There is no meaning of creating separate method for adding each component. Either make the method generic or simply remove it.
Sample code:
public class DroppingFrame {
private int clicked = 0;
public DroppingFrame() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
JPanel p = new JPanel();
final JButton btn2 = new JButton(String.valueOf(clicked));
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.dispose();
}
});
JButton btn1 = new JButton("Drop ball");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
btn2.setText(String.valueOf(++clicked));
}
});
p.add(btn1);
p.add(btn2);
contentPane.add(p, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
It's not correct.. addButton always creates a new button and its reference is lost.. you should make it class-scoped.
So make a class variable:
JButton button = new JButton();
Change your function:
public void addButton(Container c, String title, int i, ActionListener a) {
button.setText(title);
c.add(button);
button.addActionListener(a);
}
And also change your actionPerformed override:
public void actionPerformed(ActionEvent evt) {
button.setText(String.valueOf(++clicked));
....
});

How to use variables set in an actionlistener

I am having problems understanding how to use an actionlistener to change the value of variables.
In my program I need to store the choices the user makes by selecting some radio buttons.
I have got a main class with a card layout, then several classes which each are different panels. In one of the panels I have some radio buttons, with an actionlistener as an inner class.
When I try to print the variable value in the main class, it is printed immediately, before the user has made a choice, as I instantiate the panel class and get the variable from it I get the variable before it has been changed by the user.
I know I should not think in a linear manner with Java, but how can I make sure that I fetch the variable after it has been changed by the user and not before? I will not be able to do that will I? I understand there is some flaw in my thinking but I haven't slept properly for ages and I just cannot get my head around this.
public class Screen3 extends JPanel{
JRadioButton addition = new JRadioButton("Addition");
JRadioButton subtraction = new JRadioButton("Subtraction");
JRadioButton multiplication = new JRadioButton("Multiplication");
JRadioButton division = new JRadioButton("Division");
JRadioButton all = new JRadioButton("All");
JRadioButton single = new JRadioButton("Single");
JRadioButton two = new JRadioButton("Double");
JRadioButton triple = new JRadioButton("Triple");
JRadioButton mix = new JRadioButton("Mix");
JRadioButton five = new JRadioButton("5");
JRadioButton ten = new JRadioButton("10");
private int type, digit, rounds;
public Screen3() {
JPanel firstButtonPanel = new JPanel();
JPanel secondButtonPanel = new JPanel();
ButtonGroup myFirstGroup = new ButtonGroup();
ButtonGroup mySecondGroup = new ButtonGroup();
myFirstGroup.add(addition);
myFirstGroup.add(subtraction);
myFirstGroup.add(multiplication);
myFirstGroup.add(division);
//myFirstGroup.add(all);
mySecondGroup.add(single);
mySecondGroup.add(two);
mySecondGroup.add(triple);
//mySecondGroup.add(mix);
firstButtonPanel.setLayout(new FlowLayout());
firstButtonPanel.add(addition);
firstButtonPanel.add(subtraction);
firstButtonPanel.add(multiplication);
firstButtonPanel.add(division);
//firstButtonPanel.add(all);
secondButtonPanel.setLayout(new FlowLayout());
secondButtonPanel.add(single);
secondButtonPanel.add(two);
secondButtonPanel.add(triple);
//secondButtonPanel.add(mix);
JPanel buttons = new JPanel();
buttons.setLayout(new BorderLayout());
buttons.add(selectionLabel, BorderLayout.NORTH);
buttons.add(firstButtonPanel, BorderLayout.CENTER);
buttons.add(secondButtonPanel, BorderLayout.SOUTH);
ButtonGroup myThirdGroup = new ButtonGroup();
JPanel endButtons = new JPanel();
myThirdGroup.add(five);
myThirdGroup.add(ten);
endButtons.add(five);
endButtons.add(ten);
endPanel.setLayout(new BorderLayout());
endPanel.add(rounds, BorderLayout.NORTH);
endPanel.add(endButtons, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(buttons, BorderLayout.NORTH);
Selection sn = new Selection();
addition.addActionListener(sn);
subtraction.addActionListener(sn);
multiplication.addActionListener(sn);
division.addActionListener(sn);
single.addActionListener(sn);
two.addActionListener(sn);
triple.addActionListener(sn);
five.addActionListener(sn);
ten.addActionListener(sn);
}
public int getType() {
return type;
}
public int getDigit() {
return digit;
}
public int getRounds() {
return rounds;
}
public class Selection implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(addition.isSelected()) {
type = 1;
}
else if(subtraction.isSelected()) {
type = 2;
}
else if(multiplication.isSelected())
type = 3;
else if(division.isSelected())
type = 4;
//else if(all.isSelected())
//type = 5;
if(single.isSelected()) {
digit = 1;
System.out.println("single");
}
else if(two.isSelected())
digit = 2;
else if(triple.isSelected())
digit = 3;
if(five.isSelected())
rounds = 5;
else if(ten.isSelected())
rounds = 10;
}
}
}
Here is the main class:
public class Driver {
public JFrame frame = new JFrame("Math Game");
public JPanel screens = new JPanel(new CardLayout());
int digit = 1;
int rounds = 1;
int type = 1;
Driver() {
}
public void show() {
JPanel buttonPanel = new JPanel();
JButton next = new JButton("Next");
JButton previous = new JButton("Previous");
buttonPanel.add(previous);
buttonPanel.add(next);
Screen1 screen1 = new Screen1();
Screen2 screen2 = new Screen2();
Screen3 screen3 = new Screen3();
screens.add(screen1, "welcome");
screens.add(screen2, "next");
screens.add(screen3, "selection");
frame.add(screens);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(400, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
next.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cl = (CardLayout)(screens.getLayout());
cl.next(screens);
}
});
previous.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cl = (CardLayout)(screens.getLayout());
cl.previous(screens);
}
});
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Driver dr = new Driver();
dr.show();
}
});
}
}
I just try a test print of System.out.println(screen3.getType()); either in show() or main
Use JOptionPane/JDialog which has modality.
Have a read on How to Make Dialogs
In example here is only printed after JDialog is closed:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JDialog jd = new JDialog();
jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
jd.setModal(true);
jd.pack();
jd.setVisible(true);
System.out.println("Here");
}
});
}
In this example here is only printed after JOptionPane is closed:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JPanel panel=new JPanel();
panel.add(new JLabel("Hello, world!"));
JOptionPane.showMessageDialog(null, panel, "Panel Message",JOptionPane.PLAIN_MESSAGE);
System.out.println("Here");
}
});
}
I know I should not think in a linear manner with Java, but how can I
make sure that I fetch the variable after it has been changed by the
user and not before?
After using a modal JDialog/JOptionPane you would simply use public getters to access the variable contained within the class instance:
public class Test {
public static void main(String[] args) {
X x= new X();//will only return after dialog closed
System.out.println(x.getY());
}
}
class X {
private int y=0;//will be assigned during dialog/joptionpanes life span
public X() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//creates and shows the modal dialog/optionpane which will allow modification of variable y through some input/controls
}
});
}
public int getY() {
return y;
}
}

Categories