[英]checkbox appears when button pressed, java
My code displays a texture where you can type something in and than it should appear under the label with a checkbox.我的代码显示了一个纹理,您可以在其中键入内容,并且它应该出现在带有复选框的 label 下方。 What I want is that the checkbox is only there if the title is set through the textfield.
我想要的是只有通过文本字段设置标题时复选框才会出现。 I couldn't find anything on this topic just cb.validate();
我找不到关于这个话题的任何东西 cb.validate(); but that didn't really help me.
但这并没有真正帮助我。 I also tried doing this.add(cb);
我也试过做 this.add(cb); when the button ks pressed but it also didn't work.
当按下按钮 ks 但它也不起作用。
public class ToDoPage extends JFrame implements ActionListener {
int height = 300 ;
int width = 450;
JTextField tf = new JTextField("Tip here");
JLabel l1 = new JLabel();
JLabel l2 = new JLabel("");
JLabel l3 = new JLabel("");
JLabel l4 = new JLabel("");
JLabel l5 = new JLabel("");
JCheckBox cb = new JCheckBox();
JLabel l = new JLabel("Daily Goals");
JButton b = new JButton();
Date date = new Date();
public ToDoPage() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(height, width); //NICHT HARDCODEN
this.setLayout(null);
this.setLocationRelativeTo(null);
this.setResizable(false);
SimpleDateFormat DateFor = new SimpleDateFormat("dd MMMM yyyy");
String stringDate = DateFor.format(date);
tf.setBounds(50, 130, 170, 25);
cb.setBounds(60, 150, 260, 40);
l3.setBounds(60, 180, 260, 40);
l4.setBounds(60, 210, 260, 40);
l5.setBounds(60, 240, 260, 40);
l1.setText("Today is: " + stringDate);
l1.setBounds(70, 10, 300, 40);
l.setBounds(87, 90, 260, 40);
l.setFont(new Font(null, Font.ITALIC, 20));
b.setBounds(230, 130, 25, 25);
b.addActionListener(this);
this.add(tf);
this.add(l2);
this.add(b);
this.add(l);
this.add(l1);
this.add(l3);
this.add(l4);
this.add(l5);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b) {
String userInput = tf.getText();
cb.setText(userInput);
this.add(cb);
}
}
}
}
Swing is lazy, it won't automatically update the UI when you can it, instead, when you're done, you need to trigger a new layout and paint pass. Swing 是懒惰的,它不会在你可以更新 UI 时自动更新,相反,当你完成后,你需要触发一个新的布局和绘制通道。
Add...添加...
getContentPane().revalidate();
getContentPane().repaint();
after this.add(cb);
在
this.add(cb);
Don't extend from JFrame
, you're not adding any new functionality to the class and you're simply locking yourself into a single use case.不要从
JFrame
扩展,您不会向 class 添加任何新功能,您只是将自己锁定在一个用例中。
Avoid null
layouts, they aren't helping you.避免
null
布局,它们对你没有帮助。 Instead, make the time to understand how to use the layout management API which is provided.相反,花时间了解如何使用提供的布局管理 API。 See Laying Out Components Within a Container
请参阅在容器中布置组件
If you're aiming to produce a list of values, then you should consider making use of either a JTable
or JList
.如果您打算生成一个值列表,那么您应该考虑使用
JTable
或JList
。
See How to Use Tables and How to Use Lists for more details有关详细信息,请参阅如何使用表格和如何使用列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.