" i can't get the jlabel to stay at the top and the buttons to stay south(bottom)"
That's because you set the layout the
BorderLayout
, then immediately set it toFlowLayout
. WithFlowLayout
, yourBorderLayout
positioning will do nothing.setLayout(new BorderLayout()); setContentPane(new JLabel(new ImageIcon("image.png"))); setLayout(new FlowLayout());
Just get rid of the setLayout(new FlowLayout());
Also your constructor is wrong
public Jukebox() { -Should be- public ButtonClass() {
Also you need to set the layout of the
JLabel
that you set as the content pane. Yout constructor should look like thispublic ButtonClass() { JLabel background = new JLabel(new ImageIcon("image.png")); background.setLayout(new BorderLayout()); setContentPane(background); setTitle("Background with buttons"); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); JPanel top = new JPanel(); top.add(label); add(top, BorderLayout.NORTH); JPanel bottom = new JPanel(); bottom.add(b1); bottom.add(b2); bottom.add(b3); bottom.add(b4); add(bottom, BorderLayout.SOUTH); //pack(); setVisible(true); }
Also,
add("North", top);
is a deprecated method. Instead useadd(top, BorderLayout.NORTH)
and same foradd(bottom, BorderLayout.SOUTH)
Also, Swing apps should be run on the Event Dispatch Thread. You can do so by wrapping the code in your
main
with aSwingUtilities.invokeLater...
public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ButtonClass(); } }); }
Also, you should set the panel's opaque property to false, if you want the image to show behind them.
top.setOpaque(false); bottom.setOpaque(false);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonClass extends JFrame
implements ActionListener {
JButton b1 = new JButton("button1");
JButton b2 = new JButton("button2");
JButton b3 = new JButton("button3");
JButton b4 = new JButton("button4");
JLabel label = new JLabel("buttons:");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonClass();
}
});
}
public ButtonClass() {
label.setForeground(Color.WHITE);
JLabel background = new JLabel(new ImageIcon(getClass().getResource("/resources/space.png")));
background.setLayout(new BorderLayout());
setContentPane(background);
setTitle("Background with buttons");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
JPanel top = new JPanel();
top.setOpaque(false);
top.add(label);
add(top, BorderLayout.NORTH);
JPanel bottom = new JPanel();
bottom.setOpaque(false);
bottom.add(b1);
bottom.add(b2);
bottom.add(b3);
bottom.add(b4);
add(bottom, BorderLayout.SOUTH);
setSize(400, 300);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {}
}