Multiple JOptionPane input dialogs? - java

I've been looking for the past hour, but I haven't been able to find the solution I am looking for.
I'm wanting to take multiple inputs from the user using JOptionPane, but I don't want them to all be in one dialog window. I'm wanting it to transition to the next or just make the next one pop up. Is there a way to do that using JOptionPane?
Here's what I have so far:
import java.util.Scanner;
import javax.swing.*;
public class HomeWork2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
int days, assignments;
double temperature;
boolean isRaining;
JOptionPane.showInputDialog("How many days are left?");
days = input.nextInt();
JOptionPane.showInputDialog("How many assignments are due?");
assignments = input2.nextInt();
JOptionPane.showInputDialog("What is the temperature outside?");
temperature = input3.nextDouble();
JOptionPane.showInputDialog("Is it raining today?");
isRaining = input4.nextBoolean();
if(assignments<=0)
JOptionPane.showMessageDialog(null, "Why are you asking in the first place?");
else
if(days<5)
JOptionPane.showMessageDialog(null, "You need to hurry up, time is short.");
else
if(assignments>4)
JOptionPane.showMessageDialog(null, "You need to hurry up before the assignments pile up. Oh wait...");
else
if(temperature<50)
JOptionPane.showMessageDialog(null, "You should start working, it's not like it's warm eoungh to do anything.");
else
if(isRaining==true)
JOptionPane.showMessageDialog(null, "It's raining, you might as well start on your assignments.");
else
JOptionPane.showMessageDialog(null, "It's nice out and you have some time to spare, go have fun.");
input.close();
input2.close();
input3.close();
input4.close();
}
}

