Custom renderer on a JTextField. Is it possible ?

送分小仙女□ 提交于 2019-12-12 02:46:22

问题


I need to create component that looks like JTextField (same borders, shadows, rounded corners etc) but for displaying some graphic with text.

Is it possible to create something like renderer for a JTextField? Or Create custom component based on JPanel, but how to force it to looks same as JTextField

Another complication is that application will be running on different LAF's changed on the fly.

Do you have any ideas ?


回答1:


No, Swing does not provide any DefaultTextFieldRenderer or TextFieldRendere interface you can build on top of. You mention you like L&F aware rendering; thats already part of the answer: you would have to implement a UI for each L&F to render graphics into a TextField - this may be feasible for a selected few (lets say Windows/Mac/Metal), but hardly for any L&F that a user may want to use (if you leave them a choice).

Let me guess, you have the requirement to display some sort of status/validation icon with the field. Do the next best thing and display that as an icon next to the field, not in the TextField itself. Much less trouble :)




回答2:


Use a JTextPane or JEditorPane that can handle styled text (with embedded icons). See How to Use Editor Panes and Text Panes for more details.


Update

I need to create custom component that looks as JTextField in diferent Look and Feels, Using JTextPane or JEditorPane will change the borders shading and component.

Really? This next screenshot shows all 3. Which is which?

(No cheating by looking at the code 1st.)

As to the PLAF. Show me a PLAF in which there is any visible distinction between them.

import java.awt.*;
import javax.swing.*;

class DistinguishThese {

    public void initGui() {
        JPanel gui = new JPanel(new GridLayout(3,0,2,2));

        gui.add(new JTextField(5));
        gui.add(new JScrollPane(new JEditorPane()));
        gui.add(new JScrollPane(new JTextPane()));

        JOptionPane.showMessageDialog(null, gui);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                DistinguishThese dt = new DistinguishThese();
                dt.initGui();
            }
        });
    }
}


来源:https://stackoverflow.com/questions/8896310/custom-renderer-on-a-jtextfield-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!