I want my Jpanel to be just below my toolbar but the result will be my jpanel not appearing and if I also make my JPanel to have a borderlayout of page start the JFrame will only show the JPanel and not my toolbar. This is my code
package omok;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import java.util.*;
import javax.swing.*;
public class Omok implements ActionListener {
JFrame frame =new JFrame();
public Omok() {
JMenuBar menuBar=menubar();
JToolBar toolBar=toolBar();
JPanel panel=panel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,500);
frame.getContentPane().setBackground(Color.ORANGE);
frame.setLayout(new BorderLayout());
frame.setJMenuBar(menuBar);
frame.add(toolBar,BorderLayout.PAGE_START);
frame.add(panel,BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
private JMenuBar menubar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Game");
menu.setMnemonic(KeyEvent.VK_G);
menu.getAccessibleContext().setAccessibleDescription("Game menu");
menuBar.add(menu);
JMenuItem menuItem = new JMenuItem("Play", KeyEvent.VK_P);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_P, InputEvent.ALT_DOWN_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Play a new game");
//menuItem.addActionListener(…);
menu.add(menuItem);
return menuBar;
}
private JToolBar toolBar() {
ImageIcon icon=new ImageIcon("C:\\Users\\carlo\\Documents\\Adv OO Programming\\L\\OmokGUI\\res\\play.png");
Image image=icon.getImage();
Image newImg=image.getScaledInstance(20, 20, Image.SCALE_SMOOTH);
icon=new ImageIcon(newImg);
JToolBar toolBar = new JToolBar("Omok");
JButton button = new JButton(icon);
button.setPreferredSize(new Dimension(20,20));
button.setToolTipText("Play a new game");
button.setFocusPainted(false);
toolBar.add(button);
toolBar.setPreferredSize(new Dimension(30,30));
return toolBar;
}
private JPanel panel() {
JPanel panel=new JPanel();
panel.setPreferredSize(new Dimension(40,40));
panel.setBackground(Color.gray);
return panel;
}
}
This is the result I get
As the BorderLayout
JavaDocs state, "PAGE_START
... this is equivalent to NORTH" - so you're trying to place two components into the same position, BorderLayout
will only allow a single component to exist at each of it's 5 available locations.
If you want both components in the NORTH
position, then you'd need to use another container (like JPanel
) to place them into and the place that container into the NORTH
position.
This is often know as a compound layout.