Apart from my above recommendations, here are some others that will be needed to understand the below code (PLEASE READ THEM ALL BEFORE GOING FOR THE CODE PART ONLY)
Read what a layout manager is and how they work, especially take a look at Grid Layout and Box Layout, Google for examples and explanations if you don't understand the tutorial.
Read what methods are and how they work.
Read about the Event Dispatch Thread (EDT) and its function.
Be careful to not mix console application paradigm and GUI application paradigm. Use one or the other.
Learn How to use Dialogs
Read how to convert a String o a int and look how to convert to double.
For your boolean field I would use a JRadioButton including a ButtonGroup and how to get which radiobutton was selected in a buttongroup:
This code should give you a starting point on your way to finish it yourself
The annoyingGui while shorter, is not my favorite since it opens a new dialog for the user each time you want to get an imput from them, which is annoying.
The singleDialogInformation() displays a more complex GUI using a JPanel and GridLayout for requesting user information and a BoxLayout to show it back to the user, note that I'm not using 2 different variables, but reassigning the pane variable to a new instance of a JPanel with a different layout.
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class UsingDialogsExample {
private JFrame frame;
private JPanel pane;
private JTextField daysField;
private JTextField assignmentField;
private int days = 0;
private int assignments = 0;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//Comment / uncomment one of them to see the output related to each sample method.
// new UsingDialogsExample().annoyingGui();
new UsingDialogsExample().singleDialogInformation();
}
});
}
public void annoyingGui() {
frame = new JFrame("My Frame's Title");
String daysInput = JOptionPane.showInputDialog(frame, "How many days are left?"); //Get user input on the textfield as a String
String assignmentsInput = JOptionPane.showInputDialog(frame, "How many assignments are due?");
try {
days = Integer.parseInt(daysInput); //Convert the string gotten above to an int
assignments = Integer.parseInt(assignmentsInput);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
JOptionPane.showMessageDialog(frame, "The number of days left is: " + days);
JOptionPane.showMessageDialog(frame, "The number of assignments due is: " + assignments);
}
public void singleDialogInformation() {
pane = new JPanel();
pane.setLayout(new GridLayout(0, 2, 2, 2));
daysField = new JTextField(5);
assignmentField = new JTextField(5);
pane.add(new JLabel("How many days are left?"));
pane.add(daysField);
pane.add(new JLabel("How many assignments are due?"));
pane.add(assignmentField);
int option = JOptionPane.showConfirmDialog(frame, pane, "Please fill all the fields", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
String daysInput = daysField.getText();
String assignmentsInput = assignmentField.getText();
try {
days = Integer.parseInt(daysInput);
assignments = Integer.parseInt(assignmentsInput);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(new JLabel("Days left: " + days));
pane.add(new JLabel("Assignments due: " + assignments));
JOptionPane.showMessageDialog(frame, pane);
}
}
}
Screenshots of the annoyingGui:
Screenshots of the singleDialogInformation:

Related

Array input numbers 0-2 and output corresponding letters a,b,c

I have created the array with the elements ("A","B","C")
if the user enters ‘0’ output “A” to the outputlabel,e.g.,outputLabel.setText(array[0]).
I am just getting errors in the command prompt when i enter in the correct numbers. Any help with this would be highly appreciated. I have the gui created correctly. Just unsure about the array and outputs.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuiFrame extends JFrame implements ActionListener {
String[] stringArray = {"A", "B", "C"};
JTextField inputArea;
JLabel theOutputLabel;
public GuiFrame() {
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Please enter the index of the array to
output: ");
JLabel outputLabel = new JLabel("Array index");
JTextField userInput = new JTextField ();
JButton inputButton = new JButton("Go");
String inputFromUser = userInput.getText();
Container contentPane = getContentPane();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(label1);
panel.add(outputLabel);
panel.add(userInput);
panel.add(inputButton);
inputButton.addActionListener(this);
contentPane.add(panel);
setSize(250, 250);
setVisible(true);
userInput.setSize(250,50);
System.out.println(inputFromUser);
String stringArray[] = new String[3];
}
public static void main(String[] args){
new GuiFrame();
}
#Override
public void actionPerformed(ActionEvent e) {
String userInput = inputArea.getText();
try {
do {
if (e.getActionCommand().equals("0"))
theOutputLabel.setText(stringArray[0]);
if (e.getActionCommand().equals("1"))
theOutputLabel.setText(stringArray[1]);
if (e.getActionCommand().equals("2"))
theOutputLabel.setText(stringArray[2]);
}while(e.getActionCommand().equals("0") || e.getActionCommand().equals("1") || e.getActionCommand().equals("2"));
System.out.println("You have entered a number that is outside of the range of the array index please try again");
}
catch (ArrayIndexOutOfBoundsException arrayError){
System.out.println("Array Index Out of Bounds");
arrayError.printStackTrace();
}
}
}
What you have now defeats the purpose of using an array. Imagine you had to do it for all letters of the Alphabet, would you add 26 conditions? What if you have thousands of options?
Thererfore, instead of
/** DON'T DO THIS */
if (e.getActionCommand().equals("0"))
theOutputLabel.setText(stringArray[0]);
if (e.getActionCommand().equals("1"))
theOutputLabel.setText(stringArray[1]);
if (e.getActionCommand().equals("2"))
theOutputLabel.setText(stringArray[2]);
You should parse the input and get element from the array according to the index.
/** DO THIS */
int index = Integer.parseInt(e.getActionCommand());
theOutputLabel.setText(stringArray[index]);
Integer.parseInt() could throw a java.lang.NumberFormatException if the input is not a valid integer, so you have to add a catch for that.
If you want to have the index available for test in the while condition, then declare it without initializing before the do block.
Hey apart from what #isapir has suggested also please check that there are few places in your code that would result into NullPointerExceptions like :
JTextField inputArea; // Not assigned will lead to NPE
JLabel theOutputLabel; // Not assigned will lead to NPE
String userInput = inputArea.getText(); // Because of inputArea unassigned this line will throw NPE for sure so fix that as well.
So I'm assuming what exception you were getting in cmdPrompt would be NPE one so better fix your basic bug first and check your constructor code properly. Lastly, it's always better to share the exception details before post questions on SO.
e.getActionCommand().equals("0") this line will not give what you have entered in frame pop-up. Check this also instead use inputArea.getText() will give you user's entered number digit.

TroubleShooting JOptionPane error

I have a question I have a program where I want to test the users ability to remember a random list of colors. Based off if the users input is right or wrong it will ask for the next color.
So I got it all work up to where the user inputs the first color. Before it has the user input on the first color. The program is already assuming the user input is wrong, even tho it hasn't asked for any input.
I know from previously knowledge I could like flush the buffer, can you do that with JOptionPane?
Or is this another issue I'm not seeing?
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class Testing
{
//Intialization of the whole program for everything to pass information
public JFrame main;
public JLabel lbInsturctions;
public JLabel welcomeMessage;
public JLabel homeScreen;
public JLabel homeScreenColors;
public JTextField txtInput;
public int num = 1;
public String colorList = "";
public String[] color = {"red","green","blue","brown","yellow", "gold", "orange", "silver"};
public String[] solution = new String[5];
//sets up the window and random colors
public Testing ()
{
Random r = new Random();
for (int i = 0; i<solution.length; i++)
{
solution[i] = color[r.nextInt(7)];
colorList = Arrays.toString(solution);
}
JOptionPane.showMessageDialog(null, "Lets test your memory. Memorize these colors: " + colorList);
main = new JFrame ();
main.setSize (500,300);
main.setTitle ("Ultimate Colors");
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
main.setLayout(new FlowLayout());
intializeGame();
main.setVisible(true);
}
public void intializeGame ()
{
//All Intiazations
lbInsturctions = new JLabel();
homeScreen = new JLabel();
txtInput= new JTextField(null, 15);
//Need to delete or make new window if user pushes ok then
lbInsturctions.setText("Enter color number " + num + ":");
main.add(lbInsturctions);
main.add(txtInput);
txtInput.addActionListener(new colorTester());
}
public class colorTester implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//Need to delete or make new window if user pushes ok then
lbInsturctions.setText("Enter color number " + num + ":");
//grabs the users input to see if it is corect
String guess= "";
guess = txtInput.getText();
System.out.println(guess);
//Checks to see if the users input is the same as the initalizaton
if (color[num+1].equalsIgnoreCase(guess) || num > 6)
{
System.out.println("You got it!");
++num;
lbInsturctions.setText("Enter color number " + num + ":");
txtInput.setText("");
}
//if the User input is wrong
else
{
System.out.println("It's a good thing your not graded!");
txtInput.setVisible(false);
lbInsturctions.setText("It's a good thing this is not graded!");
}
if (num == 5)
{
lbInsturctions.setText("You memory is perfect good job!");
txtInput.setVisible(false);
}
}
}
}//end of program
This has nothing to do with flushing buffers.
You're getting user input here: guess = txtInput.getText(); which is in the intializeGame method. Meaning you're getting the text from the txtInput JTextField on its creation, before the user has had a chance to enter anything into the field. I think that you're used to programming linear console programs, where you get the user's input immediately, but that's not how event-driven GUI's work. Instead you must get and react to the user's input on event, here perhaps the ActionListener of some button. Perhaps your code needs a "submit" JButton or something similar, and in its ActionListener, extract the input from the JTextField and respond to it. Do this and your code has a better chance of working.
Other issues:
you don't ever appear to have added your txtInput JTextField into the GUI.
same for the homeScreen JLabel
Edit your new code posted at the bottom of your question has the same problem.

