gpt4 book ai didi

java - 添加新的组合框 Java

转载 作者:行者123 更新时间:2023-11-30 06:06:46 26 4
gpt4 key购买 nike

我在使用 java 上的 Swing 界面时遇到问题。说明:我有一个包含 1、2、3、4、5 个项目的组合框。当选择确切的项目时,我需要创建更多组合框,其数量取决于所选项目。因此,如果选择数字 5,则框架中还必须出现 5 个组合框。我使用了 ActionListener 但它无法正常工作。然而,相同的代码但在 Actionlistener 之外效果很好。这可能是什么问题?

public class FrameClass extends JFrame {
JPanel panel;
JComboBox box;

String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox adults = new JComboBox(s);
JComboBox children = new JComboBox(s1);

panel.add(box, BorderLayout.CENTER);

box.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i <= box.getSelectedIndex(); i++) {
panel.add(adults, BorderLayout.WEST);
panel.add(children, BorderLayout.WEST);
}
}
});
add(panel);
}
}

public class MainClass {
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(Color.WHITE);
frame.setVisible(true);
}
}

最佳答案

您没有向布局管理器通知面板中的新元素的问题。

这是 Action 监听器的正确变体:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class FrameClass extends JFrame {
JPanel panel;

JComboBox<String> box;

String[] s = {"1", "2", "3", "4", "5"};

String[] s1 = {"0", "1", "2", "3", "4", "5"};

public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox[] adults = new JComboBox[5];
JComboBox[] children = new JComboBox[5];
for (int i = 0; i < 5; i++) {
adults[i] = new JComboBox<>(s);
children[i] = new JComboBox<>(s1);
}

panel.add(box, BorderLayout.CENTER);
JPanel nested = new JPanel();
add(nested, BorderLayout.EAST);
box.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nested.removeAll();
nested.setLayout(new GridLayout(box.getSelectedIndex() + 1, 2));
for (int i = 0; i <= box.getSelectedIndex(); i++) {
nested.add(adults[i]);
nested.add(children[i]);
}
getContentPane().revalidate();
getContentPane().repaint();
pack();
}
});
add(panel);
}

public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.getContentPane().setBackground(Color.WHITE);
frame.setLocationRelativeTo(null); // center the window
frame.setVisible(true);
}
}

关于java - 添加新的组合框 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51136257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com