Default Java Swing Standard

I am learning Java and Swing right now and am trying to develop simple programs for educational purposes.

So here is the question.

I have gridlayout and fields in my frame with default text

accNumberField = new JTextField("0", 10); accNumberField.addFocusListener(new FocusListener() { int focusCounter = 0; @Override public void focusGained(FocusEvent arg0) { // TODO Auto-generated method stub if (focusCounter > 0) accNumberField.setText(""); focusCounter++; } 

What I want is that when the user first clicks on the field, the default text disappears. So I add a focus listener and use accNumberField.setText (""); in focusGained method.

But the problem is that for the first field by default in my frame, the focus becomes right during the creation of the frame. And the default text disappears from the very beginning. I used a counter, as you can see. But this is not what I wanted.

I want no field to get focus during creation, and each field can get focus from the moment the user clicks on one of them.

Sorry if I wrote something wrong. English is not my native language.

+4
source share
2 answers

A stream was found with the code for an example of the desired Java JTextField functionality with an input hint . Precisely you need to provide your own implementation of JTextField , which will contain the "default text" in a specially created field for this.

For your second question, you can focus on some button or frame .

+2
source

Is there a reason you are using focusListener ()? why not use mouseListener () as it should?

  accNumberField.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { accNumberField.setText(""); } }); 

if you want to clear the text for the first click, you can simply use a boolean:

  //outside constructor private boolean isTextCleared = false; //in constructor accNumberField.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { if (!isTextCleared) { accNumberField.setText(""); isTextCleared = true; } } }); 
+2
source

Source: https://habr.com/ru/post/1435220/


All Articles