Reputation: 49
I'm trying to create an interface with Swing.
This is my code:
public class JavaApplication30
{
public static void main(String[] args) throws IOException
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.X_AXIS));
frame.setPreferredSize(new Dimension(1280, 720));
frame.setResizable(false);
frame.setContentPane(new JPanel()
{
BufferedImage image = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication29\\src\\eila.jpg"));
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, 1280, 720, this);
}
});
JPanel a = new JPanel();
a.setAlignmentX(Component.LEFT_ALIGNMENT);
a.setPreferredSize(new Dimension(150, 500));
a.setMaximumSize(new Dimension(150, 500));
a.setOpaque(false);
a.add(Box.createRigidArea(new Dimension(5,50)));
JButton amico = new JButton("Amico");
a.add(amico);
a.add(Box.createRigidArea(new Dimension(5,20)));
amico.setPreferredSize(new Dimension(150, 50));
JButton bello = new JButton("Bello");
a.add(bello);
a.add(Box.createRigidArea(new Dimension(5,20)));
bello.setPreferredSize(new Dimension(150, 50));
JButton compagno = new JButton("Compagno");
a.add(compagno);
compagno.setPreferredSize(new Dimension(150, 50));
frame.getContentPane().add(a);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ImagePanel extends JComponent {
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
I set the button alignment to the left, but my buttons are still centered.
This didn't happen without paintComponent for the background.
Why is this? How can I align the buttons on the left?
Upvotes: 0
Views: 76
Reputation: 324098
I set Alignment to left, but my buttons are centered
The setAlignmentX(...) is only a hint for how the "panel" should be aligned in its parent panel. When you add the buttons to the panel, what matters is the layout manager of the panel.
By default a JPanel uses a FlowLayout
. Also by default when you create a FlowLayout
, the components added to the panel are centered aligned
in the space of the panel.
Change the layout manager to be a FlowLayout
with the components left aligned
. Read the FlowLayout
API for the proper constructor to use.
Also, you can provide a default gap between the buttons, so there is no need for the Box.createRigidArea(...). The component is really meant to be used when you use a BoxLayout
.
Upvotes: 1