Jtextfield的Java Swing圆角边框
当我这样做时:Jtextfield的Java Swing圆角边框,java,swing,jtextfield,rounded-corners,Java,Swing,Jtextfield,Rounded Corners,当我这样做时: LineBorder lineBorder =new LineBorder(Color.white, 8, true); jTextField2.setBorder(lineBorder ); 我得到的结果如下: 我怎么能有圆形的边框,而没有可见的方形角和半切的文本 多谢各位 致以最诚挚的问候您可以覆盖JTextField构建您自己的圆角JTextField。您必须重写它的paintComponent()、paintBorder()和contains()方法。您需要将roun
LineBorder lineBorder =new LineBorder(Color.white, 8, true);
jTextField2.setBorder(lineBorder );
我得到的结果如下:
我怎么能有圆形的边框,而没有可见的方形角和半切的文本
多谢各位
致以最诚挚的问候您可以覆盖
JTextField
构建您自己的圆角JTextField
。您必须重写它的paintComponent()
、paintBorder()
和contains()
方法。您需要将roundRect绘制为文本字段的形状
例如:
public class RoundJTextField extends JTextField {
private Shape shape;
public RoundJTextField(int size) {
super(size);
setOpaque(false); // As suggested by @AVD in comment.
}
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
}
public boolean contains(int x, int y) {
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15);
}
return shape.contains(x, y);
}
}
要看到这一点,请执行以下操作:
JFrame frame = new JFrame("Rounded corner text filed demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new FlowLayout());
JTextField field = new RoundJTextField(15);
frame.add(field);
frame.setVisible(true);
与@Harry Joy的答案非常相似-只是走完全程,如图所示
- 定义显示形状的边框类型
- 使零部件了解可能形成的边框
- 如果检测到形状边界,则在形状内部的paintComponent中接管背景绘制(无需触摸paintBorder)
- 这里有一个简单的例子:
问候 这将修改您在整个应用程序中创建的任何JTextField 把它放在第一个窗口的开头,它会影响每个JTextField
UIManager.put("TextField.background", Color.WHITE);
UIManager.put("TextField.border", BorderFactory.createCompoundBorder(
new CustomeBorder(),
new EmptyBorder(new Insets(4,4,4,4))));
海关边境
@SuppressWarnings("serial")
public static class CustomeBorder extends AbstractBorder{
@Override
public void paintBorder(Component c, Graphics g, int x, int y,
int width, int height) {
super.paintBorder(c, g, x, y, width, height);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(COLOR_BORDE_SIMPLE);
Shape shape = new RoundRectangle2D.Float(0, 0, c.getWidth()-1, c.getHeight()-1,9, 9);
g2d.draw(shape);
}
}
-1、你在几周前问了这个问题:@camickr谢谢,不认识这个复制品-将投票关闭这个。。