Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 둥근 JTextField를 어떻게 구현할 수 있습니까?


JTextField JTextComponent 의 하위 클래스입니다. 클래스이며 사용자가 한 줄 형식으로 텍스트 값을 입력할 수 있도록 하는 가장 중요한 구성 요소 중 하나입니다. . JTextField 클래스는 ActionListener 를 생성합니다. 인터페이스 내부에 일부 입력을 입력하려고 할 때. JTextField 클래스의 중요한 메소드는 setText(), getText(), setEnabled() 등. 기본적으로 JTextfield는 직사각형 모양을 가지며 둥근 모양의 JTextField RoundRectangle2D 를 사용하여 클래스 및 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);
   }
}

출력

Java에서 둥근 JTextField를 어떻게 구현할 수 있습니까?