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

Gaurav Agarwal :

I have a Panel which I have made scrollable in my frame. What I need is to add a button that stays fixed in the lower right corner even when I scroll. I'm new to Java Swing so would appreciate all and any help that I can get.

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

I would go for a BoxLayout. Add another panel (metaPanel) in which your first put your scrollingPanel, and then you add a button. Instead of usgin scrollingPanel as contentPane, you use metaPanel. Example (the example works, but you need to modify it to make the interface look nice):

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=276361&siteId=1