繁体   English   中英

用户填写必要的文本字段后如何填充JComboBox?

[英]How to fill JComboBox after user fills necessary text fields?

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

所有评论都是这种格式的辅助问题:

      /*
       * Like so
       *
       */

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

主班

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

我认为仅使用DefaultComboBoxModel对象即可解决您的问题,或者在您的情况下(我想)可以使用DefaultComboBoxModel<String>对象轻松解决。 给您的类一个字段,将其作为模型创建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); //!!
     }
  }

这就是我的方法

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

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM