Reputation: 27
I'm trying to display a .png picture using a GUI. But I'm having trouble with the pictures displaying. I think I've isolated where I'm messing up in my instructions but can't seem to find a working solution.
I am told in my instructions to...
It seems like I need to create a method to initialize imgButton. But if I did that wouldn't I need to create a new variable for each Icon image? For instance
imgButton = new JButton(image1);
final JButton imgButton2 = new JButton(image2);
final JButton imgButton3 = new JButton(image3);
Any help that I can get would be very appreciated. Thanks.
package ImageButton.Downloads;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ImageButton extends JFrame
{
private final JButton imgButton;
private final Icon clickImage;
public ImageButton()
{
JFrame frame = new JFrame();
frame.setTitle("Lab Button");
Icon image1 = new ImageIcon(getClass().getResource("Image1.png"));
Icon image2 = new ImageIcon(getClass().getResource("Image2.png"));
clickImage = new ImageIcon(getClass().getResource("Image3.gif"));
imgButton = new JButton(image1);
imgButton.setRolloverIcon(image2);
}
}
package ImageButton.Downloads;
import javax.swing.JFrame;
public class ImageButtonApp
{
public ImageButtonApp()
{
// TODO Auto-generated constructor stub
}
public static void main(String[] args)
{
ImageButton imageButton = new ImageButton();
imageButton.setSize(660, 660);
imageButton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
imageButton.setVisible(true);
}
}
Upvotes: 1
Views: 336
Reputation: 285403
You're creating two JFrames, displaying one of them but adding your JButton to none of them. In other words, your code ignores this rec:
Add the imgButton to this (ImageButton, which is a JFrame)
Solution: use only one JFrame, your class as per your instructions, add your JButton to it or to a JPanel that is added to the JFrame, and display it.
Specifically, change this:
JFrame frame = new JFrame(); // extra JFrame that's never used!
frame.setTitle("Lab Button");
to this:
super("Lab Button");
and add an add(imgButton);
at the end of the constructor.
Upvotes: 3