Removing Cancel Button and "X" From Dialog Box in Swing - java

I'm currently working on a chess game for a school project. When you promote a pawn, it opens a dialog box that allows the player to select which piece they would like to promote to. However, when the player clicks "cancel" or "X", then the box simply returns null, and the user cannot promote their piece. I was wondering if I could remove/disable the cancel button and the "X" button. Here is my code:
private String createDialog() {
hideLabels();
Object[] options = {"Queen", "Knight", "Bishop", "Rook"};
String selection = (String)JOptionPane.showInputDialog(frame, "What would you like to promote to?, ", "Promote", JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
return selection;
}

Instead of using a JOptionPane which doesn't give you much control over the functionality you can create your own custom JDialog and add your own components and buttons to the dialog.
You can't remove the close button, but you can prevent the close button from doing anything by adding:
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
Or if you really want to use a JOptionPane then check out the section from the Swing tutorial on Stopping a Dialog From Closing which shows how you check to make sure a valid value has been entered.

Related

If Statements based on selection from dropdown

I have read through all of the other articles and I am not finding my answers.
I start out with a JOptionPane with object options. When the user selects either animals or habitat another drop down will appears with selections. Right now I am working on getting another pop up with information to open when Lions is selected. But I can't get it to work.
Also I viewed someone else's input to have the ability for these drop downs to appear. But they are using JFrame so another window for java opens up outside of NetBeans.
What I am trying to do right now is enter if statements for selections from dropdown but I don't think it is working correctly. When I run the code and select animals and choose Tigers the window for Lions will pop up and when I say okay the Tigers box pops up. I also need to figure out how to enter a warning statement in some of the selections from dropdown. For health concerns for each animal. I thought about adding a button for additional information but I want to be able to have it automatically pop up. I'm still reading through the API documentation but I just want a simple message dialog to display the information.
public class MonitoringSystem {
public static void main(String[] args){
ImageIcon icon = new ImageIcon(img.class.getResource("zoo.png"));
String[] options = {"Animals", "Habitat", "Exit"};
int x = JOptionPane.showOptionDialog(null, "Zookeepers would you like to view animal activities or monitor habitats?",
"Welcome to the Brooklyn Zoo!", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]);
System.out.println(x);
JFrame animal = new JFrame("Animals");
JFrame habitat = new JFrame("Habitats");
if(x==0){
animal.setVisible(true);
String[] choices = {"Lions","Tigers","Bears","Giraffes",};
String input = (String) JOptionPane.showInputDialog(null,"Select Animal:","Zoo Animals",
JOptionPane.QUESTION_MESSAGE,null,choices,choices[1]);
if ("Lions".equals(choices));
JOptionPane.showMessageDialog(null, "Animal: Lion\nName: Leo\nAge: 5 \nFeeding Schedule: Twice daily");
{
}
if("Tigers".equals(choices));
JOptionPane.showMessageDialog(null, "Animal: Tiger\nName: Maj\nAge: 15 \nFeeding Schedule: 3x daily");
if(choice=="Lions")
Don't use "==" for Object comparison.
Instead use the String.equals(...) method.
I start out with a JOptionPane with object options
Sound reasonable. You create an Array of String options and use the showOptionPane(...) method.
Right now I am working on getting another pop up with information to open when Lions is selected
So why are you using showInputDialog(...) this time?
If showOptionPane(...) worked before why are you changing methods?
JFrame animal = new JFrame("Animals");
JFrame habitat = new JFrame("Habitats");
What is the point of those statements?
Read the section from the Swing tutorial on How to Make Dialogs for more examples of using a JOptionPane.
If you are just trying to display information about a Lion. then add the text to a JTextArea and then display the JTextArea in the JOptionPane. You can add any Swing component to an JOptionPane. Read the JOptionPane API.

How can I detect if a user closes the window via the red cross?

The goal of my code is to get the user input and when the user would like to save the data, they press the OK option. However, if the user has input some data, and would no longer like to continue, they then just press the red cross exit button via the top right corner to exit without saving?
How do I go about this?
Here's my code:
JOptionPane.showMessageDialog(null, myPanel, "Edit Fruit", JOptionPane.INFORMATION_MESSAGE);
...
if (!(JOptionPane.OK_OPTION))
{
//If the user exits the option pane via the red cross, exit the loop.
break;
}
EDIT: This code does not work as I'm only looking for when a JOptionPane.showMessageDialog is closed via the red cross and not an OK button:
addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
System.out.println("Closed");
e.getWindow().dispose();
}
});
The code still executes even when I press the OK option in my JOptionPane. I only want to listen for the exit via the red cross.
Thanks for your help.
Firstly, it's not a very standard UI to do something only if the user closes a window by the red x - as opposed to closing the window by typing Alt-F4, or double clicking the icon, or Alt-Space-C, and so on; so I'll assume you just meant closing without pressing the OK button rather than by the red x specifically.
You have code which can detect when the window is closed.
You have code can detect when the user presses the OK button.
So set a flag to indicate the OK button was pressed, and if the flag is not set when the window closed, then the user closed the window without pressing the OK button.
Another quick search with the keywords "JOptionPanel close listener" takes me to another question.
How can I add a listener on the ok button of JOptionPane?
The accepted answer suggests to check the return value of the method showOptionDialog.
But you can use the method JOptionPane.showOptionDialog with a single
DEFAULT_OPTION for the OK button. The showOptionDialog will return 0
if OK was clicked and -1 if the user closed the dialog.
int res = JOptionPane.showOptionDialog(null, "Hello", "Test",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, null, null);
System.out.println(res);
You don't need a listener because the javadoc says:
Each showXxxDialog method blocks the caller until the user's
interaction is complete.
Here, there is no difference between close with rea cross, with key combinations, etc., as the first answer suggests. But, I guess maybe you don't need.

