Two things you can try
- Remove the BorderLayout from this
imgPane.setLayout(new BorderLayout());
If one doesn't work try to add the label to the Panel instead of the
imgPane
panel1.add(img, BorderLayout.CENTER);
Also, panel2 looks unnecessary. Get rid of that and just add panel1 to the frame
Try setting the alignment
img.setAlignmentX(JLabel.CENTER_ALIGNMENT); img.setAlignmentX(JLabel.CENTER_ALIGNMENT); panel1.add(img, BorderLayout.CENTER);
Here's the code I used to reconstruct the desired result
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class HangManAlign extends JPanel {
public HangManAlign() {
JLabel guess = new JLabel("Guess");
JTextField jtfGuess = new JTextField(3);
JLabel label = new JLabel(new ImageIcon("images/Xpo9R.png"));
JLabel bottom = new JLabel("Letters Used __ __ __ __ __ __ __ __ __");
bottom.setHorizontalAlignment(JLabel.CENTER);
JPanel topPanel = new JPanel();
topPanel.add(guess);
topPanel.add(jtfGuess);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.NORTH);
add(label, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
setBorder(new EmptyBorder(20, 20, 20, 20));
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new HangManAlign());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I Copied your entire image and cut it down to size, so you can see that it's centered. Here's the image I used