简体   繁体   中英

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. 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

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

Then, in method actionPerformed() simply set the text of the 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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