首页 > 解决方案 > Java Swing 标签重叠

问题描述

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);
    }
}

图片链接
在此图片中,链接名称是重叠的。首先,我输入“Sagar Tanwar”,然后输入“Sumit Kumar”,这些名称是重叠的。请告诉我,如何删除以前输入的标签。您可以使用此图像链接检查图像。

标签: javaswing

解决方案


您应该注意对您的问题的评论中的建议。尽管如此,使用您已经编写的代码解决问题的最简单方法是在方法中创建label类成员MyGraphic而不是局部变量actionPerformed(),即

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

然后,在方法中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);
}

推荐阅读