gpt4 book ai didi

java - 带有圆角保留阴影的 JTextField

转载 作者:行者123 更新时间:2023-11-29 05:55:02 25 4
gpt4 key购买 nike

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

有谁知道如何恢复它们?

最佳答案

您不能在不丢失阴影的情况下简单地替换原始文本框边框。您将不得不应用一些具有您自己的类似阴影效果的特定边框,或者甚至修改 UI 以便它在字段周围绘制阴影。

这是一个简单的文本框类阴影 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 );
}
}

关于java - 带有圆角保留阴影的 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12513436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com