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
120 views
in Technique[技术] by (71.8m points)

java - Overlay Swing Text Label as Text is Entered

Various forms in my program use JTables for which I've been able to use a Key Listener to select a row as the user types. This works great but I would like to provide some feedback to the user to show what text is being entered.

I've tried creating frame/labels but can't get them to show correctly.

My basic thoughts were - create the frame (if it doesn't already exist), create the label and set the text. Eg:

private void showSearchLabel(String search) {
    if (null == searchTextFrame) {
        searchTextFrame = new JFrame("searchTextFrame");
        searchTextFrame.setBackground(new Color(0, 0, 0, 0));
        searchTextFrame.setUndecorated(true);
        searchTextFrame.setAlwaysOnTop(true);

        searchTextFrame.getContentPane().setLayout(new java.awt.BorderLayout());
        searchTextLabel = new JLabel();
        searchTextFrame.getContentPane().add(searchTextLabel);
        searchTextFrame.pack();
        searchTextFrame.setVisible(true);
    }

    searchTextLabel.setText(search);

}

showSearchLabel is called by a Key Listener which adds the most recent key press to the search string. Backspace clears the string (and removes the frame/label). Enter key selects the item in the table and should also remove the frame/label.

What am I missing?

EDIT: Clarification - using the code above, nothing shows at all.

If I set the text when creating the label, the first character is visible (which is to be expected as at that point, the user has only typed one character). Calling .setText(search) after this point, the text is not updated. Note - this is visible in the very top/left hand corner of the screen, which is not really where I want it (ideally, would like it to show within the JTable).

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A new JLabel() has "an empty string for the title." It's preferred size is zero. You can

  • Add the required space in the constructor.

    searchTextLabel = new JLabel("        ");
    
  • Invoke pack() on the enclosing frame, after the call to setVisible().

    f.setVisible(true);
    …
    searchTextFrame.pack();
    
  • Add a single space in the constructor, to establish the height, and invoke validate() on the enclosing Container.

    searchTextLabel = new JLabel(" ");
    …
    f.setVisible(true);
    …
    searchTextLabel.setText(search);
    searchTextLabel.validate();
    

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

...