如何在不使用cardlayouts的情况下重新加载面板?

6vl6ewon  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(507)

tldr;:
我正在寻找重新加载jpanels及其组件的方法。
我想实现一个动态变化的jcombobox。情况如下:
有一个按钮,它在后台生成数据(“生成内容”),这里只是一些随机数。生成数据后,应该可以在jcombobox中选择此数据。

  1. /**
  2. * Initialize the contents of the frame.
  3. */
  4. private void initialize() {
  5. frame = new JFrame();
  6. frame.setBounds(100, 100, 450, 300);
  7. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  8. panel = new JPanel();
  9. frame.getContentPane().add(panel, BorderLayout.CENTER);
  10. panel.setLayout(null);
  11. comboBox = new JComboBox<String>();
  12. comboBox.setBounds(39, 63, 144, 20);
  13. panel.add(comboBox);
  14. btnGenerateContent = new JButton("generate content");
  15. btnGenerateContent.addActionListener(new ActionListener() {
  16. public void actionPerformed(ActionEvent e) {
  17. comboContent = fillrandoms();
  18. comboBox = new JComboBox<>(fillrandoms());
  19. }
  20. });
  21. btnGenerateContent.setBounds(39, 11, 117, 23);
  22. panel.add(btnGenerateContent);
  23. }
  24. private static String[] fillrandoms() {
  25. String[] array = new String[10];
  26. for (int i = 0; i < 10; i++) {
  27. array[i] = "" + Math.random() * 100;
  28. }
  29. return array;
  30. }

现在,当我执行程序时,它将在有数据显示之前声明并初始化组合框。我现在的想法是,当我点击“生成内容”按钮时,这也会更新面板或组合框的ui。但当我插入 panel.updateUI() 或者 comboBox.updateUI() 什么都没发生。
经过研究,我找到了一些方法来使用cardlayouts,但是我没有将它们用于我的jcombobox,所以我可能需要另一种方法。我甚至不知道这是普通的方法还是其他更好的方法。

mw3dktmi

mw3dktmi1#

更新ui使用方法 panel.revalidate() , panel.repaint() ,或 revalidate() . revalidate()和repain()方法是反映ui更新任务的正确方法。

相关问题