How can I make the JButton visible?
1) When no progressive background is turned on: JButton is showing
2) When no progressive background is turned on, JButton is pressed still showing no flicker:
3) When progressive background is turned on, JButton is invisible and on pressing in this I see flicker and JButton() appears and again hides auto. << Problem is here, so how can I fix it?
import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class ButtonTest extends JWindow implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private SoftJButton softButton1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ButtonTest j = new ButtonTest();
j.createAndShowGUI();
}
});
}
public void createAndShowGUI() {
softButton1 = new SoftJButton("Transparent Button");
softButton1.setBackground(Color.GREEN);
softButton1.setAlpha(0.5f);
softButton1.setDoubleBuffered(true);
this.setLayout(new BorderLayout());
this.setBounds(100, 30, 200, 100);
this.setBackground(new Color(0, 0, 0, 255));
this.setVisible(true);
add(softButton1);
}
@Override
public void paint(Graphics g) {
super.paint(g);
}
public void mouseDragged(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static class SoftJButton extends JButton {
private static final JButton lafDeterminer = new JButton();
private static final long serialVersionUID = 1L;
private boolean rectangularLAF;
private float alpha = 1f;
public SoftJButton() {
this(null, null);
}
public SoftJButton(String text) {
this(text, null);
}
public SoftJButton(String text, Icon icon) {
super(text, icon);
setOpaque(false);
setFocusPainted(false);
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
@Override
public void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
}
@Override
public void updateUI() {
super.updateUI();
lafDeterminer.updateUI();
rectangularLAF = lafDeterminer.isOpaque();
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…