如何在 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);
}
}結果
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP