如何在 Java 中實現一個圓角的 JTextField?


JTextField JTextComponent 類的子類,它是最重要的元件之一,允許使用者以 單行格式輸入文字值。當我們嘗試在 JTextField 類中輸入一些內容時,它會生成一個 ActionListener 介面。JTextField 類的重要方法有 setText()、getText()、 setEnabled() 等等。預設情況下,一個 JTextfield 是一個矩形形狀,我們還可以使用 RoundRectangle2D 類實現一個 圓形 JTextField,需要重寫 paintComponent() 方法。

示例

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class RoundedJTextFieldTest extends JFrame {
   private JTextField tf;
   public RoundedJTextFieldTest() {
      setTitle("RoundedJTextField Test");
      setLayout(new BorderLayout());
      tf = new RoundedJTextField(15);
      add(tf, BorderLayout.NORTH);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new RoundedJTextFieldTest();
   }
}
// implement a round-shaped JTextField
class RoundedJTextField extends JTextField {
   private Shape shape;
   public RoundedJTextField(int size) {
   super(size);
   setOpaque(false);
}
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);
   }
}

結果

更新於: 2020-02-10

2K+ 瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始吧
廣告