IAmBlake IAmBlake - 8 days ago 5
Java Question

How to set Button panel at the top of the window in JFrame?

In my mini browser program my buttonPanel contains backButton, forwardButton and locationTextField. fPane contains buttonPanel and jfxPanel. The browser window should be look like the buttonPanel on the top and the other things cover the rest of the window.

Here is my constructor portion:

private JButton backButton = new JButton(), forwardButton = new JButton();

private final JFXPanel jfxPanel = new JFXPanel();

private JTextField locationTextField = new JTextField(40);

private JPanel fPane = new JPanel();

public Browser(){
createScene();
setPreferredSize(new Dimension(1024,600));
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel = new JPanel(new BorderLayout(5,0));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
buttonPanel.setBackground(Color.darkGray);
backButton.setIcon(new ImageIcon(Hello.class.getResource("/left.png")));
backButton.setBackground(Color.DARK_GRAY);
buttonPanel.add(backButton,BorderLayout.NORTH);
forwardButton.setIcon(new ImageIcon(Hello.class.getResource("/forward.png")));
forwardButton.setBackground(Color.DARK_GRAY);
buttonPanel.add(forwardButton,BorderLayout.NORTH);
buttonPanel.add(locationTextField,BorderLayout.CENTER);
fPane.add(buttonPanel,BorderLayout.NORTH);
fPane.add(jfxPanel, BorderLayout.CENTER);
getContentPane().setLayout(new BorderLayout(5,0));
getContentPane().add(fPane, BorderLayout.WEST);
pack();
}


When i compile it,it looks like this:

enter image description here

the buttonPanel goes aside instead of going top of the window, back button disappears and extra space is created below the page.

Lee Lee
Answer

I assumed the buttons are placed inside buttonPanel, then you might try

getContentPane().add(buttonPanel, BorderLayout.NORTH);
getContentPane().add(fPane, BorderLayout.CENTER);

before the pack()