Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swing - Java - placeholder on textfield

I'm trying to create a GUI with Swing. My problem is, I have a textfield, but I want it to have a "placeholder" (like in html). I read here and there that it can be done by overriding the paint() of the textfield.

Since my code is generated I found out that I need to use the "Custom Creation Code" to override the code that was generated.

Here is what I have put in the "Custom Creation Code" field

new javax.swing.JTextField()
{
    String test = super.getText();
    String hint = "Username";

    public void paint(Graphics g)
    {
        if ( test == null || test.length() < 1 ) {
            g.setColor( Color.red );
            g.drawString(hint, 0, 0);
        }

        g.setColor(Color.BLACK);
        super.paint(g);
    }
}

This generates the following output

javax.swing.JTextField username = new javax.swing.JTextField()
{
    String test = super.getText();
    String hint = "Username";

    public void paint(Graphics g)
    {
        if ( test == null || test.length() < 1 ) {
            g.setColor( Color.red );
            g.drawString(hint, 0, 0);
        }

        g.setColor(Color.BLACK);
        super.paint(g);
    }
};

For now I see the textField but there is nothing in it, maybe I need to add some function onto some event, but I am not sure.

I would be grateful if anyone could lend a hand.

EDIT : Here is a demo of what I want to do : http://davidwalsh.name/demo/html5-placeholder.php

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I use to override the text fields paint method, until I ended up with more custom text fields then I really wanted...

Then I found this prompt API which is simple to use and doesn't require you to extend any components. It also has a nice "buddy" API

This has now been included in the SwingLabs, SwingX library which makes it even eaiser to use...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...