最上面的一个是带有图像的JLabel。我想要里面的JTextfield。
我想重叠一个JLabel和JTextField,但是即时通讯有各种各样的问题。我正在使用Netbeans。我怎样才能做到这一点?请帮忙。
最佳答案
您可以创建一个提供以下功能的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
相同的高度,或者将该逻辑添加到构造函数中。关于java - 重叠JTextField和JLabel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35255780/