在JOptionPane中设置JTextField的文本

时间:2017-05-12 23:31:24

标签: java swing joptionpane

我有一个JTable存储有关菜肴的数据。当用户尝试添加新菜时,他必须在四个字段中输入值。虽然默认情况下JTable是可编辑的,但我想创建自己的实现来编辑行。我有一个生成自定义对话框的方法和一个存储文本字段引用的数组列表。我的目标是将所有文本字段的文本设置为行中对应的文本,然后显示对话框。这是我到目前为止所尝试过的。

        edit.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                if (dishes.getSelectionModel().isSelectionEmpty())
                {
                    JOptionPane.showMessageDialog(null, "You need to select a dish in order to edit it",
                            "No element selected", JOptionPane.INFORMATION_MESSAGE);
                }
                else
                {
                    String[] labels = {"Name:", "Description:", "Price:", "Restock Level:"};

                    int fields = 4
;
                    JOptionPane optionPane = new JOptionPane();

                    optionPane.setVisible(false);

                    optionPane.showConfirmDialog(null, createInputDialog(labels,fields),
                        "New Dish", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

                    for(int i = 0; i < textFields.size(); i++)
                    {
                        textFields.get(i).setText(dishes.getValueAt(dishes.getSelectedRow(), i).toString());
                    } 

                    optionPane.setVisible(true);
                }
            }
        });

以下是创建对话框中使用的面板的代码

//Creates an input dialog with the specified number of fields and text for the labels
    public JPanel createInputDialog(String[] labels, int numFields)
    {
        JPanel input = new JPanel(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5,5,5,5);

        textFields = new ArrayList<JTextField>();

        for(int i = 0; i < numFields; i++)
        {
            gbc.gridx = 2;
            gbc.gridy = i;
            gbc.anchor = GridBagConstraints.WEST;

            JLabel label = new JLabel(labels[i]);
            label.setFont(font);

            input.add(label, gbc);

            gbc.gridx = 4;

            JTextField field = new JTextField(10);
            field.setFont(font);

            input.add(field, gbc);
            textFields.add(field);
        }

        error = new JLabel("");
        error.setForeground(Color.RED);

        gbc.gridx = 2;
        gbc.gridy = numFields + 1;
        gbc.gridwidth = 2;

        input.add(error, gbc);

        return input;
    }

2 个答案:

答案 0 :(得分:1)

基本思想将是

  • 使用JTable#getSelectedRow获取所选行索引(并且-1无法选择)。
  • 使用JTable#getValueAt获取列值。
  • 将这些值传递给createInputDialog方法,以便填充文本字段

答案 1 :(得分:0)

对于JTextFields使用arraylist可能更简单一些吗?

ArrayList<JTextField> textFields = new ArrayList<JTextField>();

然后你可以遍历你的arraylist。

for (JTextField txtField : textFields) {
            txtField.setText(dishes.getValueAt(dishes.getSelectedRow(), i).toString());
        }

我不确定我是否完全理解了这个问题。

相关问题