Don't set bounds. Learn to use Layout Managers.
Paint the image on a
JPanel
instead of using aJLabel
Put the
JButton
on theJPanel
. Give thatJPanel
aGridBadLayout
Override the
getPreferredSize()
of theJPanel
.To switch between images you can use a flag like
boolean icon1, icon2, icon3;
. and repaint theJPanel
themouseXxx
. Something like thispublic void mouseClicked(MouseEvent e) { icon1 = true; icon2 = false; icon3 = false; imagePanel.repaint(); } .... protected void paintComponent(Graphics g) { if (icon1) { g.drawImage(image1, .....); } if (icon2) { ... } if (icon3) { ... } }
pack()
your frame.Use Java naming convention. variables start with lower case letters.
Here's an example
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.*;
import java.util.logging.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestButtonOverImage {
public TestButtonOverImage() {
JFrame frame = new JFrame("Test Card");
frame.add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestButtonOverImage();
}
});
}
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel() {
setLayout(new GridBagLayout());
add(new JButton("StackOverflow Button"));
try {
img = ImageIO.read(new URL("http://d8u1nmttd4enu.cloudfront.net/designs/logo-stackoverflow-logo-design-99designs_447080~36d200d82d83d7b2e738cebd2a48de07180cef3a_largecrop"));
} catch (MalformedURLException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 100, 100, 300, 300, this);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
}