Reputation:
I have this JFrame below:
public class TestJFrame extends JFrame {
public RecyclingMachinesGui(String title) {
super (title);
Container container = getContentPane();
container.setLayout(new FlowLayout());
Panel r = new Panel();
Jbutton j = new JButton("Recycle Item");
r.add(j);
container.add(r);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(500,500);
setVisible(true);
}
private class Panel extends JPanel {
private BufferedImage image;
public Panel() {
try {
image = ImageIO.read(new File("./temp.png"));
}catch (IOException e) {
e.getMessage().toString();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
}
In the above code in my main method when I run new TestJFrame()
for some reason I only see the JButton j
inside my Panel
(which I added to my container) and do not see an image inside the panel. Is the paintComponent
method in my Panel not being called?
I want to have a picture on the top and the button on the bottom of the Panel. Can anyone explain why this is not happening?
Upvotes: 0
Views: 1171
Reputation: 10127
The image in your Panel
is not displayed,
because the Panel
has no proper preferred size.
Therefore the LayoutManager (the FlowLayout
) doesn't know which size
to give to the Panel, and gives it the size of a very small square.
Hence, your Panel
's paintComponent
is actually called,
but it is painting only on an invisible small area,
You can fix it easily in your Panel
's constructor,
by calling setPreferredSize
immediately after loading your image:
image = ImageIO.read(new File("./temp.png"));
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
Upvotes: 1
Reputation: 347284
I want to have a picture on the top and the button on the bottom of the Panel. Can anyone explain why this is not happening?
Okay, so you don't really need to paint the image yourself, a JLabel
will do very nicely itself, then you just need to use a BorderLayout
to add the label to the center and the button to the south, for example...
public class TestJFrame extends JFrame {
public RecyclingMachinesGui(String title) {
super (title);
Container container = getContentPane();
container.setLayout(new FlowLayout());
JPanel r = new JPanel(new BorderLayout());
try {
r.add(new JLabel(new ImageIcon(ImageIO.read(new File("./temp.png")))));
}catch (IOException e) {
e.getMessage().toString();
}
Jbutton j = new JButton("Recycle Item");
r.add(j, BorderLayout.SOUTH);
container.add(r);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(500,500);
setVisible(true);
}
}
Your current approach would place the button OVER the image, which is great if you want to use the image as a background
Upvotes: 1