I'm currently working on some swing app.
When I try to make JButton
to show just its Icon however it starts
to overlap two JButton Icon's.
Does anyone have any idea what might have caused it (I have one icon
that says 'yes'
, the second says 'no'
,
if I move mouse over one button(let's say it is 'yes' button) and
then do it over the other ( 'no' button in this case )
'yes'
gets painted over 'no'
.
NOTE: Added the a solution to the code it is marked by comment
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class RunnerTestButtons {
public static void main(String[] args) {
JFrame frame =new JFrame("Game");
JPanel panel =new JPanel();
panel.setLayout(new GridLayout(2, 1));
frame.setPreferredSize(new Dimension(640, 480));
panel.setBackground(new Color(0, 255, 0));
JLabel label =new JLabel("SomeText",SwingConstants.CENTER);
//here
label.setOpaque(false);
JPanel panel2 =new JPanel();
//and here
panel2.setOpaque(false);
panel.add(label);
panel.add(panel2);
panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
JButton lab1=new JButton("txt");
JButton lab2=new JButton("Boo");
lab1.setAlignmentX(Box.CENTER_ALIGNMENT);
lab2.setAlignmentX(Box.CENTER_ALIGNMENT);
lab1.revalidate();
lab2.revalidate();
lab1.repaint();
lab2.repaint();
panel2.add(Box.createHorizontalGlue());
panel2.add(lab1);
panel2.add(Box.createHorizontalGlue());
panel2.add(lab2);
panel2.add(Box.createHorizontalGlue());
lab1.setOpaque(false);
lab2.setOpaque(false);
lab1.setContentAreaFilled(false);
lab2.setContentAreaFilled(false);
lab1.setBorderPainted(false);
lab2.setBorderPainted(false);
lab1.setBorder(null);
lab2.setBorder(null);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
lab1.setBackground(new Color(0, 0, 0, 0));
The problem is that you are trying to make the button transparent. You should NOT do this by playing with the opacity of the background.
For full transparency the easiest solution is to just make the button non-opaque.
So you should be doing something like:
//lab1.setBackground(new Color(0, 0, 0, 0));
lab1.setOpaque(false);
lab1.setContentAreaFilled(false);
Check out Backgrounds With Transparency for more information on why your original approach is a problem and the solutions when using partial transparency.
So as you can see the original code you posted had nothing to do with the problem, which is why a proper SSCCE should be posted with every question.