JButton overlay on JLabel in Java Swing?

Can I overlay a button in Swing?

For example, if I have a JLabel with an image and no text, and I want to overlay my button on this JLabel. The label is defined as follows:

myLabel = new javax.swing.JLabel(new ImageIcon( myPicture ));  

If not, then any ideas how I can understand this, thanks.

EDIT: Actually, I read about adding JPanel to JLabel, when I add a panel with a button layout, it compiles fine, but nothing is visible, just JLabel with an image

UPDATE: As suggested by @ paranoid-android, I somehow solved my problem. However, I still need to know how I can adjust the positions of the components overlaid on top of JLabel, since I don't have much control (perhaps because I usually use netbeans to draw layouts, and this will require hard coding).

Something like this worked:

ImagePanel(Image image, int id) {
    this.image = image;
    this.tile = false;

    JButton backButton = new JButton();
    JButton nextButton = new JButton();
    backButton.setText(" BACK ");
    nextButton.setText(" NEXT ");


    add(backButton);
    add(nextButton);

};

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
+5
source share
2 answers

You can do this with JLayeredPane, although, if I understand correctly, the absolute best way to do this is to override paintComponent:

// as part of your JPanel
@Override
public void paintComponent(Graphics g){
     super.paintComponent(g);
     g.drawImage(background, 0, 0, this);
}

You can then add components to the panel as you like, without need JLabel.

+9
source

All Articles