我一直面临着这个关于使 JCombobox 尽可能动态的小问题。
例如,当选择组合框中的选定项目时,它将根据数量动态更改按钮的数量该月内的天数并添加到面板中
我面临的问题是它不会自动更改面板的显示,但是当我尝试查看代码是否在我的控制台日志中运行时。它运行顺利。我尽力寻找解决方案,但无济于事。
主要问题在actionListener中,例如,如果选择二月,它将显示28个按钮,如果选择一月,它将显示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();
month_combo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int count = 0;
//---- gettind days of month selected in comboBox
if (month_combo.getSelectedItem().equals("February")) {
centerPanel.removeAll();
centerPanel.repaint();
for (int i = 1; i <= 28; i++) {
centerPanel.add(method_Btn(i));
System.out.println("days in feb " + i);
}
centerPanel.revalidate();
}
if (month_combo.getSelectedItem().equals("March")) {
centerPanel.removeAll();
centerPanel.repaint();
for (int i = 1; i <= 31; i++) {
centerPanel.add(method_Btn(i));
}
centerPanel.revalidate();
}
}
});
希望对有需要的人有所帮助。 :)
最佳答案
您需要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
}
});
关于java - 选择特定 JComboBox 项时如何向 JPanel 添加附加 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54322310/