Reputation: 37
So I am trying put images on to of each other and because I'm storing those images on jbuttons, I want to know if there is a way to put jbuttons on top on my already existing jbuttons. Any help please.
Edit :
So let's say I have a
Jbutton b = new JButton()
and I set it an image icon.
then I have another
JButton x = new JButton()
and set it an image icon.
These JButtons contain two different icons. and I want the images to overlap each other. I want both images to show with the bottom button being the larger image and the button on top having a smaller size. Not sure if this is clear.
Upvotes: 0
Views: 1250
Reputation: 2682
The simplest solution is this
JButton j1=new JButton("a");
j1.setLayout(new BorderLayout());
j1.setBackground(Color.red);
add(j1);
JButton j2=new JButton("b");
j2.setBackground(Color.yellow);
j1.add("Center", j2);
--
Although generally not to be used, the null layout is a solution here if you want to specify specific location and size:
JButton j1=new JButton("a");
j1.setLayout(null);
j1.setBackground(Color.red);
JButton j2=new JButton("b");
j2.setBackground(Color.yellow);
j2.setBounds(100, 100, 50, 50);
j1.add(j2);
add(j1);
Upvotes: -1
Reputation: 324098
You can use the OverlayLayout
to stack components on top of one another.
import java.awt.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
setLayout( new OverlayLayout(this) );
JButton child = new JButton( new ImageIcon("child.jpg") );
child.setAlignmentX(JButton.CENTER_ALIGNMENT);
child.setAlignmentY(JButton.CENTER_ALIGNMENT);
JButton parent = new JButton( new ImageIcon("parent.jpg") );
parent.setAlignmentX(JButton.CENTER_ALIGNMENT);
parent.setAlignmentY(JButton.CENTER_ALIGNMENT);
add(child);
add(parent);
}
@Override
public boolean isOptimizedDrawingEnabled()
{
return false;
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
Normally painting code assumes layout managers layout the components in 2 dimensions. However in this case you need to override the isOptimizedDrawingEnabled()
method to indicate components are stacked. This makes painting a little less efficient but is needed to make sure components are painted properly.
Upvotes: 2