简体   繁体   English

Java Swing 标签重叠

[英]Java Swing Label Overlapping

public class Solution{

    public static void main(String[] args){

        MyGraphic frame = new MyGraphic();
        frame.setComponents();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
    }
}
class MyGraphic extends JFrame implements ActionListener{

    JButton b;
    JTextField t;
    JLabel l;
    public MyGraphic(String s){

        super(s);
    }
    public MyGraphic(){

        super();
    }
    public void setComponents(){

        b = new JButton("Action");
        t = new JTextField();
        l = new JLabel("Name");
        this.setLayout(null);
        l.setBounds(30, 50, 50, 20);
        t.setBounds(100, 50, 150, 20);
        b.setBounds(100, 100, 70, 20);
        this.add(b);
        this.add(t);
        this.add(l);
        b.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e){

        String name = t.getText();
        JLabel label = new JLabel("Your name is "+name);
        label.setBounds(50, 150, 200, 30);
        this.add(label);
    }
}

image link图片链接
In this image link name are overlapping.在此图像中,链接名称重叠。 First, I entered "Sagar Tanwar" then I entered "Sumit Kumar" and these name are overlapping.首先,我输入“Sagar Tanwar”,然后输入“Sumit Kumar”,这些名称重叠。 Please tell me, How to remove previous entered Label.请告诉我,如何删除以前输入的标签。 You can check image using this image link.您可以使用此图片链接查看图片。

You should heed the advice in the comments to your question.您应该注意对您的问题的评论中的建议。 Nonetheless, the simplest way to fix your problem, using the code you have already written, is to make label a member of class MyGraphic rather than a local variable in method actionPerformed() , ie尽管如此,使用您已经编写的代码解决问题的最简单方法是使label成为类MyGraphic的成员,而不是方法actionPerformed()的局部变量,即

class MyGraphic extends JFrame implements ActionListener{
    JLabel label;
    // Rest of the class code

Then, in method actionPerformed() simply set the text of the label .然后,在方法actionPerformed()简单地设置label的文本。

public void actionPerformed(ActionEvent e) {
    if (label == null) {
        label = new JLabel();
        label.setBounds(50, 150, 200, 30);
        this.add(label);
    }
    String name = t.getText();
    label.setText("Your name is "+name);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM