我的代碼顯示了一個紋理,您可以在其中輸入一些內容,并且它應該出現在帶有復選框的標簽下方。我想要的是復選框只有在通過文本欄位設定標題時才存在。我在這個主題上找不到任何東西,只是 cb.validate(); 但這并沒有真正幫助我。我也試過這樣做。add(cb); 當按下按鈕 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);
}
}
}
}
uj5u.com熱心網友回復:
簡短的回答
Swing 是懶惰的,它不會在你可以的時候自動更新 UI,相反,當你完成后,你需要觸發一個新的布局并繪制通道。
添加...
getContentPane().revalidate();
getContentPane().repaint();
后this.add(cb);
長答案
不要從 擴展JFrame,您不會向該類添加任何新功能,而只是將自己鎖定在一個用例中。
避免null布局,它們對您沒有幫助。相反,請花時間了解如何使用提供的布局管理 API。請參閱在容器中布置組件
如果您的目標是生成一個值串列,那么您應該考慮使用 aJTable或JList.
有關更多詳細資訊,請參閱如何使用表格和如何使用串列
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439791.html
上一篇:為什么當我在MouseEntered()函式中使用while回圈時一切都停止了?在Java中
下一篇:JButton文本會自行更改嗎?
