Home > Blockchain >  How to add to a JFrame 3 JPanels: The 1st JPanel to take up 90% of the frame, the second to be on sk
How to add to a JFrame 3 JPanels: The 1st JPanel to take up 90% of the frame, the second to be on sk

Time:11-14

I am stuck on getting this swing UI to act the way I was hoping. I wrote this demo code to showcase what it is doing and I will now explain what I was hoping to make it do.

I have a JFrame and 3 JPanels

enter image description here

Second step: add controls buttons at the top. Define the buttons panel:

class ControlsPane extends JPanel{

    public ControlsPane(ActionListener listener) {

        setOpaque(false);
        JButton btnShowHide = new JButton("Show Drawer");
        add(btnShowHide);
        btnShowHide.addActionListener(listener);

        JButton btnExit = new JButton("Exit");
        add(btnExit);
        btnExit.addActionListener(e-> System.exit(0));
    }
}

and modify MainPane constructor to use BorderLayout and add the buttons panel as suggested by @camickr:

MainPane(Image background) {
    this.background = background;
    size = new Dimension(background.getWidth(null), background.getHeight(null));
    setLayout(new BorderLayout(5,5));
    //action listener for show drawer button
    ActionListener  listener = e-> System.out.println("Show Drawer clicked");
    add(new ControlsPane(listener), BorderLayout.PAGE_START);
}

enter image description here

Now take it to the next step (for example add a drawer).

CodePudding user response:

Something like this?

public static void main(String[] args) {
    JFrame frame = new JFrame("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridBagLayout());
    JToolBar toolBar = new JToolBar(JToolBar.HORIZONTAL);
    toolBar.setFloatable(false);
    frame.add(toolBar, new GridBagConstraints(0, 0, 2, 3, 0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    JPanel drawer = new JPanel();
    drawer.setBackground(Color.BLUE);
    drawer.setOpaque(true);
    drawer.setVisible(false);
    
    JPanel content = new JPanel();
    content.setBackground(Color.GREEN);
    content.setOpaque(true);
    
    frame.add(drawer, new GridBagConstraints(0, 1, 1, 2, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(4, 4, 4, 4), 0, 0));
    frame.add(content, new GridBagConstraints(1, 1, 1, 2, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(4, 4, 4, 4), 0, 0));
    
    Action toggleDrawer = new AbstractAction("Toggle Drawer") {
        
        @Override
        public void actionPerformed(ActionEvent e) {
            drawer.setVisible(!drawer.isVisible());
            frame.revalidate();
            frame.repaint();
        }
    };
    toolBar.add(new JButton(toggleDrawer));
    
    frame.pack();
    frame.setSize(300, 500);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
  • Related