Hello-
I am having an image display problem, which most likely has a really obvious answer, however I have spent hours stumbling through this one and have got nowhere.
In the compiled code below, I have a Label, Button, and Image. When I run it as is, the label and button appear and no image. If I cut and paste the paint() method in the ImagePanel class, I get the opposite (an image but no label or button). How can I easily display all three?
Your help or advise would be extremely appreciated.
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
import javax.swing.event.*;
import java.awt.event.*;
public class TestFrame extends JFrame{
private JButton okButton = new JButton("OK");
privateJLabel jl1 = new JLabel("hey");
private Image image;
public TestFrame(){
setSize(400, 200);
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage("image.gif");
setIconImage(image);
Container cp = getContentPane();
JPanel jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JPanel textPanel = new JPanel();
textPanel.setLayout(new GridLayout(6,1));
textPanel.add(jl1);
gbc.gridx = 1;
gbc.gridy = 0;
jp.add(textPanel, gbc);
gbc.gridx = 0; gbc.gridy = 0;
ImagePanel imagePanel = new ImagePanel(image);
imagePanel.repaint();
jp.add(imagePanel, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
JPanel okPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
okPanel.add(okButton);
jp.add(okPanel, gbc);
okButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent AE){
setVisible(false);
}
});
repaint();
cp.add(jp);
}
public void paint(Graphics g){
g.drawImage(image,30,30,this);
}
public static void main(
String args[]){
TestFrame ig = new TestFrame();
ig.pack();
ig.setVisible(true);
}
}
class ImagePanel extends JPanel {
Image image;
public ImagePanel(Image image) {
this.image = image;
}
public void paintComponent(Graphics g) {
super.paintComponent(g); //paint background
//Draw image at its natural size first.
g.drawImage(image, 0, 0, 50, 50, this); //85x62 image
}
}