我试图用JScrollPane制作一个JFrame,其中包含数百个JRadioButton和下面的两个JButton(“确定”和“取消”)。最后,我发现了JOptionPane.showConfirmDialog(...)方法。

它似乎很适合我的需求:从第一个JFrame中,使用包含我的单选按钮的Scroll打开一个“窗口”,然后在单击“确定”时在我的第一个JFrame中获取选定的窗口。
但是,当showConfirmDialog出现时,没有JScrollPane,并且我们看不到窗口的底部(有数百个单选按钮)。因此:


我试图调用JOptionPane.showConfirmDialog(myScrollPane)而不是将JScrollPane添加到JPanel并使用JPanel调用该方法...这没有用
我试图初始化JOptionPane对象,然后设置其最大大小,然后使用已初始化的对象调用showConfirmDialog方法,但是它不起作用,因为“该方法必须以静态方式调用”。


因此,我需要您的帮助,这是我的代码,并且我不明白哪里出了问题以及为什么我没有在确认对话框中使用单选按钮滚动显示的原因。

public void buildMambaJobPathWindow(ArrayList<String> list) {
    ButtonGroup buttonGroup = new ButtonGroup();
    JPanel radioPanel = new JPanel(new GridLayout(0,1));
    for(int i=0; i<list.size(); i++) {
        JRadioButton radioButton = new JRadioButton(list.get(i));
        buttonGroup.add(radioButton);
        radioButton.addActionListener(this);
        radioButton.setActionCommand(list.get(i));
        radioPanel.add(radioButton);
    }

    JScrollPane myScrollPane = new JScrollPane(radioPanel);
    myScrollPane.setMaximumSize(new Dimension(600,600));

    JOptionPane.showConfirmDialog(null, myScrollPane);
}

// Listens to the radio buttons
public void actionPerformed(ActionEvent e) {
    String result = e.getActionCommand();
}


感谢您的时间。

最佳答案

here所示,您可以覆盖滚动窗格的getPreferredSize()方法以建立所需的大小。如果任一方向上的内容较大,则将根据需要显示相应的滚动条。

JScrollPane myScrollPane = new JScrollPane(radioPanel){
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(600, 600);
    }
};
JOptionPane.showConfirmDialog(null, myScrollPane);

08-17 19:01