Snehasish
Snehasish

Reputation: 1073

Displaying a TextField on user interaction

I want to display a TextField only when user has entered a value in Input field

Here is my code:

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class PlayingAround {

    JFrame frame;
    JTextField display;
    JTextField input;

    public static void main(String[] args) {
        PlayingAround obj = new PlayingAround();
        obj.create();
    }

    private void create() {
        frame = new JFrame();
        display = new JTextField();
        input = new JTextField();
        display.setEditable(false);
        display.setVisible(false);

        input.addKeyListener(new Listener());
        frame.add(BorderLayout.NORTH, display);
        frame.add(BorderLayout.SOUTH, input);

        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    class Listener implements KeyListener {

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            display.setVisible(true);
            display.setText(input.getText());
        }
    }
}

But my problem is that the Display JTextField doesn't becomes visible until there are some events like Resizing the Window, Minimizing and maximizing the Window.

I tried calling frame.repaint() in the keyReleased Method but even it has not helped.

Upvotes: 1

Views: 150

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You should call revalidate() and repaint() on the container that holds the JTextField after placing the text field component in the container. The revalidate() call sends a request to the container's layout managers to re-layout its components. The repaint() then requests that the JVM request of the paint manager to redraw the newly laid out container and its child components. The repaint() is not always needed but is usually a good idea.

Also, don't use a KeyListener for this, but rather a DocumentListener on the first text component's Document. This way, if the user empties the first text component, you can make the second text component disappear if desired. Also, text can be entered without key presses, and you want to allow for that.

Upvotes: 4

Related Questions