Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào chúng ta có thể triển khai một JTextField tròn trong Java?


A JTextField là một lớp con của JTextComponent và nó là một trong những thành phần quan trọng nhất cho phép người dùng nhập giá trị văn bản đầu vào ở định dạng một dòng . Lớp JTextField sẽ tạo ActionListener giao diện khi chúng tôi cố gắng nhập một số đầu vào bên trong nó. Các phương thức quan trọng của lớp JTextField là setText (), getText (), setEnabled () và v.v. Theo mặc định, trường JText có hình chữ nhật, chúng tôi cũng có thể triển khai hình tròn JTextField bằng cách sử dụng RoundRectangle2D và cần ghi đè paintComponent () phương pháp.

Ví dụ

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);
   }
}

Đầu ra

Làm thế nào chúng ta có thể triển khai một JTextField tròn trong Java?