【发布时间】:2017-05-12 23:31:24
【问题描述】:
我有一个 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;
}
【问题讨论】:
-
createInputDialog方法在哪里?我想您需要获取JTable的选择行,从中提取值(JTable#getValueAt)并将这些值提供给createInputDialog -
@MadProgrammer 可变菜品以实际餐桌为准
-
您的任务可能超出了
JOptionPane的处理能力。您可能需要创建一个JDialog。
标签: java swing joptionpane