I am working on an application in which I have developed a window with three check boxes. When first and second check boxes are selected, new windows will be opened as desired. The third check box is for closing the application. When Exit check box is selected, it is showing the conformation Dialog as desired but Exit check box is not ticked.
I could not trace out the issue here. Please help me to resolve this issue!
package jcheckbox;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InitiaaWindow extends JPanel {
static JFrame frame = new JFrame("Credit Contract Validation");
private static final long serialVersionUID = 1L;
JCheckBox jValidateECOUT;
JCheckBox jValidateSuperDeals;
JCheckBox jEXIT;
JLabel jlbPicture,jlbPicture1;
CheckBoxListener myListener = null;
public InitiaaWindow() {
myListener = new CheckBoxListener();
jValidateECOUT = new JCheckBox("ValidateECOUT");
jValidateECOUT.setMnemonic(KeyEvent.VK_C);
jValidateECOUT.setSelected(false);
jValidateECOUT.addItemListener(myListener);
jValidateSuperDeals = new JCheckBox("ValidateSuperDeals");
jValidateSuperDeals.setMnemonic(KeyEvent.VK_G);
jValidateSuperDeals.setSelected(false);
jValidateSuperDeals.addItemListener(myListener);
jEXIT = new JCheckBox("EXIT");
jEXIT.setMnemonic(KeyEvent.VK_G);
jEXIT.setSelected(false);
jEXIT.addItemListener(myListener);
jlbPicture = new JLabel(new ImageIcon("src/jcheckbox/image.jpg"));
jlbPicture1 = new JLabel(new ImageIcon("src/jcheckbox/image1.jpg"));
JPanel jplCheckBox = new JPanel();
jplCheckBox.setLayout(new GridLayout(0, 1));
jplCheckBox.add(jValidateECOUT);
jplCheckBox.add(jValidateSuperDeals);
jplCheckBox.add(jEXIT);
setLayout(new BorderLayout());
add(jplCheckBox, BorderLayout.WEST);
add(jlbPicture1, BorderLayout.CENTER);
add(jlbPicture, BorderLayout.EAST);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
class CheckBoxListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (jValidateECOUT.isSelected())
{
try {
UIPack.UI.myMethod(null);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (jValidateSuperDeals.isSelected())
{
try {
ValidateSuperDealsUIPack.UI.ValidateSuperDealsUI(null);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (jEXIT.isSelected())
{
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Would you like to close the application", "Conformation message",dialogButton);
if(dialogResult==0)
System.exit(1);
else
JOptionPane.getRootFrame().dispose();
}
}
}
public static void main(String s[]) {
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new InitiaaWindow());
frame.pack();
frame.setVisible(true);
}
}
Since showConfirmDialog creates a modal dialog until the dialog is closed the execution of item selection event may not propagate to other listeners which might be responsible for updating the display of the checkbox.
If you click 'No' in the dialog, does the checkbox update properly? If yes then you can create the dialog in a separate runnable task using SwingUtilities.invokeLater this will ensure the current processing of selection event completes before the modal dialog is opned.
You can add
jEXIT.setSelected(true);
before
int dialogButton = JOptionPane.YES_NO_OPTION;
1.Sorry, but your code style is really terrible (IMHO, I don't want you to be dissappointed of that).
2.Use ActionListener instead of ItemListener for JCheckBox. And check the source of action before process it:
ActionListener listener = new ActionListener({
#Override
public void actionPerfomed(ActionEvent ae) {
if (ae.getSource().equals(comboBox1) {
//process 1
} else if (ae.getSource().equals(comboBox2) {
//process 2
} else if (ae.getSource().equals(comboBox3) {
//process 3
}
}
});
comboBox1.add(listener);
comboBox2.add(listener);
comboBox3.add(listener);
3.If you want to show modal dialogs on action events, it is good to use SwingUtilities.invokeLater() for that, because your action' source should repaint after action perfomed.
Related
I'm trying to put a conditional in a JDialog which detect if the two buttons in it are disabled. I need that also to close the dialog when it reach this condition so I found 2 problems. Example code:
public static String windowvisitAlert(JButton but, JButton but2, String message1, String message2) throws Exception, Exception {
String n = "";
Object[] options = {but, but2};
Object a = message1;
JOptionPane pane = new JOptionPane(a, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
JDialog dialog = pane.createDialog(message2);
dialog.setContentPane(pane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setSize(new Dimension(450, 10));
dialog.pack();
dialog.setVisible(true);
return n;
}
This is the method which creates a JDialog from a JPanel options. We have 2 buttons and 2 "messages" which only determinates the name of the dialog window.
I tried to put :
if (but.isEnabled()==false && but2.isEnabled()==false) {
dialog.setVisible(false);
}else{
dialog.setVisible(true);}
Also this method will return the value n so I don't know how will a condition work inside it.
Where i implement this method:
public void actionPerformed(ActionEvent e) {
final JButton but = new JButton("VISITA");
final JButton but2 = new JButton("RESPONSABLE");
try {
ActionListener actionListener2 = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//action performed
}
};
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//action performed
}
};
but.addActionListener(actionListener2);
but2.addActionListener(actionListener);
Alerts.windowvisitAlert(but, but2, Gui.getProperties().getProperty("text"), Gui.getProperties().getProperty("text"));
}catch (Exception ex) {
sc.functionSavingInLog(Utils.getClassInfo(Thread.currentThread().getStackTrace()[1]), ex.toString());
System.out.println(Utils.getClassInfo(Thread.currentThread().getStackTrace()[1]) + ex);
}
}
This is actually not working so my question is:
-How can I make this condition work and make the JDialog close when it hits it?
If not, how can I change the method or just do a jpanel?
new to programming and Java is the first language I'm learning.
I'm having difficulty thinking through the logic on this application I'm building. The application is really simple: it has say five checkboxes and a sync button. You select a checkbox and click sync and it runs a cmd command associated with the specific checkbox.
However, I would like to be able to check multiple checkboxes and hit sync and have them all go instead of doing it one at a time. I currently have an if statement (if the checkbox is selected and sync button is pressed) run "xyz" command (that corresponds to that checkbox). But it only runs for the first checkbox (if) and then quits.
Thanks!
Edit. Code below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Scanner;
class RcSync extends JFrame implements ActionListener{
Container contentPane = getContentPane();
JPanel top = new JPanel();
JPanel center = new JPanel();
JPanel bottom = new JPanel();
JScrollPane mainScrollFrame = new JScrollPane(center);
JLabel displayMessage = new JLabel("Please select a item, and click sync:");
Font customFontHeader = new Font("", Font.BOLD,15);
JButton syncButton = new JButton("Sync");
JButton cancelButton = new JButton("Cancel");
String[] database = {"Apple","Pineapple","Orange","Pear","Fig"};
JCheckBox chk1 = new JCheckBox(database[0]);
JCheckBox chk2 = new JCheckBox(database[1]);
JCheckBox chk3 = new JCheckBox(database[2]);
JCheckBox chk4 = new JCheckBox(database[3]);
JCheckBox chk5 = new JCheckBox(database[4]);
JCheckBox chk6 = new JCheckBox(database[5]);
public RcSync() {
super ("Sync Application");
setSize (400,450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(top);
setVisible(true);
top.add(displayMessage);
displayMessage.setFont(customFontHeader);
center.add(chk1);
center.add(chk2);
center.add(chk3);
center.add(chk4);
center.add(chk5);
bottom.add(syncButton);
syncButton.addActionListener(this);
cancelButton.addActionListener(new CloseListener());
bottom.add(cancelButton);
bottom.add(emailButton);
emailButton.addActionListener(this);
contentPane.add("North", top);
contentPane.add("South", bottom);
this.getContentPane().add(mainScrollFrame, BorderLayout.CENTER);
center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));
}
public void actionPerformed(ActionEvent event){
if ((event.getSource() == syncButton) && (chk1.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk1.getText());
} catch (IOException e) {
e.printStackTrace();}
}
if ((event.getSource() == syncButton) && (chk2.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk2.getText());
} catch (IOException e) {
e.printStackTrace();}
}
if ((event.getSource() == syncButton) && (chk3.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk3.getText());
} catch (IOException e) {
e.printStackTrace();}
}
if ((event.getSource() == syncButton) && (chk4.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk4.getText());
} catch (IOException e) {
e.printStackTrace();}
}
if ((event.getSource() == syncButton) && (chk5.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk5.getText());
} catch (IOException e) {
e.printStackTrace();}
}
}
private class CloseListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main (String[]args){
RsSync gui = new RcSsync();
}
}
}
I have edited my response since you provided more context to your question. Pasted below: is my approach to solving your problem, working code with explanation, and errors I had to resolve with your associated code:
Approach: Associate a boolean value for each checkbox corresponding to whether or not that option has been 'selected by the end user'. When the sync button is clicked, find which checkboxes have been selected. These checkboxes will return a true value from their isSelected() method. For each checkbox selected add the associated command into a List containing all the commands to be ran on the end user's machine. Iterate through this list until there are no commands left to be ran.
Code:
import javax.swing.*;
import java.util.ArrayList;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
class RcSync extends JFrame implements ActionListener{
Container contentPane = getContentPane();
JPanel top = new JPanel();
JPanel center = new JPanel();
JPanel bottom = new JPanel();
JScrollPane mainScrollFrame = new JScrollPane(center);
JLabel displayMessage = new JLabel("Please select a item, and click sync:");
Font customFontHeader = new Font("", Font.BOLD,15);
JButton syncButton = new JButton("Sync");
JButton cancelButton = new JButton("Cancel");
// Encapsulate your checkboxes to commands, since there is one
// to one relationship and makes future changes easier since there is a single point of change
String[] database = {"Apple","Pineapple","Orange","Pear","Fig"};
CheckboxCommand chk1 = new CheckboxCommand("Checkbox 1 cmd", new JCheckBox(database[0]));
CheckboxCommand chk2 = new CheckboxCommand("Checkbox 2 cmd", new JCheckBox(database[1]));
CheckboxCommand chk3 = new CheckboxCommand("Checkbox 3 cmd", new JCheckBox(database[2]));
CheckboxCommand chk4 = new CheckboxCommand("Checkbox 4 cmd", new JCheckBox(database[3]));
CheckboxCommand chk5 = new CheckboxCommand("Checkbox 5 cmd", new JCheckBox(database[4]));
public RcSync() {
super ("Sync Application");
setSize (400,450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(top);
setVisible(true);
top.add(displayMessage);
displayMessage.setFont(customFontHeader);
center.add(chk1.checkbox);
center.add(chk2.checkbox);
center.add(chk3.checkbox);
center.add(chk4.checkbox);
center.add(chk5.checkbox);
bottom.add(syncButton);
syncButton.addActionListener(this);
cancelButton.addActionListener(new CloseListener());
bottom.add(cancelButton);
// TODO email button doesn't exist, assuming copy/paste error?
// bottom.add(emailButton);
// emailButton.addActionListener(this);
contentPane.add("North", top);
contentPane.add("South", bottom);
this.getContentPane().add(mainScrollFrame, BorderLayout.CENTER);
center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));
}
public void actionPerformed(ActionEvent event){
// Implements the approach I described initially
if (event.getSource() == syncButton){
List<String> cmdsToRun = new ArrayList<>();
if (chk1.isSelected()){
cmdsToRun.add(chk1.getCmdToRun());
}
if (chk2.isSelected()){
cmdsToRun.add(chk2.getCmdToRun());
}
if (chk3.isSelected()){
cmdsToRun.add(chk3.getCmdToRun());
}
if (chk4.isSelected()){
cmdsToRun.add(chk4.getCmdToRun());
}
if (chk5.isSelected()){
cmdsToRun.add(chk5.getCmdToRun());
}
// Note: for verification purposes I just print out your commands
// since they're hard coded to your particular environment
System.out.println(cmdsToRun);
// This is where you would loop through your command list i.e.
// for (int x=0; x<cmdsToRun; x++){ //run command at cmdToRun.get(x); }
}
}
private class CloseListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
// encapsulating your checkboxes to commands
private class CheckboxCommand {
private String cmdToRun;
private boolean isSelected;
private JCheckBox checkbox;
public CheckboxCommand(String cmdToRun, JCheckBox checkbox) {
this.cmdToRun = cmdToRun;
this.checkbox = checkbox;
}
public String getCmdToRun() {
return cmdToRun;
}
public void setCmdToRun(String cmdToRun) {
this.cmdToRun = cmdToRun;
}
public boolean isSelected() {
return this.checkbox.isSelected();
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
public static void main (String[]args){
// Fixed your typo error to run the swing interface
RcSync gui = new RcSync();
}
}
Verification of correct code:
Key Insight:
I encapsulated your commands to checkboxes into a private class since there is a one to one relationship and this will allow your code to have a single point of change, which in general is a best practice :)
Side Note:
I don't actually run your commands on my end since they're tied to your particular machine. I.e. associated to local scripts, so I printed out dummy commands to prove the code functions appropriately. I added a comment block in the code to show where you can add your environment specific code i.e. Runtime.getRuntime().exec("<CMD>");
Errors to be fixed:
I removed this line: JCheckBox chk6 = new JCheckBox(database[5]); since this will throw an indexOutOfBounds exception since there are only 5 elements in your in-memory database variable not 6.
emailButton doesn't exist so I commented it out:
// bottom.add(emailButton);
// emailButton.addActionListener(this);
This is a typo and won't run the gui: RsSync gui = new RcSsync(); so I changed it appropriately: RcSync gui = new RcSync();
Hopefully that helps! :)
I have this code sample in a separate jDialog (jDialog is in the same package as that of JFrame) which used to check (using a Thread) if the jCheckBox1 in the jFrame is whether visible or not. JDialog is set to visible by clicking a JLabel (Change Password) in JFrame. I have not set the visibility of the JFrame even to false even after I click on the Change Password JLabel.
The problem I encountered is that even if the JFrame is not visible i.e when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible" and I'm more than sure that the jFrame is not visible and not running.
This is the code snippet (Thread) I have used to check the visibility of the JFrame's jCheckBox1:
LockOptions lock = new LockOptions();
private void setLocation2() {
new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lock.jCheckBox1.isVisible()) {
System.out.println("Visible");
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
And this is the Code I have written in JFrame's Change Password JLabel:
private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {
Container c = new ChangePassword(this, rootPaneCheckingEnabled);
if (!c.isShowing()) {
c.setVisible(true);
hideMeToSystemTray();
this.requestFocusInWindow();
}
}
But when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible"
I have attached a Screenshots of both JFrame and JDialog
JFrame containing jCheckBox1
JDialog:
OK, let's have the simplest possible example.
The following code creates a main frame having a button to create a new frame of class LockOptionsWindow, which extends JFrame.
The class FrameDemo implements Runnable. So can it be accessed on the event dispatching thread using SwingUtilities.invokeLater as mentioned in Swing's Threading Policy. So it is possible creating a new thread checklockoptionswindow which then can check whether the new window created by the button is visible or not visible.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameDemo extends WindowAdapter implements ActionListener, Runnable {
private LockOptionsWindow lockoptionswindow;
private Thread checklockoptionswindow = new Thread();
private void showLockOptionsWindow() {
if (lockoptionswindow != null && lockoptionswindow.isDisplayable()) {
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
} else {
lockoptionswindow = new LockOptionsWindow();
lockoptionswindow.setSize(new Dimension(300, 100));
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
}
}
private void startCheckLockOptionsWindow() {
if (!checklockoptionswindow.isAlive()) {
checklockoptionswindow = new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lockoptionswindow.isVisible()) {
if (lockoptionswindow.getExtendedState() == Frame.ICONIFIED) {
System.out.println("Visible iconified");
} else {
System.out.print("Visible on screen ");
int x = lockoptionswindow.getLocation().x;
int y = lockoptionswindow.getLocation().y;
System.out.println("at position " + x + ", " + y);
}
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
checklockoptionswindow.start();
}
}
public void actionPerformed(ActionEvent e) {
showLockOptionsWindow();
startCheckLockOptionsWindow();
}
public void run() {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Show LockOptions frame");
button.addActionListener(this);
Container contentPane = frame.getContentPane();
contentPane.add(button);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new FrameDemo());
}
class LockOptionsWindow extends JFrame {
public LockOptionsWindow() {
super("LockOptions frame");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
}
Edited to determine whether the LockOptionsWindow is visible iconified only or is really showed as window on the screen.
I have an application I'm making for a game to automatically update a game client.
Once you press Launch, it will open up my DownloadFrame (extends JDialog), and will look like this:
If you click the icon for the application in the taskbar, (maybe Windows 8 is the problem?) it will minimize the application like usual. However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent. It looks like this:
Here's my code for my extension of JDialog. Apologies in advance for it being messy.
public class DownloadFrame extends JDialog implements Runnable {
private static final long serialVersionUID = -8764984599528942303L;
private Background frame;
private ImageIcon[] gifs;
private JLabel spinner;
public DownloadFrame() {
super(Loader.application, false);
setLayout(null);
setUndecorated(true);
setAutoRequestFocus(true);
new Thread(this).start();
generateBackground();
generateButton();
generateGif();
}
private void generateBackground() {
frame = new Background("sub_background.png");
setSize(frame.getWidth(), frame.getHeight());
setBackground(new Color(1.0f, 1.0f, 1.0f, 0.0f));
setLocationRelativeTo(null);
setLocation(this.getX(), this.getY() + 5);
setLayout(null);
setContentPane(frame);
}
private void generateGif() {
gifs = Utils.generateGifImages();
spinner = new JLabel(gifs[0]);
spinner.setBounds(70, 30, gifs[0].getIconWidth(), gifs[0].getIconHeight());
add(spinner);
}
private HoverableButton cancel;
public HoverableButton getCancelButton() {
return cancel;
}
private void generateButton() {
cancel = new HoverableButton(Settings.CANCEL_BUTTON, 75, 145);
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
/*
* TODO -
* stop the download in progress
*/
for (HoverableButton button : Loader.application.getPrimaryButtons()) {
button.setActive(true);
button.setVisible(true);
}
dispose();
}
});
add(cancel);
}
private int cycleCount;
private void cycleGif() {
if (spinner == null) {
return;
}
cycleCount++;
if (cycleCount > 7) {
cycleCount = 0;
}
spinner.setIcon(gifs[cycleCount]);
}
#Override
public void run() {
while (true) {
cycleGif();
try {
Thread.sleep(100L);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
In case it's needed, here's my usage of it. Most of the stuff can be ignored I'm sure, it's simply there to hide the four buttons while the download is in progress.
((HoverableButton) components[2]).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
HoverableButton source = (HoverableButton) components[2];
if (source.isActive()) {
try {
Thread.sleep(500L);
} catch (Exception ex) {
ex.printStackTrace();
}
if (panel == null) {
panel = new DownloadFrame();
panel.setVisible(true);
} else {
panel.setVisible(true);
panel.getCancelButton().removeHighlight();
}
for (HoverableButton button : getPrimaryButtons()) {
button.setActive(false);
button.setVisible(false);
button.removeHighlight();
}
/*
* TODO -
* handle checking for updates / downloading updates
*/
}
}
});
However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent
Yes. When you create the JDialog, you need to specify the "owner" JFrame of the dialog in the constructor.
So you must create and make the JFrame and make the frame visible before you create the dialog.
This might be a very simple thing that I'm overlooking, but I just can't seem to figure it out.
I have the following method that updates a JTable:
class TableModel extends AbstractTableModel {
public void updateTable() {
try {
// update table here
...
} catch (NullPointerException npe) {
isOpenDialog = true;
JOptionPane.showMessageDialog(null, "No active shares found on this IP!");
isOpenDialog = false;
}
}
}
However, I don't want isOpenDialog boolean to be set to false until the OK button on the message dialog is pressed, because if a user presses enter it will activate a KeyListener event on a textfield and it triggers that entire block of code again if it's set to false.
Part of the KeyListener code is shown below:
public class KeyReleased implements KeyListener {
...
#Override
public void keyReleased(KeyEvent ke) {
if(txtIPField.getText().matches(IPADDRESS_PATTERN)) {
validIP = true;
} else {
validIP = false;
}
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
if (validIP && !isOpenDialog) {
updateTable();
}
}
}
}
Does JOptionPane.showMessageDialog() have some sort of mechanism that prevents executing the next line until the OK button is pressed? Thank you.
The JOptionPane creates a modal dialog and so the line beyond it will by design not be called until the dialog has been dealt with (either one of the buttons have been pushed or the close menu button has been pressed).
More important, you shouldn't be using a KeyListener for this sort of thing. If you want to have a JTextField listen for press of the enter key, add an ActionListener to it.
An easy work around to suite your needs is the use of showConfirmDialog(...), over showMessageDialog(), this lets you take the input from the user and then proceed likewise. Do have a look at this example program, for clarification :-)
import javax.swing.*;
public class JOptionExample
{
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
int selection = JOptionPane.showConfirmDialog(
null
, "No active shares found on this IP!"
, "Selection : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.INFORMATION_MESSAGE);
System.out.println("I be written" +
" after you close, the JOptionPane");
if (selection == JOptionPane.OK_OPTION)
{
// Code to use when OK is PRESSED.
System.out.println("Selected Option is OK : " + selection);
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
// Code to use when CANCEL is PRESSED.
System.out.println("Selected Option Is CANCEL : " + selection);
}
}
});
}
}
You can get acces to the OK button if you create optionpanel and custom dialog. Here's an example of this kind of implementation:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author OZBORN
*/
public class TestyDialog {
static JFrame okno;
static JPanel panel;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
zrobOkno();
JButton przycisk =new JButton("Dialog");
przycisk.setSize(200,200);
panel.add(przycisk,BorderLayout.CENTER);
panel.setCursor(null);
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
przycisk.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor"));
final JOptionPane optionPane = new JOptionPane(
"U can close this dialog\n"
+ "by pressing ok button, close frame button or by clicking outside of the dialog box.\n"
+"Every time there will be action defined in the windowLostFocus function"
+ "Do you understand?",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION);
System.out.println(optionPane.getComponentCount());
przycisk.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
final JFrame aa=new JFrame();
final JDialog dialog = new JDialog(aa,"Click a button",false);
((JButton)((JPanel)optionPane.getComponents()[1]).getComponent(0)).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
aa.dispose();
}
});
dialog.setContentPane(optionPane);
dialog.pack();
dialog.addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Zamykam");
aa.dispose();
}
#Override public void windowGainedFocus(WindowEvent e) {}
});
dialog.setVisible(true);
}
});
}
public static void zrobOkno(){
okno=new JFrame("Testy okno");
okno.setLocationRelativeTo(null);
okno.setSize(200,200);
okno.setPreferredSize(new Dimension(200,200));
okno.setVisible(true);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel();
panel.setPreferredSize(new Dimension(200,200));
panel.setLayout(new BorderLayout());
okno.add(panel);
}
}
Try this,
catch(NullPointerException ex){
Thread t = new Thread(new Runnable(){
public void run(){
isOpenDialog = true;
JOptionPane.setMessageDialog(Title,Content);
}
});
t.start();
t.join(); // Join will make the thread wait for t to finish its run method, before
executing the below lines
isOpenDialog = false;
}