【问题标题】:How to fill JComboBox after user fills necessary text fields?用户填写必要的文本字段后如何填写 JComboBox?
【发布时间】:2015-03-08 19:21:20
【问题描述】:

我想在我的主面板中添加一个JComboBox 并用我用另一种名为rectSizeList 的方法制作的ArrayList 填充它(现在将ArrayList 打印到控制台),这个方法得到它的参数来自另一个名为actionPerformed 的静态方法。在用户输入填充我的 ComboBox 后,我想不出一种方法来获取填充的数组。任何帮助将不胜感激。

所有评论都是这种格式是为了帮助问题:

      /*
       * Like so
       *
       */

所有其他 cmets 都是为了帮助我想编译和运行的任何人,以便他们了解发生了什么。

主类

import javax.swing.*;

public class ductulatorApp
{
    public static void main(String[] args)
    {
        JFrame frame = new DuctulatorFrame();
        frame.setVisible(true);
    }
}

框架类

import javax.swing.*;
import java.awt.*;

public class DuctulatorFrame extends JFrame
{
    private static final long serialVersionUID = 1L;
    public DuctulatorFrame()
    {
        setTitle("Test Scores");
        setSize(267, 200);
        centerWindow(this);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new DuctulatorPanel();
        this.add(panel);
    }
    private void centerWindow(Window w)
    {
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d = tk.getScreenSize();
        setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    }
}

面板类

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.ArrayList;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class DuctulatorPanel extends JPanel implements ActionListener
{
    private static final long serialVersionUID = 1L;
    private JTextField staticTextField,
                        cfmTextField,
                        rductTextField,
                        sqductTextField;
    private JLabel staticLabel,
                    cfmLabel,
                    rductLabel,
                    sqductLabel;
    private JButton calculateButton,
                    exitButton,
                    clearButton;
    private JComboBox ductSizes;        //JComboBox instance

    private String[] ductList;          //Array to fill JComboBox

    double staticP;          //static pressure entered by user
    double cfm;             //cfm entered by user
    double deSQ;            
    double de;              //round duct diameter
    double pi = 3.14;       
    double ca;              //round duct surface area
    double radious; 
    double sqrA;            //rectangular duct area

    //two sides of rectangular duct
    double a = 4;
    double b = 4;

    String squareduct;

    public DuctulatorPanel()
    {

        // Creates main panel for labels and text fields
        JPanel displayPanel = new JPanel();
        displayPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        staticLabel = new JLabel("Static pressure:");
        displayPanel.add(staticLabel);

        staticTextField = new JTextField(10);
displayPanel.add(staticTextField);

        cfmLabel = new JLabel("             CFM:");
        displayPanel.add(cfmLabel);

        cfmTextField = new JTextField(10);
        displayPanel.add(cfmTextField);

        rductLabel = new JLabel("Round Duct:");
        displayPanel.add(rductLabel);

        rductTextField = new JTextField(15);
        rductTextField.setEditable(false);
        rductTextField.setFocusable(false);
        displayPanel.add(rductTextField);

        sqductLabel = new JLabel("Square Duct:");
        displayPanel.add(sqductLabel);

        /*
        * This is where I want to add my JComboBox problem is I want to populate ductList arr
        * with the array inside rectSizeList(int number) BELOW
        * right now this method only prints my array to the console
        * this method takes its parameters from the value assigned to 
        * actionperformed(ActionEvent e)
        * below is comboBox commented out
        */

        //ductList = new String[list.size];     THIS IS ASSUMING I COULD SOME HOW TRANSFER
        //ductList = list.toArray(ductList);    ARRAYLIST UP HERE AND NAME IT LIST AND USE IT

        //ductSizes = new JComboBox(ductList);
        //ductSizes.setSelectedIndex(1);
        //displayPanel.add(ductSizes);

        sqductTextField = new JTextField(10);
        sqductTextField.setEditable(false);
        sqductTextField.setFocusable(false);
        displayPanel.add(sqductTextField);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        calculateButton = new JButton("Calculate");
        calculateButton.addActionListener(this);
        buttonPanel.add(calculateButton);

        clearButton = new JButton("Clear");
        clearButton.addActionListener(this);
        buttonPanel.add(clearButton);

        exitButton = new JButton("Exit");
        exitButton.addActionListener(this);
        buttonPanel.add(exitButton);

        this.setLayout(new BorderLayout());
        this.add(displayPanel, BorderLayout.CENTER);
        this.add(buttonPanel, BorderLayout.SOUTH);
    }
    public void actionPerformed(ActionEvent e)
    {
        NumberFormat number = NumberFormat.getNumberInstance();
        number.setMaximumFractionDigits(1);

        Object source = e.getSource();
        if(source == exitButton)System.exit(0);

        else if(source == clearButton)
        {
            staticTextField.setText("");
            cfmTextField.setText("");
            rductTextField.setText("");
            sqductTextField.setText("");
            staticP = 0;
            cfm = 0;
            deSQ = 0;
        }
        else if(source == calculateButton)
        {
            try
            {
                staticP = Double.parseDouble(staticTextField.getText());
                cfm = Double.parseDouble(cfmTextField.getText());
            }
            catch(NumberFormatException nfe)
            {
                staticTextField.setText("Invalid input");
                staticP = 0;
                cfm = 0;
                deSQ = 0;
                de = 0;
            }

                deSQ = staticP * (0.109136 * Math.pow(cfm, 1.9));   //Calculate round duct
                de = Math.pow(deSQ, 0.199) * 2.5;                   //diameter

                // Calculate round duct surface area
                radious = de/2;
                ca = (radious * radious) * pi;
                ca = (int)ca;
                rectSizeList((int)ca);

                double i = 0;
                for(i=0; i<ca; i++)
                {
                    a = a + 0.5;
                    b = b + 0.5;
                    i = a * b;  // convert round duct to rectangular duct
                }

                sqrA = i;
                a = (int)a;
                b = (int)b;
                rductTextField.setText(number.format(de));
                squareduct = (a + " x " + b);
                sqductTextField.setText(squareduct);
        }
    }
    public ArrayList<String> rectSizeList(int number) 
    {
        if (number <= 0) throw new IllegalArgumentException("The number should be greater than 0.");

        int i = 0;
        int j = 0;

        /*
        * This is the array list I am hoping to use in order to fill array for
        * comboBox
        */


        ArrayList<String> rectangularDucts = new ArrayList<String>(); //Create array for rectangular duct

        // Fill array for rectangular duct using nested for loop
        /*
         * If statement will ensure the result is with in range of surface
         * area of duct
         */
        for(i=4; i<=50; i++)
        {
            for(j=4; j<=50; j++)
            {
                if(number == i*j || (i*j)+1 == number || (i*j)-2 == number) 
                {
                    rectangularDucts.add(i + " x " + j);
                }
            }
            if(number == i*j || (i*j)+1 == number || (i*j)-2 == number)
            {
                rectangularDucts.add(i + " x " + j);
            }
        }
        System.out.println(rectangularDucts);  

        return rectangularDucts;
    }
}

