Benhemin80
Benhemin80

Reputation: 1

Using Images as Buttons, getting a Blank Screen

I'm trying to add an Image button to my GUI but all I get is a blank screen. Can anyone show me whats wrong with my code? This is what I have so far.

package fallingStars;

import java.awt.*;
import java.awt.event.*;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JFrame 
{
    private JLabel label;
    private JButton button;
    private JPanel buttonPanel;

    public static void startButton() 
    {
        ImageIcon start = new ImageIcon("Start.png");
        JButton play = new JButton(start);
        play.setBounds(150,100,100,50);
    }

    public static void main(String args[]) 
    {
        GUI gui = new GUI();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(300, 500);
        gui.setVisible(true);
        gui.setResizable(false);
        gui.setTitle("Falling Stars");

        JPanel panel = new JPanel();

        startButton();

    }
}

Upvotes: 0

Views: 184

Answers (2)

Adarsh Singhal
Adarsh Singhal

Reputation: 362

First of all just insert an ImageIcon in JLabel. If you want an image act as button, you have to add MouseListener & implement mouseClicked() as I did.

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;


public class MyFrame extends JFrame{
    private JLabel label;
    private static MyFrame frame;

    public MyFrame(){
        initComponent();
        label.addMouseListener(new MouseListener(){

            @Override
            public void mouseClicked(MouseEvent arg0) {
                JOptionPane.showMessageDialog(frame, "You just clicked the image");         
            }

            @Override
            public void mouseEntered(MouseEvent arg0) {}
            @Override
            public void mouseExited(MouseEvent arg0) {}
            @Override
            public void mousePressed(MouseEvent arg0) {}
            @Override
            public void mouseReleased(MouseEvent arg0) {}

        });
    }

    private void initComponent() {
        this.setSize(400, 400);
        this.setLocationRelativeTo(null);
        label = new JLabel();
        label.setIcon(new ImageIcon(getClass().getResource("res/image.png")));
        add(label);     
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible (true);
    }

    public static void main(String[] args) {
        frame = new MyFrame();
    }
}

Upvotes: 1

loafy
loafy

Reputation: 105

You have to add the JButton to the container using container.add(JButton);

You're going to get a blank screen if you don't actually add it :)

Upvotes: 2

Related Questions