java - 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”,这些名称是重叠的。请告诉我,如何删除以前输入的标签。您可以使用此图像链接检查图像。
解决方案
您应该注意对您的问题的评论中的建议。尽管如此,使用您已经编写的代码解决问题的最简单方法是在方法中创建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);
}
推荐阅读
- c++ - C++中的输出流
- javascript - 如何将点表示法中的字符串转换为具有值的嵌套对象?
- objective-c - Objective-C 连续控制循环
- flutter - 我在向容器添加文本时遇到问题
- c++ - glfw 未定义的标识符
- python - 根据字符串匹配的熊猫子集行
- javascript - 如何在特定键之前返回数组中的所有数组项
- python - 使用带有列表理解的条件
- javascript - 尝试加载 LESS CSS 库时出现 GET ERR_FILE_NOT_FOUND 错误
- r - 将 scale_x_continuous 与 labeller 函数一起使用,该函数也将数据框作为参数以及默认中断