How to enter a specific word in a textfield - java

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!");
}
}
}

Related

Adding values in JTextFields in real time in Java GUI

I am writing a Java GUI program. I have two JTextFields:
'txtNet' and 'txtExcise'. I want values in these two textfields added as soon as I enter them and populate the result in another textfield 'txtTotal' without using a button.
I want values in these two textfields added as soon as I enter them
and populate the result in another textfield 'txtTotal' without using
a button.
This can be done using a DocumentListener on the JTextField's.
Here is a tutorial that covers the basics on how to use them: How to Write a Document Listener
Important extract from tutorial:
Document events occur when the content of a document changes in any
way
This will allow you to monitor changes on the textfield values and react accordingly. For your case this would involve checking the values of the 2 inputs and provided both are valid, displaying the result in the output textfield
Here is a quick SSCCE (Stack overflow glossary of acronyms):
public class AutoCalculationDemo {
public static void main(String[] args) {
JTextField firstInput = new JTextField();
JTextField secondInput = new JTextField();
JTextField output = new JTextField();
output.setEditable(false);
DocumentListener additionListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
attemptAddition();
}
#Override
public void removeUpdate(DocumentEvent e) {
attemptAddition();
}
#Override
public void changedUpdate(DocumentEvent e) {
attemptAddition();
}
public void attemptAddition(){
try{
double firstValue = Double.parseDouble(firstInput.getText());
double secondValue = Double.parseDouble(secondInput.getText());
output.setText(String.valueOf(firstValue + secondValue));
}catch (NumberFormatException nfe){
System.out.println("Invalid number(s) provided");
}
}
};
firstInput.getDocument().addDocumentListener(additionListener);
secondInput.getDocument().addDocumentListener(additionListener);
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(new JLabel("First number: "));
panel.add(firstInput);
panel.add(new JLabel("Second number: "));
panel.add(secondInput);
panel.add(new JLabel("Output: "));
panel.add(output);
frame.add(panel);
frame.setSize(250,150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

JTextArea won't read in text properly

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.

Button ActionListener runs both combo box choices at the same time why?

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.

How do I add the java icon and lineup text with input?

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

Problems aligning text field input using GridLayout

I want to make a form using java frame. I have two fields Name and Age. After entering the details, when the button is clicked, the entered data must be displayed as shown below, but I am not sure how to align it.
The entered data are:
FirstName: abcd
LastName: efg
This is what I have so far:
import java.awt.*;
import java.awt.event.*;
public class DataEntry {
public static void main(String[] args) {
Frame frm=new Frame("DataEntry frame");
Label lbl = new Label("Please fill this blank:");
frm.add(lbl);
frm.setSize(350,200);
frm.setVisible(true);
frm.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Panel p = new Panel();
Panel p1 = new Panel();
Label jFirstName = new Label("First Name");
TextField lFirstName = new TextField(20);
Label jLastName =new Label("Last Name");
TextField lLastName=new TextField(20);
p.setLayout(new GridLayout(3,1));
p.add(jFirstName);
p.add(lFirstName);
p.add(jLastName);
p.add(lLastName);
Button Submit=new Button("Submit");
p.add(Submit);
p1.add(p);
frm.add(p1,BorderLayout.NORTH);
}
}
Firstly, you need to add an event to the button, when it is clicked.
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Add the code to output the relevant details.
}
}
Then it's up to you to add the relevant code to the method body.
You should read the Documentation
Add a listener to your "Submit" button:
Submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myLabelForShowingTheOutput.setText("<html><body>Name: " + lFirstName + "<br>Last name: " + lLastName + "</body></html>");
}
});
Note that "myLabelForShowingTheOutput" is the JLabel you want to print. The text to print is basic HTML, so the label can show multiple lines. Other way to do it without HTML would be create a JLabel for the name and another for the age. Note as well that I did put the last name in the output, because there isn't an obvious JTextField for the age.
Remember, as well, that variables should start their name in lower case, so Submit would be "submit".

Categories