How do I use the information from an option pane in an if statement

I'm trying to figure out how to assign a name/title to the options used in an option pane so that I can use them in an if-statement. Here's the code I have so far:
int i = 0;
while(i<1){
JFrame frame = new JFrame();
String[] options = new String[2];
options[0] = new String("Peat");
options[1] = new String("Repeat");
JOptionPane.showOptionDialog(frame.getContentPane(),"Peat and Repeat were walking on a bridge\nPeat fell off, "
+ "who was left?","", 0,JOptionPane.INFORMATION_MESSAGE,null,options,null);
}
What would you recommend I do next to finish this "joke"?
I think what you mean by your question is how do you determine what option was selected by the user? JOptionPane.showOptionDialog returns the index of the selected option. So you can do something like:
import javax.swing.*;
public class Example {
public static void main(String[] args) {
String[] options = {"Peat", "Repeat"};
int selectedOption = JOptionPane.showOptionDialog(null,"Peat and Repeat were walking on a bridge\nPeat fell off, who was left?","", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,options,null);
if(selectedOption == 0) System.out.println("Peat selected");
else System.out.println("Repeat selected");
}
}
When the user selects "Peat" it will print "Peat selected".
When they selected "Repeat" it will print "Repeat selected"

Adding 2 Integers using AWT

