如何让 JButton 在框架上滚动时移动?

How to have a JButton that moves as I scroll on the frame?

我有一个面板,我已将其设置为可在我的框架中滚动。 我需要的是添加一个按钮,即使我滚动时它也固定在右下角。 我是 Java Swing 的新手,非常感谢我能得到的所有帮助。

mainPanel = new SimulationPanel(); //class SimulationPanel extends JPanel

//making mainPanel scrollable
mainPanel.setPreferredSize(new Dimension(((int)(WIDTH*1.2)), HEIGHT));
JScrollPane scrollPane = new JScrollPane(mainPanel);
scrollPane.setViewportView(mainPanel);

// Settings for JFrame
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("Warehouse Simulator");
frame.setContentPane(scrollPane);
frame.setSize(screenSize.width, screenSize.height);
frame.setResizable(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);

我会选择 BoxLayout。添加另一个面板 (metaPanel),您首先在其中放置滚动面板,然后添加一个按钮。您不使用 scrollingPanel 作为 contentPane,而是使用 metaPanel。示例(示例有效,但您需要修改它以使界面看起来更好):

    JPanel mainPanel = new JPanel();
    JScrollPane scrollPane = new JScrollPane(mainPanel);
    scrollPane.setViewportView(mainPanel);

    JPanel metaPanel = new JPanel();
    BoxLayout boxlayout = new BoxLayout(metaPanel, BoxLayout.Y_AXIS);
    metaPanel.setLayout(boxlayout);
    metaPanel.add(scrollPane);
    metaPanel.add(new JButton("button"));

    // Settings for JFrame
    frame = new JFrame("Warehouse Simulator");
    frame.setContentPane(metaPanel); // Put metaPanel here
    frame.setSize(500, 300);
    frame.setResizable(true);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);

我会使用嵌套面板,外层面板与 BorderLayout 一起使用。然后一个 FlowLayout 并对齐 FlowLayout.RIGHT 和里面的按钮。

public class Example extends JFrame {
    public Example() {
        super("");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setLayout(new BorderLayout());

        JTextArea textArea = new JTextArea(10000, 0);
        JScrollPane scrollPane = new JScrollPane(textArea);

        add(scrollPane, BorderLayout.CENTER);

        JButton button = new JButton("button");

        JPanel panelWithButton = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        panelWithButton.add(button);
        add(panelWithButton, BorderLayout.PAGE_END);

        setLocationByPlatform(true);
        pack();
        setSize(600, 600);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new Example().setVisible(true);
        });
    }
}

结果: