首页 > 解决方案 > 当我在框架上滚动时,如何让 JButton 移动?

问题描述

我有一个面板,在我的框架中可以滚动。我需要的是添加一个即使在我滚动时也保持固定在右下角的按钮。我是 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);

标签: javaswingjframejpaneljbutton

解决方案


我会使用嵌套面板和外部面板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);
        });
    }
}

结果:

结果


推荐阅读