【问题标题】:Overlapping JTextField and JLabel重叠 JTextField 和 JLabel
【发布时间】:2016-05-17 07:08:06
【问题描述】:

顶部是带有图像的 JLabel。我想要里面的 JTextfield。

我想重叠 JLabel 和 JTextField 但我遇到了各种各样的问题。我正在使用 Netbeans。我怎样才能做到这一点?请帮忙。

【问题讨论】:

  • 用你的JFrame试试AbsoluteLayout
  • 您是否要实现水印,即出现在文本字段中以提示用户输入的文本? Something like this

标签: java netbeans jlabel jtextfield


【解决方案1】:

您可以创建一个提供此功能的 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 具有相同的高度,或者将该逻辑添加到构造函数中。

【讨论】:

    猜你喜欢
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 2011-07-07
    • 2013-10-04
    • 2019-11-04
    相关资源
    最近更新 更多