My code displays a texture where you can type something in and than it should appear under the label with a checkbox. 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(); but that didn't really help me. I also tried doing this.add(cb); when the button ks pressed but it also didn't work.
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);
}
}
}
}
CodePudding user response:
Short answer
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.
Add...
getContentPane().revalidate();
getContentPane().repaint();
after this.add(cb);
Long answer
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.
Avoid null
layouts, they aren't helping you. Instead, make the time to understand how to use the layout management API which is provided. 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
.
See How to Use Tables and How to Use Lists for more details