繁体   English   中英

带有圆角的JTextField保留阴影

[英]JTextField with rounded corner preserving shadows

我需要一个圆角文本字段,我在这里找到解决方案的问题是,使用这个解决方案,我失去了所有标准的JTextField阴影。

有谁知道如何恢复它们?

您不能简单地替换原始文本字段边框而不会丢失阴影。 您必须使用自己的阴影效果应用某些特定边框,甚至修改UI以便在场周围绘制阴影。

以下是textfield的类似阴影的UI的简单示例:

public static class RoundedFieldUI extends BasicTextFieldUI
{
    private int round = 5;
    private int shadeWidth = 2;
    private int textSpacing = 3;

    public void installUI ( JComponent c )
    {
        super.installUI ( c );

        c.setOpaque ( false );

        int s = shadeWidth + 1 + textSpacing;
        c.setBorder ( BorderFactory.createEmptyBorder ( s, s, s, s ) );
    }

    protected void paintSafely ( Graphics g )
    {
        Graphics2D g2d = ( Graphics2D ) g;
        g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON );

        Shape border = getBorderShape ();

        Stroke os = g2d.getStroke ();
        g2d.setStroke ( new BasicStroke ( shadeWidth * 2 ) );
        g2d.setPaint ( Color.LIGHT_GRAY );
        g2d.draw ( border );
        g2d.setStroke ( os );

        g2d.setPaint ( Color.WHITE );
        g2d.fill ( border );

        g2d.setPaint ( Color.BLACK );
        g2d.draw ( border );

        super.paintSafely ( g );
    }

    private Shape getBorderShape ()
    {
        JTextComponent component = getComponent ();
        if ( round > 0 )
        {
            return new RoundRectangle2D.Double ( shadeWidth, shadeWidth,
                    component.getWidth () - shadeWidth * 2 - 1,
                    component.getHeight () - shadeWidth * 2 - 1, round * 2, round * 2 );
        }
        else
        {
            return new Rectangle2D.Double ( shadeWidth, shadeWidth,
                    component.getWidth () - shadeWidth * 2 - 1,
                    component.getHeight () - shadeWidth * 2 - 1 );
        }
    }

    public static void main ( String[] args )
    {
        JFrame frame = new JFrame ();

        JPanel panel = new JPanel ( new BorderLayout ( 5, 5 ) );
        panel.setBorder ( BorderFactory.createEmptyBorder ( 50, 50, 50, 50 ) );
        frame.add ( panel );

        panel.add ( new JLabel ( "Field:" ), BorderLayout.NORTH );

        JTextField field = new JTextField ( 20 );
        field.setUI ( new RoundedFieldUI () );
        panel.add ( field );

        frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
        frame.pack ();
        frame.setLocationRelativeTo ( null );
        frame.setVisible ( true );
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM