为了账号安全,请及时绑定邮箱和手机立即绑定

选择特定 JComboBox 项时如何向 JPanel 添加额外的 JButton

选择特定 JComboBox 项时如何向 JPanel 添加额外的 JButton

杨魅力 2022-05-20 18:26:08
我一直面临这个关于让我的 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();希望这可以帮助任何有需要的人。:)
查看完整描述

1 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

您需要revalidate()添加的组件如下所示:


centerPanel.revalidate();

您需要更改以下代码:


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));

            }

        }


        centerPanel.revalidate(); // Need to add this for revalidation for the component

    }

});


查看完整回答
反对 回复 2022-05-20
  • 1 回答
  • 0 关注
  • 120 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号