1
頂部是一個帶圖像的JLabel。我想要JTextfield在裏面。重疊JTextField和JLabel
我想重複一個JLabel和JTextField中,但即時通訊都有點問題。我正在使用Netbeans。我怎樣才能做到這一點?請幫忙。
頂部是一個帶圖像的JLabel。我想要JTextfield在裏面。重疊JTextField和JLabel
我想重複一個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
的高度相同,或者將該邏輯添加到構造函數中。
用'JFrame'嘗試'AbsoluteLayout'。 –
您是否試圖獲得水印,即顯示在您的文本字段中以提示用戶輸入的文本? [類似這樣](http://stackoverflow.com/questions/1805486/adding-a-watermark-to-an-empty-jcombobox) – River
謝謝你工作:) –