我有这个简单的 JPanel 子类:
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SearchTextField extends JPanel
{
private ImageIcon image;
private JTextField textField;
SearchTextField ()
{
this.setLayout(new FlowLayout());
image = new ImageIcon ("img/search.png");
textField = new JTextField ("test");
JLabel label = new JLabel(image);
this.add(label,FlowLayout.LEFT);
this.add(textField, FlowLayout.CENTER);
this.setPreferredSize(new Dimension (250,50));
textField.setPreferredSize(new Dimension (this.getWidth() - 50, this.getHeight()));
}
}
问题是this.getWidth()
JPanel 和 JTextArea 上的方法都返回 0。似乎组件尚未初始化。您对修复它有任何想法吗?谢谢!