【问题标题】:Adding Ok/Cancel buttons to existing JFrame向现有 JFrame 添加确定/取消按钮
【发布时间】: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,因此面板本身也可能包含其他面板和组件,但应将它们添加到该单个组件中。

标签: java swing jbutton


【解决方案1】:

您需要为您的JFrame 提供一个layout,您可以在其中放置滚动视图和一个带有按钮的面板。这是一个例子:

在向您的frame 添加任何内容之前,请写下

frame.getContentPane().setLayout(new BorderLayout());

为按钮创建一个面板

JPanel panel = new JPanel(); //Flow layout by default
//If you want to anchor the buttons to the right you might try
panel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
panel.add(okButton);
panel.add(cancelButton);

然后像这样添加scrollPane

frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

以及面板中的按钮

frame.getContentPane().add(panel, BorderLayout.NORTH);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多