If Statements based on selection from dropdown - java

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.

Related

Why are my JOptionPane message dialogs popping up behind the console window?

I'm making a somewhat simple text game for my cs course. The majority of the game is played out in the console window, however, at a certain if the user wins or loses the game, a JOptionPane message dialog window shows up and says that the user has won or lost
My problem is that the JOptionPane is showing up on the layer the furthest back of all my other windows and applications open. In all my other programs like this, it has always appeared in the front.
I've found a temporary fix for this however I was wondering if anyone could give me a definitive reason as to why this may be happening to avoid the problem in the future
I'm not exactly sure why exactly this happens but for anyone who finds this in the future, this is why I was having this problem.
In my program, I had certain sections that used input from the console window (so scanners) and then displayed JOptionPanes based off of certain requirements of the game (i.e winning losing, etc).
For whatever reason, whenever you are taking user input from the scanner class then opening a JOptionPane, the JOptionPane will always open in the furthest section back from all your open tabs which is what was happening to me.
As a workaround for this bug, I did the following:
Declare a JDialog and setAlwaysOnTop to true:
final JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
Every time I made a JOptionPane open, instead of writing null as the first parameter I put the name of the JDialog so it looked something like this:
final JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(dialog, "You win!);
With this, my JOptionPanes always popped up in front of the console even when using the scanner class.

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

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.

How do I extend Javas JFrame to replicate WinForms' ShowDialog (.Net Framework)?

I have written an application in Java that has a JFrame with options. I now want a certain action to be executed when the user has confirmed the dialog with "Ok". I was recommended to add a return value to JFrame.
Unfortunately, I don't have any experience and need some help. Here are the details.
I want to extend JFrame so that I can have an Enum "DialogResult" when closing a JFrame like in the .Net Framework. Well, the Enum is no problem. My problem is to replicate the ShowDialog method from WinForms of the .Net Framework working in Java for the class JFrame.
Below is an example code in C#:
// DlgOptions : Form
DlgOptions dlg = new DlgOptions();
if(dlg.ShowDialog() == DialogResult.Ok)
{
// do something only when "Ok" was clicked
}
Here's a link from MSDN with the behavior I want to replicate:
https://msdn.microsoft.com/de-de/library/c7ykbedk(v=vs.110).aspx
How can I best implement this? Thanks in advance.
EDIT:
I changed my DlgOptions class so it doesn't extend JFrame but JDialog. I also added an enumeration DialogResult and added a public property of this type in my DlgOptions. But I still have a problem. When I use this code:
// executed when user clicked a JMenuItem in a JMenuBar
DlgOptions dlg = new DlgOptions();
dlg.setModal(true);
dlg.setVisible(true);
if(dlg.DialogResult == DialogResult.OK)
{
// do something
}
the program continues running before the user closed the modal dialog. What can I do?
EDIT 2:
My JDialog contains two JButtons; one to confirm changes that were made and one to abort changing the preferences for the program. I have several JCheckBoxes the user can check or uncheck.
So a JOptionPane would not be what I want / need (as far as I know). That's why I need a modal JDialog. But my Java code above doesn't work as I want it to. I read on a German website of a Java book that a JDialog set to modal with
setModal(true);
would cause the program to wait until the dialog is closed. The problem is, that the code continues too early.

How to open a new Window after y close a first one?

I'm working in this program in this the user is asked, for different types of data, but each type of data depends of the previous ones. So I created three frames, in which I place the first quiz, and now what I want is to open a new window, when the user press a button (Next) which at the same time close the first one. What I've tried so far is to change a Boolean variable when the user press that button (Next), however, I don't know how to make reference to this last variable from a new class. I'm putting the trouble in context because may you can give me a better approach tho solve this.
Opening and closing windows isn't complicated and involves nothing more than creating the window instances (such as a JFrame or JDialog) and calling setVisible(true) or setVisible(false) on them. But having said that, how many commercial applications do you use where windows are thrown willy nilly at the user? Few because it's a user interface nightmare. Instead do your user's a favor and swap views with a CardLayout, and for the instance where you occasionally need to get information modally ,use a modal dialog such as a JDialog set to modal or a JOptionPane.
I think you can do it by typing these lines in (Next) button's ActionListener method:
dispose();
NewJFrame n = NweJFrame();
n.setVisible(true);
The line dispose(); will close your previous window and your another new window suppose named NewJFrame will be opened by this two line
NewJFrame n = NweJFrame();
n.setVisible(true);
But before that you must have to write the code of NewJFrame as you have written for your previous window.
this code was only half successfull.
Form2 f2 = new Form2();
if (f2 is Form2)
{
f2.Show();
this.Close();
}
else
{
Form1 f1 = new Form1();
f1.Show();
}

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