Error message for empty textfield for a JCombo box - java

I have created a JComboBox in order to add players to a list as I am creating a game. I am trying to show an error message using JOptionPane if the text field is left empty I did this using the method below.
btnAddPlayer = new JButton("Add Player");
btnAddPlayer.addActionListener(new ActionListener() { //This is the layout for the list of points that are possible to achieve
public void actionPerformed(ActionEvent arg0) {
if (txtAddPlayer.equals("")){
JOptionPane.showMessageDialog(btnAddPlayer, this, "Please Enter Full Details", NumofAnswers);//THIS IS THE METHOD I TRIED
} else {
comboBox.addItem(txtAddPlayer.getText());
}
}
});
btnAddPlayer.setBounds(469, 243, 89, 23);
panel.add(btnAddPlayer);
txtAddPlayer = new JTextField();
txtAddPlayer.setBounds(373, 244, 86, 20);
panel.add(txtAddPlayer);
txtAddPlayer.setColumns(10);
I am not sure why this is not working. Please provide an answer using my code.
Regards,

Should be
If (textField.gettext().equals(""))

Related

jpanel.add(component) doesnt work when inside an actionListener

I am currently still learning this spell called swing so i wrote this code
lblWarning = new JLabel("<html>Incorrect Username or Password<br/> please try again!</html>");
lblWarning.setBounds(10,121,220,48);
lblWarning.setForeground(new Color(150, 0, 0));
lblWarning.setBackground(new Color(255, 255, 255));
lblWarning.setFont(new Font("Tahoma", Font.BOLD, 12));
JButton btnNewButton_1 = new JButton("Confirm");
btnNewButton_1.setFont(new Font("Microsoft JhengHei", Font.BOLD, 14));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(txtUsername.getText()!="user" && txtPassword.getText()!="pass") {
contentPane.add(lblWarning);
}else {
}
}
});
btnNewButton_1.setBounds(10, 180, 94, 23);
contentPane.add(btnNewButton_1);
txtusername and txtpassword are text fields btw. but the problem is contentPane (jpanel) doesnt add the label "lblWarning" when the conditions are true but works and shows fine when its outside the actionListener, whats the problem ?
How do you know your "if condition" is ever true? Did you do basic debugging by adding a System.out.println(...) statement to verify you are executing the code inside the statement?
Don't use "==" or "!=" to compare a String. Instead use the String.equals(...) method.
After you add a component to a visible frame you need to also invoke panel.revalidate(), to invoke the layout manager so the component is given a size/location.

How to store and display user input in JList?