How can you set an actionlistener on the ok option of a jdialog?

Hi i want to trigger some action when the ok button of jdialog is pressed, i know that you can do this way
int rep =JOptionPane.showConfirmDialog(null, pangesfac, "Gestion des chambres a facturer", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if(rep == JOptionPane.OK_OPTION) {//actions to do}
but in my case i want an external controller to take care of the things that have to be done (my code is structured by mvc) when the ok button is pressed. SO how can you set set up an action listner on the ok button ?
It is possible but it isn't as easy as adding an ActionListener to the OK button. You have to use a PropertyChangeListener.
An example is shown on this page: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#stayup
However you might want to reconsider your design. You can still pass the result from the JOptionPane to your controller without capturing the event itself.

JOptionPane.showOptionDialog does not always move to front in Applet

I have a JOptionPane popup in my applet normally, a-la:
Object[] options = {"Grade", "Save", "Cancel"};
selection = JOptionPane.showOptionDialog(this,
"Do you want to grade now or save your work to continue later?",
"Grade Or Save",
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
this refers to the JApplet object.
The popup works fine and everything, but occasionally it will appear behind the applet instead of popping up in front of it.
Unknowingly you not may be passing in the parent component; specifically "this" into the showOptionDialog(). Make sure "this" is actually the parent component.
If "this" refers to a Frame you can find what frame is in focus by doing the following:
(pseduo code)
myFrames[] = Frame.getFrames();
if ( myFrames[i].isFocused() )
frame to pass in :)
The thing to do is find the parent of the applet that is a Frame (it's of a hidden, plugin specific type) and use that frame as the dialog owner. You can find that with (Frame)SwingUtilities.getAncestorOfClass(java.awt.Frame.class, theApplet);
That will ensure the dialog remains on top of the browser. However, if the user switches browser tabs, the dialog doesn't hide.

java wait for dialog to be closed

i have a small program where an element is draged and dropped, when the drop is performed i open a dialog (extends Jframe) where some text should be entered. The Problem is, that i want to wait for this dialog to be closed (actually the ok button to be pressed so i can read out the data from the textfield), than analyse what the user has entered and based on that i will decide if the drop is rejected or allowed.
public void drop(DropTargetDropEvent e) {
try{
//popup
Popup p = new Popup();
p.setParmeter("enter a new name: ");
p.setVisible(true);
//programm wont wait before the user has pressed ok in the popup
System.out.println("value: " + p.getValue());
repaint();
} else {
e.rejectDrop();
}
}
I hope you get the idea. Popup is a dialog extended from a JFrame. The problem is, that p.getValue() is executed before the User gets to press the ok button. I tried using a boolean variable and a loop to check if something was entered in the popup but it doesnt work, the dialog is desplayed but there is not textfield or ok button, so the only thing i can do is to kill it. I'm pretty new to gui's so i really would appreciate the help. Thanks in advance.
If possible you should re-implement Popup to inherit from JDialog instead of JFrame, and call JDialog's setModal(true) method, which will prevent subsequent code from running until the dialog is dismissed.
Alternatively, check out the static convenience methods in JOptionPane, which eliminate the need to implement your own bespoke dialog class in many cases. For example (from the JOptionPane API):
Show an information panel with the options yes/no and message 'choose one':
JOptionPane.showConfirmDialog(null, "choose one", "choose one", JOptionPane.YES_NO_OPTION);
Java has built-in dialog support. Yon don't want to extend JFrame. See the tutorial on how to make dialogs.

Categories