I'm trying to create a Java AWT program with these codes:
import javax.swing.*;
import java.awt.*;
public class Exer1 extends JFrame {
public Exer1(){
super ("Addition");
JLabel add1 = new JLabel("Enter 1st Integer: ");
JTextField jtf1 = new JTextField(10);
JLabel add2 = new JLabel("Enter 2nd Integer: ");
JTextField jtf2 = new JTextField(10);
JButton calculate = new JButton("Calculate");
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(add1);
add(jtf1);
add(add2);
add(jtf2);
add(calculate);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] a){
Exer1 ex1 = new Exer1();
}
}
My problem is HOW to add these 2 integers using JTextField. Can someone help me? Thank you so much. :)
You need to use ActionListener on your JButton.
Then you need to get int's from JTextField's and sum them like next:
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
System.out.println("sum=" + (i1 + i2));
} catch (Exception e1){
e1.printStackTrace();
}
}
});
Generally, you should create an event listener for click events on your button: Lesson: Writing Event Listeners. In that handler, you would take contents of your two text fields, convert them to integers:
Integer i1 = Integer.valueOf(jtf1.getText());
Then you can add those two integers and display them in another control or do anything else with them.
Start with How to Use Buttons, Check Boxes, and Radio Buttons and
How to Write an Action Listeners
This will provide you with the information you need to be able to tell when the user presses the button.
JTextField#getText then return's String. The problem then becomes a problem of converting a String to a int, which if you take the time, there are thousands of examples demonstrating how to achieve that
Once you've played around with oddities of converting String to a int, you could take a look at How to Use Spinners and How to Use Formatted Text Fields which perform there own validation on the values been entered

Issues creating java GUI with while loop

