【发布时间】:2015-10-29 16:07:33
【问题描述】:
我有一个方法弹出一个 JFrame/JScrollPane,它有 2 列,一个用于 hashmap 的键,另一列用于 hashmap 的值。这些值填充在可编辑的文本字段中。我正在尝试向 JFrame 添加一个确定和取消按钮,但是在进行更改后,我在我的应用程序中看不到任何更改。 (也没有收到任何错误,运行时或编译)。知道为什么我的按钮没有显示吗?
private static List<JTextField> showFrames(Map<String, String> longToShortNameMap) {
JFrame frame = new JFrame("Data Changed");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(400, 500);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(0, 2));
List<String> keys = new ArrayList(longToShortNameMap.keySet());
List<JTextField> textFields = new ArrayList<>();
for (String key : keys) {
JLabel label = new JLabel(key);
JTextField textField = new JTextField(longToShortNameMap.get(key));
panel.add(label);
panel.add(textField);
textFields.add(textField);
}
JScrollPane scrollPane = new JScrollPane(panel);
JButton okButton = new JButton("ok"); //added for ok button
JButton cancelButton = new JButton("cancel");//added for cancel button
okButton.setVisible(true);//added for ok button
cancelButton.setVisible(true);//added for cancel button
scrollPane.add(okButton);//added for ok button
scrollPane.add(cancelButton);//added for cancel button
scrollPane.setVisible(true);
scrollPane.setSize(500, 500);
frame.add(scrollPane);
return textFields; //make clicking ok button return this, this method should return void
}
我也尝试将按钮直接添加到 JFrame 而不是 JScrollPane,这会产生相同的结果:没有变化也没有错误(注意:这些按钮应该在 JScrollPane 下方)
如果我将按钮添加到面板,那么按钮会出现,但是我必须滚动到 JScrollPane 的底部才能看到它们,这是不可取的。
【问题讨论】:
-
参见The Use of Multiple JFrames, Good/Bad Practice? 使用
JDialog来实现这一点.. "..尝试添加一个确定和取消按钮.." 但是JOptionPane会更简单,因为它可以配置为显示确定/取消按钮组合。 -
您有几个问题,首先是您没有正确使用 JScrollPane。您应该查看 JOptionPane 以了解自动添加 OK Cancel 按钮,否则请练习您的挥杆教程以了解挥杆的工作原理
-
JScrollPane scrollPane = new JScrollPane(panel); .. scrollPane.add(okButton); ..JScrollPane旨在仅容纳一个组件。由于该组件可能是JPanel,因此面板本身也可能包含其他面板和组件,但应将它们添加到该单个组件中。