창 크기를 조정할 때 내 사용자 정의 JTextField 크기가 변경됩니다. 이 작업은 창 크기를 처음 조정할 때 한 번만 수행됩니다. 그것은 paintComponent
내부에이 라인에 관련이 :Java Swing JTextField setMargin 예기치 않은 동작
setMargin(new Insets(2, 25, 2, 2));
내가 창 크기를 조정 할 때까지 텍스트 필드의 크기를 조정하지 않는 명령을 실행합니다. 창 크기를 조정하면 해당 명령을 실행하면 JTextField가 더 커집니다. 창의 실제 크기는 중요하지 않습니다. 처음으로 창 크기가 변경되면 JTextField가 커지고 시간이 끝날 때까지 JTextField가 크게 유지됩니다. 나는 프로그램을 시작하자마자 필드가 크다면 좋을 것이고, 분명히 크기를 무작위로 바꿀 필요는 없다.
무작위로 변경되지 않도록이 JTextField의 크기를 수정하려면 어떻게해야합니까?
가 여기에 전체 클래스 : 당신이 paintComponent
방법으로부터 코드를 잘라 생성자에 붙여 넣을 경우 의견 또한
/**
* From https://gmigdos.wordpress.com/2010/03/30/java-a-custom-jtextfield-for-searching/
* @author Georgios Migdos <[email protected]> */
public class JIconTextField extends JTextField {
private Icon icon;
private Insets dummyInsets;
public JIconTextField(int columns) throws IOException {
super(columns);
Border border = UIManager.getBorder("TextField.border");
JTextField dummy = new JTextField();
this.dummyInsets = border.getBorderInsets(dummy);
String path = "find-16x16.png";
InputStream is = Main.class.getClassLoader().getResourceAsStream(path);
setIcon(new ImageIcon(ImageIO.read(is)));
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int textX = 2;
if(this.icon!=null){
int iconWidth = icon.getIconWidth();
int iconHeight = icon.getIconHeight();
int x = dummyInsets.left + 5;//this is our icon's x
textX = x+iconWidth+2; //this is the x where text should start
int y = (this.getHeight() - iconHeight)/2;
icon.paintIcon(this, g, x, y);
}
setMargin(new Insets(2, textX, 2, 2));
}
}
왜 paintComponent 메서드 내에서 여백을 설정하고 있습니까? 이것은 가장 특이하고 매우 개략적으로 보입니다. –
코드 원본은 OP의 URL에 있습니다. 왜 그가 그렇게했는지 나는 모른다. 나는 텍스트 필드 위에 아이콘을 그리는 방법에 대해 인터넷 검색을 할 때 그것을 보았습니다. –
그래서 ** 정확하게 ** 당신이 성취하려고 노력하고 있습니까? 관찰 된 코드 동작과 반대되는 원하는 코드 동작은 무엇입니까? –