簡體   English   中英

如何讓 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);

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

結果:

結果

我會選擇 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM