2011-12-15 240 views
3

当我这样做:的Java Swing圆角边框的JTextField

LineBorder lineBorder =new LineBorder(Color.white, 8, true); 
jTextField2.setBorder(lineBorder); 

我得到这样的结果,如:

enter image description here

我怎样才能具有圆形边框无方角可见,文本半切?

非常感谢。

问候

+2

-1,你一个几个星期前问这个问题:http://stackoverflow.com/questions/8305460/java-swing-jtextfield-inset/8305672 #8305672 – camickr 2011-12-15 16:29:57

+0

@camickr谢谢,没有承认重复 - 将投票关闭此.. – kleopatra 2011-12-15 16:58:20

回答

12

您可以覆盖JTextFiled建立自己的圆角JTextField。您必须覆盖它的方法paintComponent()paintBorder()和方法。您需要将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); 
1

非常相似,@Harry Joy的答案 - 只是去充分的距离,为outlined in a recent answer

  • 定义边框类型,露出一个形状
  • 意识到可能形边框组件
  • 如果检测到形状边界,接管背景画中的paintComponent形状(无需触摸的paintBorder)
0

这将修改您在整个应用程序

创建任何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); 
    } 
}