Hot questions for Using JTextField in mouselistener

Top Java Programmings / JTextField / mouselistener

Question:

I am trying to make a cheat code button for my game, and the displaying of it is all fine but I cannot correctly get the contents of this text field. This is the code for it:

cheats.addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
            Class.console("DISPLAYED OPTIONPANE");
            JOptionPane.showInputDialog(cheatCode, "Enter Code Here");

            Class.console("GOT STRING" + cheatCode.getText());
            if(cheatCode.getText().equals("testin")) {
                Class.console("testout");
            }
        }

I'm pretty much a beginner at this, so help? I can post everything else if needed.

P.S. Class.console() is a thing in my driver class. It's basically a shortened version of System.out.println()


Answer:

The showInputDialog() method returns the value that was entered by the user. You should capture it into a variable. For example, do this:

String userInputString = JOptionPane.showInputDialog("Enter Code Here");

The variable userInputString will be a string containing the value that you're looking for.

Question:

I am trying to get a JTextField to show over a JButton when I click the button. I have that working, but when I click out of the button it still stays visible. I'm using a MouseListener event so once I exit the button I want JTextField to become transparent again, but it stays visible.

My code:

import java.awt.EventQueue;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseEvent;


public class magicalJtextField extends JFrame implements MouseListener{

private JPanel contentPane;
private JTextField textField;


public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                magicalJtextField frame = new magicalJtextField();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}


public magicalJtextField() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);


    textField = new JTextField();
    textField.setBounds(78, 78, 89, 30);
    contentPane.add(textField);
    textField.setColumns(10);

    JButton button = new JButton("");
    //button transparent
//      button.setOpaque(false);
//      button.setContentAreaFilled(false);
//      button.setBorderPainted(false);
    button.setBounds(78, 78, 89, 23);
    button.addMouseListener(this);
    contentPane.add(button);

    textField.setVisible(false);

}
public void mouseEntered(MouseEvent e) 
{
//button.setText("Mouse Entered");
//button.setBackground(Color.CYAN);
//  textField.setVisible(true);
}

public void mouseExited(MouseEvent e) 
{
    textField.setVisible(false);    
}   
public void mouseClicked(MouseEvent e) 
{
    textField.setVisible(true);
}
public void mousePressed(MouseEvent e) 
{
    textField.setVisible(true);
}   
public void mouseReleased(MouseEvent e)
{
    textField.setVisible(true);
}
}

Answer:

I suggest a CardLayout for the Jbutton-JTextField magic trick (edit: I actually saw the recommendations in the comments only after I posted because it was so obvious and on an answer). Pressing the button will switch the card and then exiting the text field area with the mouse will switch it again.

public class Example extends JPanel {

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.add(new Example());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        });
    }

    public Example() {

        CardLayout cards = new CardLayout(5, 5);
        JPanel panel = new JPanel(cards);

        JButton button = new JButton("");
        JTextField textField = new JTextField(10);

        button.addActionListener(e -> {
            cards.next(panel);
            textField.requestFocusInWindow();
        });

        textField.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseExited(MouseEvent e) {

                cards.next(panel);
            }
        });

        panel.add(button);
        panel.add(textField);

        add(panel);
    }
}

As you were told by Andrew Thompson, don't use null layouts and don't specify bounds. Use a proper layout manager to do this for you.

Question:

I'm doing some error checking in two JTextFields. I'll label them jtext1 and jtext2.

Right now my GUI looks like this:

Enter number 1: [      ] // jtext1
Enter number 2: [      ] // jtext2
Convert         [ answer ]

I want to be able to check for multiple conditions and display an error message. For example, if the user enters nothing for both text fields, and hits convert the following should appear:

Enter number 1: [  Nothing entered    ] // jtext1
Enter number 2: [  Nothing entered    ] // jtext2
Convert         [ answer ]

And, if you use the mouse to click on jtext1 I want it to clear the message so the user can enter a number. If they click on jtext2 the same thing should also happen.

So for example if I were to click on jtext2 the following should appear:

Enter number 1: [  Nothing entered    ] // jtext1
Enter number 2: [        ]              // jtext2
Convert         [ answer ]

The problem is, with this piece of code:

if(!jtext1.isvalid()) {
    jtext1.setText("Nothing entered");
    jtext1.addMouseListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e) {
            jtext1.setText("");
        }
    });
}

if(!jtext2.isvalid()) {
    jtext2.setText("Nothing entered");
    jtext2.addMouseListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e) {
            jtext2.setText("");
        }
    });
}

Only jtext1 will work. This sort of makes sense to me, because I don't think I can keep overriding the same function, but how would I go around the issue?


Answer:

I think it would be better if you create another class that can display a hint, that way it will be easier whenever you need to do this again. Here's an example of how it could work, taken from another question on SO

class HintTextField extends JTextField implements FocusListener {

  private final String hint;
  private boolean showingHint;

  public HintTextField(final String hint) {
    super(hint);
    this.hint = hint;
    this.showingHint = true;
    super.addFocusListener(this);
  }

  @Override
  public void focusGained(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText("");
      showingHint = false;
    }
  }
  @Override
  public void focusLost(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText(hint);
      showingHint = true;
    }
  }

  @Override
  public String getText() {
    return showingHint ? "" : super.getText();
  }
}

You can use this and then set your JTextField to new HintTextField("What you want your hint to be"). You can modify this class for your own needs, but it's a good starting point.

Update: And if you want to use your current code for whatever reason, change the mouse listener to a focus listener and override focusGained.

Question:

I'm trying to make a program that when the user clicks the box the message will clear up. (Must be 6-15 characters) This thing will clear up when it will be clicked, I Tried using a mouse listener but it doesn't go when i click it.

Here's a snippet of the code :

    abc = new JTextField(" (Must be 6-15 characters)");         
    abc.setBounds(40,130,310,30);
    abc.setFont(new Font("Lucida Grande", Font.ITALIC, 14));
    abc.setForeground(Color.gray);                          
    abc.addMouseListener(new MouseAdapter() {
     public void mouseClicked(MouseEvent e) {
        abc.setText("");
      }
    });
    mainPanel.add(abc);

Answer:

Code looks good. Be sure to @Override the mouseClicked method and declare abc as final.

    final JTextField abc = new JTextField(" (Must be 6-15 characters)");         
    abc.setBounds(40,130,310,30);
    abc.setFont(new Font("Lucida Grande", Font.ITALIC, 14));
    abc.setForeground(Color.gray);                          
    abc.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            abc.setText("");
        }
    });
    mainPanel.add(abc);