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

问题描述 投票:0回答:2

我有一个面板,可以在其框架中滚动。我需要添加一个即使在滚动时也保持固定在右下角的按钮。我是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);
java swing jframe jpanel jbutton
2个回答
0
投票

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

    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);

0
投票

我将嵌套面板与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);
        });
    }
}

结果:

result

© www.soinside.com 2019 - 2024. All rights reserved.