【问题讨论】:

  • 不确定其他人,但我正忙着弄清楚你的代码在做什么或你的问题是什么。如需更好的帮助,请考虑创建并发布Minimal, Complete, and Verifiable Example Program。我们不想看到你的整个程序,而是你应该将你的代码压缩成仍然可以编译的最小部分,没有与你的问题无关的额外代码,但仍然可以演示你的问题。
  • 我不在电脑前,但我一到家就会这样做。另外程序没有任何问题,我想添加组合框并用在发布的最后一个方法中创建的数组填充它...最后一个方法是完整代码
  • @HovercraftFullOfEels 我更新了我的问题并添加了一些可编译的代码。希望这对您有所帮助并帮助您找到答案,谢谢。
  • 感谢您的编辑。我认为您的解决方案非常简单,无需使用数组来保存您的值。

标签: java swing arraylist jcombobox


【解决方案1】:

我认为您的问题很容易解决,只需一个 DefaultComboBoxModel 对象,或者在您的情况下(我猜),一个 DefaultComboBoxModel&lt;String&gt; 对象。给你的类这个字段,创建你的 JComboBox 作为它的模型,通过将它传递给构造函数,然后在需要时填充这个模型对象。

例如:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class ComboModelEg extends JPanel {
   private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
   private JComboBox<String> comboBox = new JComboBox<>(comboModel);
   private JTextField textField = new JTextField(5);

   public ComboModelEg() {
      // so combo box is wide enough
      comboBox.setPrototypeDisplayValue("              ");
      add(comboBox);
      add(textField);
      add(new JButton(new AddToComboAction("Add Text", KeyEvent.VK_A)));
   }

   // AbstractAction is like a *super* ActionListener
   private class AddToComboAction extends AbstractAction {
      public AddToComboAction(String name, int mnemonic) {
         super(name);  // button's text
         putValue(MNEMONIC_KEY, mnemonic); // button's mnemonic key
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         String text = textField.getText(); //get text from text field
         comboModel.addElement(text);  // and put it into combo box's model
      }
   }   

   private static void createAndShowGui() {
      ComboModelEg mainPanel = new ComboModelEg();

      JFrame frame = new JFrame("ComboModelEg");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

翻译成你的代码,它可能看起来像:

  for (i = 4; i <= 50; i++) {
     for (j = 4; j <= 50; j++) {
        if (number == i * j || (i * j) + 1 == number
              || (i * j) - 2 == number) {
           // rectangularDucts.add(i + " x " + j); //!!
           comboModel.addElement(i + " x " + j); //!!
        }
     }
     if (number == i * j || (i * j) + 1 == number || (i * j) - 2 == number) {
        // rectangularDucts.add(i + " x " + j);
        comboModel.addElement(i + " x " + j); //!!
     }
  }

【讨论】:

  • 我一回到家就试试这个。一个问题; comboBoxModel 是否直接与必须填写才能启动的文本字段一起使用?
  • @ednomx:它将与您编写的代码一起使用,不多也不少。
  • 好的。非常感谢,我最终使用了它并且它有效,谢谢,我只需要在comboboxmodel 上阅读更多内容,以便了解它是如何工作的。谢谢。
【解决方案2】:

我就是这样做的

ArrayList<String> myList = new ArrayList<>();
//some code to populate the list
jComboBox.removeAllItems();
    for(int i=0;i<myList.size();i++){
        jComboBox.addItem(myList.get(i));

    }

【讨论】:

  • 这只是个人的事情,但我更喜欢简单地替换组合框的模型......
  • 我的模型已经在上面显示的代码片段上定义了,我正在结合 netbeans 生成的 GUI 代码 + 用于与 gui 交互的手写代码
  • 您没有在我看到的任何地方定义 ComboBoxModel。此外,代码是否由表单编辑器生成并没有区别,调用 setModel 的工作方式相同......
  • 也许我没有正确解释自己。我知道如何添加和填充组合框,我用注释掉的组合框版本更新了我的问题和我想要填充它的数组以及代码中的一些更好的 cmets 来尝试帮助问题
猜你喜欢
  • 2020-04-26
  • 2019-01-04
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 2016-04-19
  • 2018-09-20
  • 2021-10-09
  • 1970-01-01
相关资源
最近更新 更多