我一直面临这个关于让我的 JCombobox 尽可能动态的小问题。
For an example, when a selected item in combobox is selected, it will dynamically change the number of buttons accordance to the number of days within the month and be added in the panel
我面临的问题是它不会自动更改面板的显示,但是当我尝试查看代码是否在我的控制台日志中运行时。它运行顺利。我尽我所能找到解决方案,但无济于事。
主要问题在 actionListener 中,例如,如果选择了 2 月,它将显示 28 个按钮,如果选择了 1 月,它将显示 31 天等,但是当我运行代码时,我的 system.out.println 状态它运行但我的 Gui 没有显示任何按钮。

private static JButton method_Btn(int i){
JButton btn = new JButton(Integer.toString(i));
return btn;
}
public static void day(){
JFrame frame = new JFrame();
JPanel topPanel = new JPanel();
JPanel centerPanel = new JPanel();
JButton days = new JButton();
JLabel days_label = new JLabel();
//-- Top Panel
String month[] = {"--Select Month--" , "January", "February"};
JComboBox month_combo = new JComboBox(month);
topPanel.add(month_combo, BorderLayout.PAGE_START);
//-- Center Panel
centerPanel.setLayout(new FlowLayout());
centerPanel.add(days_label);
//------- Change when jcombo is selected
month_combo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(month_combo.getSelectedItem().equals("January")){
for(int i = 0;i < 31;i++){
centerPanel.add(method_Btn(i));
}
}
if(month_combo.getSelectedItem().equals("February")){
for(int i = 0;i < 28;i++){
centerPanel.add(method_Btn(i));
}
}
}
});
frame.add(topPanel, BorderLayout.PAGE_START);
frame.add(centerPanel , BorderLayout.CENTER);
frame.setSize(400,400);
frame.setVisible(true);
}
public static void main(String[] args){
day();
}
附加说明,我意识到我面临的另一个问题是,它会在选择第二个月后创建按钮的数量。我如何解决它是我添加了 centerPanel.removeAll(); 和 centerPanel.repaint();
希望这可以帮助任何有需要的人。:)
杨魅力
HUWWW
随时随地看视频慕课网APP
相关分类