I am creating a java GUI which is a fortune teller. The GUI will spit out one of twelve fortunes every time you click the "get my fortune" button, the strings will never repeat back to back, can can repeat later after other strings have gone before it. I have made already for the most part. But now I am having some trouble creating the while loops to display the strings without repeating. I have looked at my book which didn't really help. If you guys could point me in the right direction,it would be much appreciated. Thanks!
I entered all of the code so you can see the variables used. But my question starts at class RndButtonListener.
package FortuneTellerRunner;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
*
* #author a3cal_000
*/
class FortuneTellerFrame extends JFrame
{
final private JPanel mainPnl, titlePnl, displayPnl, buttonPnl, imagePnl;
final private JButton quitBtn, rndBtn;
final private JLabel titleLbl, iconLbl;
final private JTextArea displayTa;
final private JScrollPane scroller;
public String[] fortune = new String [12];
int newIndex, oldIndex;
private static final int HEIGHT = 250;
private static final int WIDTH = 450;
public FortuneTellerFrame()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPnl = new JPanel();
mainPnl.setLayout(new BorderLayout());
displayPnl = new JPanel();
buttonPnl = new JPanel();
titlePnl = new JPanel();
ImageIcon icon = new ImageIcon("FortuneTellerIcon.JPEG");
iconLbl = new JLabel(icon);
titleLbl = new JLabel("Fortune Teller!");
displayTa = new JTextArea();
imagePnl = new JPanel();
scroller = new JScrollPane();
// Create the layout of the title panel
titlePnl.setLayout(new GridLayout(2,1));
add(mainPnl);
// Set the label to the panel.
titlePnl.add(titleLbl);
titlePnl.add(iconLbl);
// add the panel to the main panel.
mainPnl.add(titlePnl, BorderLayout.NORTH);
mainPnl.add(scroller, BorderLayout.CENTER);
mainPnl.add(displayTa, BorderLayout.CENTER);
// Create the "Get my fortune button.
rndBtn = new JButton("Get My Fortune!");
quitBtn = new JButton("Quit");
// Add the buttons to the buttonPnl in grid layout.
buttonPnl.add(rndBtn);
buttonPnl.add(quitBtn);
// Create the grid layout for the button panel.
buttonPnl.setLayout( new GridLayout(1, 2));
// Add the button panel to the grid layout, South.
mainPnl.add(buttonPnl, BorderLayout.SOUTH);
ActionListener listener = new RndButtonListener();
rndBtn.addActionListener(listener);
quitBtn.addActionListener(listener);
}
class RndButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
fortune[0] = "He who throws dirt is losing ground.";
fortune[1] = "You will find the love of your life in food.";
fortune[2] = "Do or do not, there is no try.";
fortune[3] = "Tomorrow is a better day to try anything of importance.";
fortune[4] = "Life's not about how hard you can hit, but how hard you can get hit and keep moving forward.";
fortune[5] = "You can't be late until you show up.";
fortune[6] = "If you think things can't get worse it's probably only because you lack sufficent imagination.";
fortune[7] = "If youre at the top it means you have further to fall.";
fortune[8] = "Even in last place, youre still in the race.";
fortune[9] = "The road to riches is paved on the failures of others.";
fortune[10] = "If you feel like your going no where, get off the treadmill.";
fortune[11] = "Thinking about going to the gym is just as good as going.";
Random rnd = new Random(fortune.length);
do
{
newIndex = rnd.nextInt(fortune.length);
}
while(newIndex == oldIndex);
do
{
System.out.println(fortune[newIndex]);
displayTa.append(fortune[newIndex] + "||");
displayTa.updateUI();
mainPnl.updateUI();
oldIndex = newIndex;
}
while(newIndex != oldIndex);
class QuitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
System.exit(0);
}
}
}
}
}
The basic problem is you are re-creating the Random with the same seed each time, which is generally creating the same random sequence over and over again.
Instead try using...
do {
newIndex = (int) Math.round(Math.random() * (fortune.length - 1));
} while (newIndex == oldIndex);
You also don't need the second loop, it's just clutter that confuses the situation.
You may also find that...
displayTa.append(fortune[newIndex] + "\n");
produces nicer output (IMHO)
You may also wish to take a look at How to use Scroll Panes
Your program run fine, but this is a problem, fortune.length is a random seed which return me only 6 and 8 when I later called Random.nextInt().
Random rnd = new Random(fortune.length);
Do it this way
Random rnd = new Random();
and also consider the formatting solution given by MadProgrammer.
Random() gives you same number pattern. Try Random(System.currentTimeMillis()). It uses current time as seed, so you can get real random numbers.
I did something similar to this just today, so let's see if I can remember... I made an ArrayList of type int of how many items I had (fortunes)
ArrayList<Integer> fortuneSeq = new ArrayList<Integer>();
Then add in some numbers starting from 0 to code for the fortunes.
for(int i = 0; i < fortune.length; i++) {
fortuneSeq.add(i);
}
Then I used the shuffle() method from the Collections class to randomize the list.
Collections.shuffle(fortuneSeq);
After that, just loop through to access the fortunes.
for(int i = 0; i < fortune.length; i++) {
System.out.println(fortune[fortuneSeq.get(i)]);
//...
}
Edit: Silly autocorrect, you don't like programmers.
Edit: Fixed some furtunes instead of fortunes and fixed println statement.

Categories

Resources