KyleKW
KyleKW

Reputation: 300

Use JButton as an Image

So, the problem I'm facing is that I want to take JButton's image model, and use it as an image instead. I have not worked with implementing Icons in swing before, so I decided to do some searching. However, I couldn't find anything to make sense what is happening here.

I've tried the following code:

JButton button = new JButton("Text");
JLabel buttonIcon = new JLabel(button.getIcon());

However, when I go to display the JLabel, nothing appears. Is this interaction wrong?

I would also be satisfied with saving JButton's Model as an image format, and importing it as such.

Any help would be greatly appreciated!

Upvotes: 0

Views: 482

Answers (2)

Lukas Rotter
Lukas Rotter

Reputation: 4188

So if you want to snapshot a visible component and display it inside a JLabel, you can

  1. Set the button's size to it's preferredSize.
  2. Create a BufferedImage.
  3. Call button.paint(image.createGraphics()) to draw the button onto the image.
  4. Set the Icon of the JLabel to a new one containing the image.

Here's an example (thanks to camickr who helped me make the process cleaner):

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Example {

    public void createAndShowGUI() {
        JButton button = new JButton("Text");
        button.setSize(button.getPreferredSize());

        JLabel label = new JLabel();
        label.setIcon(new ImageIcon(snapshot(button)));

        JPanel contentPane = new JPanel();
        contentPane.add(label);

        JFrame frame = new JFrame();
        frame.setContentPane(contentPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private BufferedImage snapshot(Component component) {
        BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        component.paint(image.createGraphics());
        return image;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new Example().createAndShowGUI());
    }
}

Upvotes: 6

Adam
Adam

Reputation: 33

Try this

File imgFile=new File("img.jpeg");
Image img=ImageIO.read(imgFile);
ImageIcon icon=new ImageIcon(img);
JButton button=new JButton();
JLabel label=new JLabel();
button.setIcon(icon);
label.setIcon(button.getIcon());

Upvotes: -1

Related Questions