I don't know what I am doing wrong. I am trying to take a JTextField user input to be stored and displayed in a JList, but every time the button is pressed to store the user input the JList remains blank. Any help would be greatly appreciated.
DefaultListModel<String> model = new DefaultListModel<String>();
menuList = new JList<String>(model);
menuList.setBounds(500, 65, 300, 400);
menuList.setSelectionBackground(Color.LIGHT_GRAY);
menuList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
btnCreateMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
childFrame = new JFrame("New Menu");
childFrame.setBounds(340, 300, 400, 200);
childFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
childFrame.getContentPane().setLayout(null);
childFrame.setVisible(true);
lblNewMenu = new JLabel("Menu Name:");
lblNewMenu.setBounds(30, 60, 200, 20);
childFrame.getContentPane().add(lblNewMenu);
input = new JTextField();
String userInput = input.getText();
input.setBounds(lblNewMenu.getX() + 80, lblNewMenu.getY(), 250, 30);
childFrame.getContentPane().add(input);
btnMenuInput = new JButton("Create New Menu");
btnMenuInput.setBounds(120, 100, 200, 30);
btnMenuInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
model.addElement(userInput);
menuList.setModel(model);
childFrame.setVisible(false);
Entree selectedEntree = (Entree)cboEntrees.getSelectedItem();
Side selectedSide = (Side)cboSides.getSelectedItem();
Salad selectedSalad = (Salad)cboSalads.getSelectedItem();
Dessert selectedDessert = (Dessert)cboDesserts.getSelectedItem();
Menu menu = new Menu(userInput, selectedEntree, selectedSide, selectedSalad, selectedDessert);
menuArray.add(menu);
}
});
childFrame.getContentPane().add(btnMenuInput);
}
});
mainframe.setVisible(true);
This line
userInput = input.getText();
needs to be called first in the ActionListener. Otherwise you never get the latest String from the text field.
e.g.,
public void actionPerformed(ActionEvent e){
userInput = input.getText();
model.addElement(userInput);
//menuList.setModel(model); // not needed
Also, as mentioned by camickr in comment, avoid using null layouts and setBounds as this fights against the Swing GUI library rather than working with it, making it much harder to create flexible easy to update and edit GUI's.
Also, the childFrame top-level window should be a JDialog and not a second JFrame. Please see The Use of Multiple JFrames: Good or Bad Practice? for more on this.
Also note that you should create the entire dialog or Frame before you make it visible, or else some of the items may not be visible at first.
Another problem is the use of JFrame.HIDE_ON_CLOSE. You should probably be using DISPOSE_ON_CLOSE instead. Otherwise the frame will just be hidden, but will still exist, possibly for the life of the program.

Passing the name to the action

I am new to coding and I am trying my best, but I am trying to get the gui to submit a name and then have a pop-window say "Your name is:" I know I am missing something obvious, so please be easy on me.
public class Frame1 extends JFrame {
private JPanel panel;
private JTextField NametextField;
public Frame1() {
setTitle("Confirm Name");
getContentPane().setLayout(null);
JLabel lblEnterName = new JLabel("Enter Name:");
lblEnterName.setBounds(10, 22, 83, 14);
getContentPane().add(lblEnterName);
NametextField = new JTextField();
NametextField.setBounds(10, 47, 274, 20);
getContentPane().add(NametextField);
NametextField.setColumns(10);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new Frame2());
panel = new JPanel();
add(panel);
setVisible(true);
btnNewButton.setBounds(20, 78, 89, 23);
getContentPane().add(btnNewButton);
}
private class Frame2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (actionCommand.contains(getName())); {
JOptionPane.showInputDialog("Your name is: " + NametextField );
}
}
public static void main(String[] args) {
}
JOptionPane.showInputDialog("Your name is: " + NametextField );
You're basically saying "Your name is this text field object". You'll want to use the getText() method of the text field to get the actual text
NametextField.getText()
Note, if (actionCommand.contains(getName())) looks very suspect to me. I'm not sure this is what you want, though I have no idea what getName() returns. I think you want to check if the action command equals the action command of the button you want to check for. In which case you want if ("Submit.equals(actionCommand))
Also note, as pointed out by #Takendarkk , the ; after your parenthesis is negating the if statement, causing the action to be performed, whether or not the if statement is true.
Also note, as pointed out by #MadProgrammer, stay away from the null layout. Learn to use LayoutManagers, and let them do the sizing and positioning for you. See more at Laying out Components Withing a Container
Also note, you should be following Java naming convention. variable names begin with lower case letters, using camel casing: NametextField → nameTextField

Java - Get var information from another JDialog

I've got a JDialog with a textField and a button. If I press the button and the textField is empty, it prints an error message. But now I want to open a new Window (JDialog I guess) with the information of the textField.
{
JButton aceptarButton = new JButton("Aceptar");
aceptarButton.setBounds(332, 387, 86, 23);
contentPanel.add(aceptarButton);
aceptarButton.setFont(new Font("Tahoma", Font.PLAIN, 11));
aceptarButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ArticuloDAO dao = new ArticuloDAO();
Articulo a = new Articulo();
if (nombreField.getText().equals("")) {
System.out.println("Nombre");
}else{
String nombre = nombreField.getText();
a.setNombre(nombre);
dao.insert(a);
Success s = new Success();
s.setVisible(true);
setVisible(false);
}
}
});
aceptarButton.setActionCommand("OK");
getRootPane().setDefaultButton(aceptarButton);
}
A new window saying "Name is missing" should open whenever I click OK and the textField nombreField is empty. How is it?
You can simply use JOptionPane for this. Just call it like so:
JOptionPane.showMessageDialog(this, "Name is missing");
It will display the message in a dialog box and wait for OK.
To show a popup messages from any kind you can use the class JOptionPane and their static methods. in your case JOptionPane.showMessageDialog(null, "Name is missing"); should do the thing.

Java Window Duplication Prevention

JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
RegisterStudent panel_1 = new RegisterStudent();
panel_1.setVisible(true);
}
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);
Is there a way, that IF one specific window is open already, it cant be opened once again?
Because, i don't want the user to click on a button several times, causing several windows to be opened with the same content?
Create the panel_1 variable outside of the mouse listener block and initialize it to null. When the mouse is clicked, check if panel_1 is null, and if it is, create it.
final RegisterStudent panel_1 = new RegisterStudent();
JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
panel_1.setVisible(true);
}
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);
You can get an array of all open windows from Window.getWindows() since 1.6 or all open Frames with Frame.getFrames() since 1.2. You can use the name property or the window class (RegisterStudent) to test if the windows is already open and set the focus on it instead open another one.

Categories