求助关于SWING组件按钮提交事件显示不同的标签
为什么下面的程序当文本输入1的时候提交按钮,不显示1号标签,也不显示2号标签呢
详细测试代码:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class TEST extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TEST frame = new TEST();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TEST() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
textField = new JTextField();
textField.setBounds(59, 38, 66, 21);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("提交");
btnNewButton.setBounds(201, 37, 93, 23);
contentPane.add(btnNewButton);
final JLabel lblNewLabel1 = new JLabel("1号");
lblNewLabel1.setBounds(59, 109, 54, 15);
// contentPane.add(lblNewLabel);
final JLabel lblNewLabel2 = new JLabel("2号");
lblNewLabel2.setBounds(218, 109, 54, 15);
// contentPane.add(lblNewLabel_1);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 文本框输入1加载标签1号显示,否则加载lable标签2号
if (textField.getText().equals("1")) {
System.out.println("进去");
contentPane.add(lblNewLabel1); // 显示1号标签
} else {
contentPane.add(lblNewLabel2); // 显示2号标签
}
}
});
}
}
------解决方案--------------------
建议,在TEST()中就将lblNewLabel1、lblNewLabel2加入,但不显示它们
而把事件处理改成
if (textField.getText().equals("1")) {
System.out.println("进去");
lblNewLabel1.setVisible(true); // 显示1号标签
} else {
lblNewLabel2.setVisible(true); // 显示2号标签
}
------解决方案--------------------contentPane.add(lblNewLabel1);
后尝试:
1、设置下lblNewLabel1.setBounds
2、contentPane.updateUI();
------解决方案--------------------感觉不需要从新lable属性了。
直接添加完控件后,updateUI();