您可以创建一个提供此功能的 JPanel:
public class JTextFieldWithIcon extends JPanel {
private JTextField jtextfield;
private ImageIcon image;
public JTextFieldWithIcon(ImageIcon imgIco, String defaultText) {
super();
this.image = imgIco;
setLayout(null);
this.jtextfield = new JTextField(defaultText);
jtextfield.setBorder(BorderFactory.createEmptyBorder());
jtextfield.setBackground(new Color(0, 0, 0, 0));
jtextfield.setBounds(50, 0, 286, 40);
add(jtextfield);
JLabel imageLbl = new JLabel();
imageLbl.setBounds(0, 0, 286, 40);
imageLbl.setIcon(imgIco);
add(imageLbl);
}
public Icon getIcon() {
return this.image;
}
public JTextField getJTextField() {
return this.jtextfield;
}
}
上面的代码产生了这个:
另一种方法是将图像排列在JTextField 的左侧。
import java.awt.BorderLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JTextFieldWithIcon extends JPanel {
private JTextField jtextfield;
private ImageIcon image;
public JTextFieldWithIcon(ImageIcon imgIco,String defaultText) {
super();
setLayout(new BorderLayout());
this.jtextfield = new JTextField(defaultText);
this.image = imgIco;
JLabel imageLbl = new JLabel();
imageLbl.setIcon(image);
add(imageLbl,BorderLayout.WEST);
add(jtextfield,BorderLayout.CENTER);
}
public Icon getIcon(){
return this.image;
}
public JTextField getJTextField(){
return this.jtextfield;
}
}
注意:ImageIcon 在上面的代码中不会自动缩放。您可能希望预先缩放ImageIcon 使其与JTextField 具有相同的高度,或者将该逻辑添加到构造函数中。