So I'm trying to get the same result, according to this picture:
I'm trying to make the bottom 2 look like the upper 2.
So the first problem is that I don't get the java icon in the title.
The second problem is that "Some text:" isn't lined with the input box.
Here is my code:
public static void main(String[] args) {
String input = JOptionPane.showInputDialog(null, "Some Text:", "Dialog",
JOptionPane.PLAIN_MESSAGE);
if(input != null)
JOptionPane.showMessageDialog(null, "Value entered: " + input, "Message box", JOptionPane.INFORMATION_MESSAGE);
else
System.exit(0);
}
we can add Swing Component to JOptionPane. So why not creating a custom panel containing a JLabel and JTextFeild with layout i.e., FlowLayout and add that panel to JOptionPane using
JOptionPane.showConfirmDialog
(
frame, // main window frame
customPanel, // custom panel containing the label and textFeild
"My Panel with Text Feild", // Title
JOptionPane.OK_CANCEL_OPTION, // with OK and CANCEL button
JOptionPane.PLAIN_MESSAGE
);
A minimal working example:
import java.awt.event.*;
import javax.swing.*;
class CustomPanel extends JPanel
{
JLabel lab;
JTextField txtField;
public CustomPanel() {
lab = new JLabel("Some Text: ");
txtField = new JTextField(20);
add(lab);
add(txtField);
}
public String getText()
{
return txtField.getText();
}
}
public class JOptionPaneDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CustomPanel inputPane = new CustomPanel();
int value = JOptionPane.showConfirmDialog(null, inputPane, "Demo" ,JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if(value == JOptionPane.OK_OPTION)
{
JOptionPane.showMessageDialog(null, "Value Entered: "+inputPane.getText(), "Demo", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
}
Tutorial resource: How to make Dialogue
Related
what do I have to add to the code below so that the user has to enter a specific word i.e. "London" to open the JOptionPane input dialog box.
JFrame frame = new JFrame("JTextField");
JTextField textfield = new JTextField(30);
frame.add(textfield);
At the moment I can type in anything in the text field and the dialog box will appear. I only want it to open if the user enters a specific word.
I'm using the action event with action listener and action performed to open the JOptionPane Dialog box.
public class Test9 {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField");
JTextField textfield = new JTextField(30);
frame.add(textfield);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,200);
JPanel panel = new JPanel();
frame.add(panel);
panel.add(textfield);
textfield.addActionListener(new Action4());
}
}
You can do something like this.
if(museum_name.equals("London")){
JOptionPane.showMessageDialog(null, " You are attending the " + museum_name);
} else{
// show the error message
}
Its encouraged to use equals() method for String comparison. Please note, equals() is used to compare two strings for equality, while operator == compares the reference of an object in java.
Update
To show an error message if the input is not "London", you can do something like this.
static class Action4 implements ActionListener {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String museum_name = ((JTextField) e.getSource()).getText();
if (museum_name.equals("London")) {
JOptionPane.showMessageDialog(null, "You are attending the " + museum_name);
} else {
JOptionPane.showMessageDialog(null, "Wrong input!");
}
}
}
I can not seem to get this to work. My assignment will only let us use JTextAreas.
The issue with my code is that I can not read it text in the TextArea. The goal is to run the logic after the user types in ENTER after they type in their input.
When I run the code I can only type in one character.. and the the GUI presents the character after a zero for reasons I can not figure out. Ex: [0b ] will be in the TextArea. Please help I can't figure this out.
public class ArabicToRomanGUI extends JFrame
{
private static final long serialVersionUID = 1L;
private JTextArea enterRomanNumber = new JTextArea();
JLabel label = new JLabel();
JPanel panel = new JPanel();
JFrame frame = new JFrame();
//TestArea contructor adds jtextArea to jframe
public ArabicToRomanGUI()
{
super("Convert a Roman Numeral");
setLayout(new FlowLayout());
//Text field to enter a roman numeral
enterRomanNumber = new JTextArea(1,25);
enterRomanNumber.setText("Delete this text and Enter a Roman Numerial Here!");
//enterRomanNumber.setAlignmentX(0);
//enterRomanNumber.setAlignmentY(0);
add(enterRomanNumber);
HandlerForTextArea handler = new HandlerForTextArea();
enterRomanNumber.addKeyListener(handler);
}
private class HandlerForTextArea implements KeyListener
{
//used to process text field events
#Override
public void keyTyped(KeyEvent e)
{
String userInput = "";
userInput = enterRomanNumber.getText();
userInput = userInput.toUpperCase();
ConversionLogic.ConvertFromRomanToArabic(userInput); //converts user string of Roman numerals to an int in arabic
String arabicNumberAsString = ConversionLogic.getConvertedRomanNumeral();
enterRomanNumber.setText(arabicNumberAsString);
//user pressed enter in JTextField enterNumberField
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
//enterRomanNumber.setText(arabicNumberAsString);
if (ConversionLogic.getCheckFail() == true)
{
JOptionPane.showMessageDialog(frame, "The Roman Numeral entered is Invalid", "Error", JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(frame, "The arabic equivalent is " + arabicNumberAsString + "." , "Conversion Successful", JOptionPane.PLAIN_MESSAGE);
}
}
}
#Override
public void keyPressed(KeyEvent e) {
//not used
}
#Override
public void keyReleased(KeyEvent e) {
//not used
}
}//end inner class TextFieldHandler
}//end class ArabicToRomainGUI
As you'll read time and time again on this site -- don't use a KeyListener with a text component such as a JTextArea as this can mess up the functioning of the text component. Instead use a DocumentListener for when you wish to detect changes to the state of the JTextArea after it happens, or a DocumentFilter if you wish to detect (and possibly change) changes to the text component before it is posted to the text component.
I see that you're using a JTextArea(1, 25), or a single-line JTextArea, which makes me ask: why not use a JTextField? If you do this and want to trap the ENTER key press, then you can simply add an ActionListener to the JTextField.
Hello I have a problem with my comboBox. In app that im making my panel has a combo box with two choices and a button next to the combo box to proceed to the choice selected in the combo box but instead both if Statements run and no I have no idea why.
Combo box code is simple private JComboBox mainChoice = new JComboBox();
mainChoice.addItem("") etc...
class mainPanelGoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String choice = (String)mainChoice.getSelectedItem();
System.out.printf(choice);
if(choice == "View Passenger Details");
{
JTextField first = new JTextField();
JTextField last = new JTextField();
Object[] message = {
"First Name:", first,
"Last Name:", last
};
int option = JOptionPane.showConfirmDialog(null, message, "Enter passenger name", JOptionPane.PLAIN_MESSAGE);
if (option == JOptionPane.OK_OPTION)
{
// Load passenger data
p = dataHandler.getPassengerData(first.getText(), last.getText());
if(p != null)
{
updateTextfields( p);
// Display passenger data
getContentPane().removeAll();
getContentPane().add(passengerDetailsPanel);
setSize(400,340);
setLocationRelativeTo(null);
validate();
repaint();
printAll(getGraphics());
}
}
}
if(choice == "Add New Passenger")
{
if(displayPassengerInputForm());
{
// Display passenger data
getContentPane().removeAll();
getContentPane().add(passengerDetailsPanel);
setSize(400,340);
setLocationRelativeTo(null);
validate();
repaint();
printAll(getGraphics());
}
}
}
}
// EXAMPLE OF MY PROGRAM THAT RETURNS BOTH WINDOW A and WINDOW B
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame extends JFrame
{
private JPanel mainPanel = new JPanel();
private JComboBox<String> mainChoice = new JComboBox<String>();
private JButton goButton = new JButton("GO");
public Frame()
{
createMainPanel();
this.add(mainPanel);
}
private void createMainPanel()
{
// Fill choice box
mainChoice.addItem("Find Passenger");
mainChoice.addItem("Add New Passenger");
// Set button
goButton.addActionListener(new mainPanelGoButtonListener());
goButton.setPreferredSize(new Dimension(5,5));
// Add to main panel
mainPanel.setLayout(new GridLayout(1,2,4,4));
mainPanel.add(mainChoice);
mainPanel.add(goButton);
}
class mainPanelGoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(mainChoice.getSelectedItem().equals("Find Passenger"));
{
// DISPLAYS WINDOW FOR INPUT
System.out.printf(" WINDOW A ");
}
if(mainChoice.getSelectedItem().equals("Add New Passenger"));
{
// DISPLAYS WINDOW FOR INPUT
System.out.printf(" WINDOW B ");
}
}
}
public static void main(String args[])
{
Frame frame = new Frame();
frame.setTitle("SSD Project");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(400,50);
frame.setVisible(true);
}
}
Each time I press a button it prints out both Window A and Window B instead of one
One problem I see is that you use == to compare Strings.
Don't use == to compare Strings as this compares if two String objects are the same, something that you are not interested in testing. Use the equals(...) or equalsIgnoreCase(...) method which tests if two Strings contain the same characters, in the same order, with or without the same case respectively, and this is what you are really interested in.
Next: be sure you use if (something) { xxxx } else if (somethingElse) { xxxx } to be sure that only one if block gets performed.
Next: look up the CardLayout which will allow your GUI to change views much more cleanly.
Edit
You ask:
do you mean: mainChoice.getSelectedItem().equals("Add New Passenger") ?? cause im still getting the same result ;
Yes, exactly. But on further reflection, your code above cannot be causing both if blocks to fire as the String == can't be true for both test Strings. Something else is causing your problem.
could you give me some quick example?
Actually it would be better if you could create and post a minimal runnable program that reproduces your problem for us.
I'm writing a Text Analysis Program for college that requires you to add a word to a dictionary as well as other actions. I'm having a problem with this section of the code as I need an error message to come up if the user hits ok while the JTextField is empty. I can get it going but have created an infinite loop somehow with the error message. Please help, I've looked all over the internet but can't find an answer for such a simple bug. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.lang.Character;
public class TAPtest implements ActionListener
{
private JFrame tap = new JFrame("Text Analysis");
private JMenuBar tapMenu = new JMenuBar();
private JMenu dictionary = new JMenu("Dictionary");
private JMenuItem addWord = new JMenuItem("Add Word");
private JFrame frameAdd = new JFrame("Add Word");
private JLabel add = new JLabel("Enter word to add:");
private JButton okNewWord = new JButton("Ok");
private JButton cancelNewWord = new JButton("Cancel");
private JTextField inputNewWord = new JTextField(28);
private JPanel westAdd = new JPanel();
private JPanel eastAdd = new JPanel();
private JPanel southAdd = new JPanel();
private Vector <String> dictionaryVector = new Vector<String>();
public TAPtest() //Constructor. Contains TAP GUI.
{
tap.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tap.setSize(350, 100);
tap.setLocation(700, 500);
tap.setResizable(false);
tap.setJMenuBar(tapMenu);
tapMenu.add(dictionary);
dictionary.add(addWord);
addWord.addActionListener(this);
tap.setVisible(true);
}
public void actionPerformed(ActionEvent event) //All actions performed.
{
if (event.getActionCommand() == "Add Word") addNewDicWordGUI();
if (event.getSource() == okNewWord) addNewDicWord();
if (event.getSource() == cancelNewWord) frameAdd.dispose();
}
public void addNewDicWordGUI()
{
frameAdd.setSize(350, 150);
frameAdd.setLocation(700, 500);
frameAdd.setResizable(false);
okNewWord.setSize(5,20);
cancelNewWord.setSize(5,20);
westAdd.add(add);
eastAdd.setLayout(new GridLayout(2,1));
eastAdd.add(okNewWord);
eastAdd.add(cancelNewWord);
southAdd.add(inputNewWord);
frameAdd.add(westAdd, BorderLayout.WEST);
frameAdd.add(eastAdd, BorderLayout.EAST);
frameAdd.add(southAdd, BorderLayout.SOUTH);
okNewWord.addActionListener(this);
cancelNewWord.addActionListener(this);
inputNewWord.addActionListener(this);
frameAdd.setVisible(true);
}
public void addNewDicWord()
{
String inputNew = inputNewWord.getText(); //Get JTextField value.
inputNew = inputNew.toLowerCase();
frameAdd.dispose();
if (inputNew.equals(""))
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice", 1);
else {
boolean addItemFound = dictionaryVector.contains(inputNew); //True if contains.
if(addItemFound) //If true.
JOptionPane.showMessageDialog(null, inputNew + " already exists in the dictionary.", "Word Already Exists", 1);
else { //If not true.
dictionaryVector.addElement(inputNew); //Add the word to the dictionary Vector.
Collections.sort(dictionaryVector); //Sort the vector in ascending order.
JOptionPane.showMessageDialog(null, inputNew + " was added to the dictionary.", "Word Added", 1);
}
inputNewWord.setText(null);
}
}
public static void main(String [] args)
{
TAPtest program = new TAPtest();
}
}
private Vector <String> dictionaryVector = new Vector<String>();
inputNewWord.setText(null);
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice", 1);
public void actionPerformed(ActionEvent event) //All actions performed.
{
...
}
should better be
private SortedSet<String> dictionaryVector = new TreeSet<String>();
inputNewWord.setText("");
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice",
JOptionPane.ERROR_MESSAGE);
public void actionPerformed(ActionEvent event) //All actions performed.
{
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
...
}
}
}
The last invokeLater might have caused the troubles. The event handling actionPerformed is done on the event thread, and showing a message should be done after
the event is handled (as any longer task for the GUI to remain responsive).
Declare frameAdd like this -
private JFrame frameAdd = null;
The addNewDicWordGUI() method should be like this -
public void addNewDicWordGUI()
{
if(frameAdd==null)
{
//Initialized only for the first time
frameAdd = new JFrame("Add Word");
frameAdd.setSize(350, 150);
frameAdd.setLocation(100, 200);
frameAdd.setResizable(false);
okNewWord.setSize(5,20);
cancelNewWord.setSize(5,20);
westAdd.add(add);
eastAdd.setLayout(new GridLayout(2,1));
eastAdd.add(okNewWord);
eastAdd.add(cancelNewWord);
southAdd.add(inputNewWord);
frameAdd.add(westAdd, BorderLayout.WEST);
frameAdd.add(eastAdd, BorderLayout.EAST);
frameAdd.add(southAdd, BorderLayout.SOUTH);
okNewWord.addActionListener(this);
cancelNewWord.addActionListener(this);
inputNewWord.addActionListener(this);
}
frameAdd.setVisible(true);
}
Make the above changes and it will work fine.
I have a dialog for a client-GUI that asks for the IP and Port of the server one wants to connect to. I have everything else, but how would I make it so that when the user clicks "OK" on my dialog box, that it runs something? Here's what I have so far:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class ClientDialog {
JTextField ip = new JTextField(20);
JTextField port = new JTextField(20);
GUI gui = new GUI();
Client client = new Client();
JOptionPane optionPane;
public void CreateDialog(){
Object msg[] = {"IP: ", ip, "\nPort: ", port};
optionPane = new JOptionPane();
optionPane.setMessage(msg);
optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = optionPane.createDialog(null, "Connect to a server");
dialog.setVisible(true);
if(dialog == JOptionPane.OK_OPTION){
System.out.println(ip);
String ipMsg = ip.getText();
int portMsg = Integer.parseInt(port.getText());
gui.CreateConsole(client, ipMsg, portMsg);
}
}
} //End class
I know that the code isn't correct, but what I want is that when the user hits "OK" on the dialog, I can run some code. Thanks!
I'd suggest to use showConfirmDialog instead
int result = JOptionPane.showConfirmDialog(myParent, "Narrative",
"Title", JOptionPane.INFORMATION_MESSAGE);
and there you can test for various returns value from JDialog/JOptionPane
if (result == JOptionPane.OK_OPTION,
JOptionPane.CANCEL_OPTION,
JOptionPane.CLOSED_OPTION, etc..
I'd suggest creating a JPanel and using JOptionpane.showConfirmDialog() (or even JOptionPane.showOptionDialog() to display the dialog and retrieve the option. Here's a modification of your code as an example:
import java.awt.*;
import javax.swing.*;
class ClientDialog {
private JTextField ip = new JTextField(20);
private JTextField port = new JTextField(20);
private JOptionPane optionPane;
private JPanel panel;
public void CreateDialog(){
panel = new JPanel(new GridLayout(2, 2));
panel.add(new JLabel("IP"));
panel.add(ip);
panel.add(new JLabel("Port"));
panel.add(port);
int option = JOptionPane.showConfirmDialog(null, panel, "Client Dialog", JOptionPane.DEFAULT_OPTION);
if (option == JOptionPane.OK_OPTION) {
System.out.println("OK!"); // do something
}
}
}
public class Test {
public static void main(String args[])
{
ClientDialog c = new ClientDialog();
c.CreateDialog();
}
}
Damn, took too long to post. Anyway just design the layout of the JPanel as you would for any other sort of frame.
Please understand that the 2nd parameter in a JOptionPane, the object parameter, can be any Swing component including a JPanel that holds a simple or complex GUI.
Consider creating a JPanel, placing a few components in it including JLabels and two JTextFields, one for IP, one for port, and then displaying this JPanel in a JOptionPane. Then you can easily check if OK has been pressed and act accordingly.
import javax.swing.*;
public class OptionEg {
public static void main(String[] args) {
final JTextField ipField = new JTextField(10);
final JTextField portField = new JTextField(10);
JPanel panel = new JPanel();
panel.add(new JLabel("IP:"));
panel.add(ipField);
panel.add(Box.createHorizontalStrut(15));
panel.add(new JLabel("Port:"));
panel.add(portField);
int result = JOptionPane.showConfirmDialog(null, panel,
"Enter Information", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("IP: " + ipField.getText());
System.out.println("Port: " + portField.getText());
}
}
}
Good solutions.
If you want not to use something else, this is a working example:
1) set DO_NOTHING_ON_CLOSE to ensure user MUST press OK
2) verify if the JDialog is still visible.
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setModal(false);
dialog.setVisible(true);
dialog.setAlwaysOnTop(true);
while(dialog.isVisible())try{Thread.sleep(50);}
catch(InterruptedException e){}
This can be a solution if you want to implement a non-modal dialog box.