Example text in JTextField

后端 未结 7 2066
独厮守ぢ
独厮守ぢ 2021-01-18 05:15

I am looking for a way to put example text into a swing JTextField and have it grayed out. The example text should then disappear as soon as any thing is entered into that t

相关标签:
7条回答
  • 2021-01-18 05:23

    The Text Prompt class provides the required functionality without using a custom JTextField.

    It allows you to specify a prompt that is displayed when the text field is empty. As soon as you type text the prompt is removed.

    The prompt is actually a JLabel so you can customize the font, foreground etc..:

    JTextField tf7 = new JTextField(10);
    TextPrompt tp7 = new TextPrompt("First Name", tf7);
    tp7.setForeground( Color.RED );
    
    0 讨论(0)
  • 2021-01-18 05:32
    private JLabel l;
    
    JPromptTextField(String prompt) {
        l = new JLabel(prompt, SwingConstants.CENTER);
        l.setForeground(Color.GRAY);
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
    
        if (this.getText().length() == 0) {
            // Reshape the label if needed, then paint
    
            final Rectangle mine = this.getBounds();
            final Rectangle its = l.getBounds(); 
            boolean resized = (mine.width != its.width) || (mine.height != its.height);
            boolean moved = (mine.x != its.x) || (mine.y != its.y);
            if (resized || moved)
                l.setBounds(mine);
    
            l.paint(g);
        }
    }
    
    0 讨论(0)
  • 2021-01-18 05:34

    How about initialize the text field with default text and give it a focus listener such that when focus is gained, if the text .equals the default text, call selectAll() on the JTextField.

    0 讨论(0)
  • 2021-01-18 05:41

    You can't do that with a plain text field, but you can put a disabled JLabel on top of the JTextField and hide it if the text field gets the focus.

    0 讨论(0)
  • 2021-01-18 05:46

    If you can use external librairies, the Swing components from Jide software have what you are looking for; it's called LabeledTextField (javadoc) and it's part of the JIDE Common Layer (Open Source Project) - which is free. It's doing what mklhmnn suggested.

    0 讨论(0)
  • 2021-01-18 05:46

    Rather than overriding, put a value in the field and add a KeyListener that would remove the value when a key stroke is registered. Maybe also have it change the foreground.

    You could wrap this up into your own custom JTextField class that would take the default text in a constructor.

    0 讨论(0)
提交回复
热议问题