I'm trying to have Aero Glass look in my JPanel. Is it possible do such a thing?
How to add Aero effect to JFrame - like this picture?
please read tutorials How to Create Translucent, How to Create Translucent and Shaped Windows, then by using javax.swing.Timer is possible (for example)
import java.awt.event.*;
import java.awt.Color;
import java.awt.AlphaComposite;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class ButtonTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest().createAndShowGUI();
}
});
}
private JFrame frame;
private JButton opaqueButton1;
private JButton opaqueButton2;
private SoftJButton softButton1;
private SoftJButton softButton2;
public void createAndShowGUI() {
opaqueButton1 = new JButton("Opaque Button");
opaqueButton2 = new JButton("Opaque Button");
softButton1 = new SoftJButton("Transparent Button");
softButton2 = new SoftJButton("Transparent Button");
opaqueButton1.setBackground(Color.GREEN);
softButton1.setBackground(Color.GREEN);
frame = new JFrame();
frame.getContentPane().setLayout(new java.awt.GridLayout(2, 2, 10, 10));
frame.add(opaqueButton1);
frame.add(softButton1);
frame.add(opaqueButton2);
frame.add(softButton2);
frame.setSize(567, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Timer alphaChanger = new Timer(30, new ActionListener() {
private float incrementer = -.03f;
#Override
public void actionPerformed(ActionEvent e) {
float newAlpha = softButton1.getAlpha() + incrementer;
if (newAlpha < 0) {
newAlpha = 0;
incrementer = -incrementer;
} else if (newAlpha > 1f) {
newAlpha = 1f;
incrementer = -incrementer;
}
softButton1.setAlpha(newAlpha);
softButton2.setAlpha(newAlpha);
}
});
alphaChanger.start();
Timer uiChanger = new Timer(3500, new ActionListener() {
private LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
private int index = 1;
#Override
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(laf[index].getClassName());
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception exc) {
exc.printStackTrace();
}
index = (index + 1) % laf.length;
}
});
uiChanger.start();
}
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();
}
}
}
Maybe this blog post will help you more. The author describes an approach where he rebuilds the whole Windows Aero effect. Here is his working example:
(source: centigrade.de)
Related
I want to have transparent panels in my GUI (if like Windows 7 window headers, it is better).
Before I have used com.sun.awt.AWTUtilities as
AWTUtilities.setWindowOpacity(frame, (float)0.90);
but its parameter is a window like JFrame and couldn't be used for JPanel.
Also I want to have effects on JPanel or JLabel for example luminescence, as is on Windows 7 header buttons. Any other interesting effect is also helpful for me.
Please see the tutorials How to Create Translucent and Shaped Windows and* How to Create Translucent and Shaped Windows*. Follow the links to excellent example depots by #camickr.
For example,
import java.awt.event.*;
import java.awt.Color;
import java.awt.AlphaComposite;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class ButtonTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest().createAndShowGUI();
}
});
}
private JFrame frame;
private JButton opaqueButton1;
private JButton opaqueButton2;
private SoftJButton softButton1;
private SoftJButton softButton2;
public void createAndShowGUI() {
opaqueButton1 = new JButton("Opaque Button");
opaqueButton2 = new JButton("Opaque Button");
softButton1 = new SoftJButton("Transparent Button");
softButton2 = new SoftJButton("Transparent Button");
opaqueButton1.setBackground(Color.GREEN);
softButton1.setBackground(Color.GREEN);
frame = new JFrame();
frame.getContentPane().setLayout(new java.awt.GridLayout(2, 2, 10, 10));
frame.add(opaqueButton1);
frame.add(softButton1);
frame.add(opaqueButton2);
frame.add(softButton2);
frame.setSize(567, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Timer alphaChanger = new Timer(30, new ActionListener() {
private float incrementer = -.03f;
#Override
public void actionPerformed(ActionEvent e) {
float newAlpha = softButton1.getAlpha() + incrementer;
if (newAlpha < 0) {
newAlpha = 0;
incrementer = -incrementer;
} else if (newAlpha > 1f) {
newAlpha = 1f;
incrementer = -incrementer;
}
softButton1.setAlpha(newAlpha);
softButton2.setAlpha(newAlpha);
}
});
alphaChanger.start();
Timer uiChanger = new Timer(3500, new ActionListener() {
private LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
private int index = 1;
#Override
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(laf[index].getClassName());
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception exc) {
exc.printStackTrace();
}
index = (index + 1) % laf.length;
}
});
uiChanger.start();
}
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();
}
}
}
If you have time I recommend you go through this Filty Rich Clients. By using this book you can learn to create stunning visual and animated effects with Swing and Java 2D. Learn graphics and animation fundamentals as well as advanced rendering techniques.
EDIT:
To creat transparent panels call
setOpaque(false)
It'll pass off painting the background to its parent, which may draw its own background.
You can do a screen capture and then use that to paint the background of the panel.
I have this following class, which refresh a jpeg file in layer 0 and layer 1 is used to draw/paint/sketch up anything related to smash things. But in my drawing when I want to do a thin line, it breaks. Because the mouse cursor movement needs to be slower.
How to resolve on fast mouse move, that the line remains joined?
Annotation.java
package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Annotation {
// Image
private static Image backgroundImage;
private static BufferedImage _bufImage = null;
// Enum
public static enum Shape { RECTANGLE, OVAL, LINE }
private static enum State { IDLE, DRAGGING }
private static final Shape INIIIAL_SHAPE = Shape.RECTANGLE;
private static final Color INITIAL_COLOR = Color.RED;
private static Shape _shape = INIIIAL_SHAPE;
private static Color _color = INITIAL_COLOR;
private static State _state = State.IDLE;
private static Point _start = null;
private static Point _end = null;
// JPanel
private static JPanel p;
private static JPanel mp;
/* Run: */
public static void main(String args[]) {
c();
}
/* GUI */
public static void c() {
try {
backgroundImage = ImageIO.read(new File("/var/tmp/test.jpeg"));
} catch (IOException e) {
e.printStackTrace();
}
myTimer();
loadAnnotation();
loadBackground();
JFrame f;
f = new JFrame();
f.setLayout(new BorderLayout());
f.add(mp);
f.pack();
f.setVisible(true);
}
/* 5 seconds to load picture */
public static void myTimer() {
javax.swing.Timer t = new javax.swing.Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
backgroundImage = ImageIO.read(new File("/var/tmp/test.jpeg"));
mp.repaint();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
/* Layer 0:
* Load background picture */
public static void loadBackground() {
mp = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, 1024, 600, null);
}
public Dimension getPreferredSize() {
return new Dimension(1024, 600);
}
};
mp.add(p);
}
/* Layer 1:
* Annotation: Draw on top of background picture anything! */
public static void loadAnnotation() {
p = new JPanel() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.RED);
if (_bufImage == null) {
int w = this.getWidth();
int h = this.getHeight();
_bufImage = new BufferedImage(1024,600, BufferedImage.TRANSLUCENT);
Graphics2D gc = _bufImage.createGraphics();
}
g2.drawImage(_bufImage, null, 0, 0);
if (_state == State.DRAGGING) {
g2.drawLine(_start.x, _start.y, _end.x , _end.y);
}
}
public Dimension getPreferredSize() {
return new Dimension(1024, 600);
}
};
p.setLayout(new FlowLayout());
p.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent me) {
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
//_state = State.IDLE;
_state = State.IDLE;
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
});
p.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent me) {
System.out.println("drag");
_state = State.DRAGGING;
_start = me.getPoint();
_end = _start;
if (_state == State.DRAGGING) {
Graphics2D g2 = _bufImage.createGraphics();
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(90));
g2.fillOval(_start.x, _start.y, 10, 10);
p.repaint();
}
}
#Override
public void mouseMoved(MouseEvent me) {
System.out.println("move");
}
});
JButton pm = new JButton("+");
pm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
p.add(pm);
p.setOpaque(true);
}
}
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Annotation {
// Image
private static Image backgroundImage;
private static BufferedImage _bufImage = null;
// Enum
public static enum Shape { RECTANGLE, OVAL, LINE }
private static enum State { IDLE, DRAGGING }
private static final Shape INIIIAL_SHAPE = Shape.RECTANGLE;
private static final Color INITIAL_COLOR = Color.RED;
private static Shape _shape = INIIIAL_SHAPE;
private static Color _color = INITIAL_COLOR;
private static State _state = State.IDLE;
private static Point _start = null;
private static Point _end = null;
// JPanel
private static JPanel p;
private static JPanel mp;
/* Run: */
public static void main(String args[]) {
c();
}
/* GUI */
public static void c() {
try {
URL url = new URL("http://pscode.org/media/stromlo2.jpg");
backgroundImage = ImageIO.read(url);
} catch (Exception e) {
e.printStackTrace();
}
loadAnnotation();
loadBackground();
JFrame f;
f = new JFrame();
f.setLayout(new BorderLayout());
f.add(mp);
f.pack();
f.setVisible(true);
}
/* Layer 0:
* Load background picture */
public static void loadBackground() {
mp = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
}
public Dimension getPreferredSize() {
return new Dimension(backgroundImage.getWidth(this), backgroundImage.getHeight(this));
}
};
mp.add(p);
}
/* Layer 1:
* Annotation: Draw on top of background picture anything! */
public static void loadAnnotation() {
p = new JPanel() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.RED);
if (_bufImage == null) {
int w = this.getWidth();
int h = this.getHeight();
_bufImage = new BufferedImage(1024,600, BufferedImage.TRANSLUCENT);
Graphics2D gc = _bufImage.createGraphics();
}
g2.drawImage(_bufImage, null, 0, 0);
if (_state == State.DRAGGING) {
g2.drawLine(_start.x, _start.y, _end.x , _end.y);
}
}
public Dimension getPreferredSize() {
return new Dimension(1024, 600);
}
};
p.setLayout(new FlowLayout());
p.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent me) {
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
//_state = State.IDLE;
_state = State.IDLE;
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
});
p.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent me) {
_state = State.DRAGGING;
_end = me.getPoint();
if (_state == State.DRAGGING) {
Graphics2D g2 = _bufImage.createGraphics();
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(2));
g2.drawLine(_start.x, _start.y, _end.x, _end.y);
p.repaint();
}
_start = _end;
}
#Override
public void mouseMoved(MouseEvent me) {
//System.out.println("move");
_start = me.getPoint();
}
});
JButton pm = new JButton("+");
pm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
p.add(pm);
p.setOpaque(true);
}
}
I solved this problem by drawing rectangles between points, using the Stroke size (Basic Stroke) for height. It sounds like an icky solution but it does pretty well in reality
Is it possible to add multiple GlassPanes for a single JFrame, or do I have to use the uncomfortable LayeredPane with the Opacity attribute.
I have attached some code that shows what I want to do (provided by #camickr).
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class MultiplayGlassPane {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame("frameTitle");
private JPanel fPanel = new JPanel();
private Random random = new Random();
private final static Border MESSAGE_BORDER = new EmptyBorder(10, 10, 10, 10);
private JLabel message = new JLabel();
private ArrayList<Star> stars = new ArrayList<Star>();
public MultiplayGlassPane() {
MyGlassPane glass = new MyGlassPane();
for (int i = 0; i < 35; i++) {
Star star = new Star(new Point(random.nextInt(580), random.nextInt(550)));
star.setColor(Color.orange);
star.setxIncr(-3 + random.nextInt(7));
star.setyIncr(-3 + random.nextInt(7));
glass.add(star);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(glass, BorderLayout.CENTER);
frame.setLocation(20, 20);
frame.pack();
frame.setVisible(true);
DisabledGlassPane1 glassPane = new DisabledGlassPane1();
JRootPane rootPane = SwingUtilities.getRootPane(frame);
rootPane.setGlassPane(glassPane);
glassPane.activate("");
}
private class MyGlassPane extends JLabel {
private static final long serialVersionUID = 1L;
private ArrayList<Star> stars = new ArrayList<Star>();
private javax.swing.Timer timer = new javax.swing.Timer(20, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Star star : stars) {
star.move();
}
repaint();
}
});
public void stopAnimation() {
if (timer.isRunning()) {
timer.stop();
}
}
public void startAnimation() {
if (!timer.isRunning()) {
timer.start();
}
}
#Override
public void addNotify() {
super.addNotify();
timer.start();
}
#Override
public void removeNotify() {
super.removeNotify();
timer.stop();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(new Dimension(620, 620));
}
public MyGlassPane() {
this.setPreferredSize(new Dimension(620, 620));
}
public void add(Star star) {
stars.add(star);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Star star : stars) {
g.setColor(star.getColor());
g.fillPolygon(star);
}
}
}
class DisabledGlassPane1 extends JComponent implements KeyListener {
private static final long serialVersionUID = 1L;
public DisabledGlassPane1() {
setOpaque(false);
Color base = UIManager.getColor("inactiveCaptionBorder");
Color background = new Color(base.getRed(), base.getGreen(), base.getBlue(), 128);
setBackground(background);
setLayout(new GridBagLayout());
add(message, new GridBagConstraints());
message.setOpaque(true);
message.setBorder(MESSAGE_BORDER);
addMouseListener(new MouseAdapter() {
});
addMouseMotionListener(new MouseMotionAdapter() {
});
addKeyListener(this);
setFocusTraversalKeysEnabled(false);
Random random = new Random();
for (int i = 0; i < 50; i++) {
Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
star.setColor(Color.magenta);
star.setxIncr(-3 + random.nextInt(7));
star.setyIncr(-3 + random.nextInt(7));
add(star);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Star star : stars) {
g.setColor(star.getColor());
g.fillPolygon(star);
}
}
#Override
public void setBackground(Color background) {
super.setBackground(background);
Color messageBackground = new Color(background.getRGB());
message.setBackground(messageBackground);
}
public void keyPressed(KeyEvent e) {
e.consume();
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
e.consume();
}
public void activate(String text) {
if (text != null && text.length() > 0) {
message.setVisible(true);
message.setText(text);
message.setForeground(getForeground());
} else {
message.setVisible(false);
}
setVisible(true);
//setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
requestFocusInWindow();
}
public void deactivate() {
setCursor(null);
setVisible(false);
}
private javax.swing.Timer timer = new javax.swing.Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Star star : stars) {
star.move();
}
repaint();
}
});
public void stopAnimation() {
if (timer.isRunning()) {
timer.stop();
}
}
public void startAnimation() {
if (!timer.isRunning()) {
timer.start();
}
}
#Override
public void addNotify() {
super.addNotify();
timer.start();
}
#Override
public void removeNotify() {
super.removeNotify();
timer.stop();
}
public void add(Star star) {
stars.add(star);
}
}
private class Star extends Polygon {
private static final long serialVersionUID = 1L;
private Point location = null;
private Color color = Color.YELLOW;
private int xIncr, yIncr;
static final int WIDTH = 600, HEIGHT = 600;
Star(Point location) {
int x = location.x;
int y = location.y;
this.location = location;
this.addPoint(x, y + 8);
this.addPoint(x + 8, y + 8);
this.addPoint(x + 11, y);
this.addPoint(x + 14, y + 8);
this.addPoint(x + 22, y + 8);
this.addPoint(x + 17, y + 12);
this.addPoint(x + 21, y + 20);
this.addPoint(x + 11, y + 14);
this.addPoint(x + 3, y + 20);
this.addPoint(x + 6, y + 12);
}
public void setColor(Color color) {
this.color = color;
}
public void move() {
if (location.x < 0 || location.x > frame.getContentPane().getWidth() - 20) {
xIncr = -xIncr;
}
if (location.y < 0 || location.y > frame.getContentPane().getHeight() - 20) {
yIncr = -yIncr;
}
translate(xIncr, yIncr);
location.setLocation(location.x + xIncr, location.y + yIncr);
}
public void setxIncr(int xIncr) {
this.xIncr = xIncr;
}
public void setyIncr(int yIncr) {
this.yIncr = yIncr;
}
public Color getColor() {
return color;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MultiplayGlassPane Mpgp = new MultiplayGlassPane();
}
});
}
}
Look at http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html for an explanation on Root panes and what the Glass pane actually is.
The glass pane is just a convenient way to add a component which has the size of the Root Pane, and which blocks all input events. This allows you to catch any interaction with your components to create a "Please wait..." screen.
There is only a single glass pane per root container. You cannot layer glass panes.
You can replace the contents of the glass pane by something else if you want to layer something over the current glass pane. You can also set a JPanel as a glass pane, which allows you to layout multiple components in the glass pane.
Usually, you should only use the glass pane to block user input (and, if necessary, display some kind of "please wait" message). Can you provide a use case of why you want to put glass panes on top of one another?
I have to use both AWT and Swing component in my application. At displaying the AWT first appear on the screen then come the Swing component (with LAF style)
Is it possible that and make them appear simutaneously ? Like before paint, a kind of buffer ?
Thank you
1) since as of the JDK 6 update 12 and JDK7 build 19 releases, you can seamlessly mix heavyweight (AWT) and lightweight (Swing) components,But I don't suggest mixing AWT with Swing,
2) its hard change Look and Feel for AWT Components, I never saw good one, by default is there Look and Feel that came from Native OS, Look and Feel is about usage Swing JComponents
3) since is possible put JComponents with different Look and Feel, I'd suggest to create something similair
import java.awt.event.*;
import java.awt.Color;
import java.awt.AlphaComposite;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class ButtonTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest().createAndShowGUI();
}
});
}
private JFrame frame;
private JButton opaqueButton1;
private JButton opaqueButton2;
private SoftJButton softButton1;
private SoftJButton softButton2;
public void createAndShowGUI() {
opaqueButton1 = new JButton("Opaque Button");
opaqueButton2 = new JButton("Opaque Button");
softButton1 = new SoftJButton("Transparent Button");
softButton2 = new SoftJButton("Transparent Button");
opaqueButton1.setBackground(Color.GREEN);
softButton1.setBackground(Color.GREEN);
frame = new JFrame();
frame.getContentPane().setLayout(new java.awt.GridLayout(2, 2, 10, 10));
frame.add(opaqueButton1);
frame.add(softButton1);
frame.add(opaqueButton2);
frame.add(softButton2);
frame.setSize(567, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Timer alphaChanger = new Timer(30, new ActionListener() {
private float incrementer = -.03f;
#Override
public void actionPerformed(ActionEvent e) {
float newAlpha = softButton1.getAlpha() + incrementer;
if (newAlpha < 0) {
newAlpha = 0;
incrementer = -incrementer;
} else if (newAlpha > 1f) {
newAlpha = 1f;
incrementer = -incrementer;
}
softButton1.setAlpha(newAlpha);
softButton2.setAlpha(newAlpha);
}
});
alphaChanger.start();
Timer uiChanger = new Timer(3500, new ActionListener() {
private LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
private int index = 1;
#Override
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(laf[index].getClassName());
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception exc) {
exc.printStackTrace();
}
index = (index + 1) % laf.length;
}
});
uiChanger.start();
}
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();
}
}
}
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();
}
}
}
It's not clear how your video source works, but it appears to be incompatible with Swing due to Mixing Heavyweight and Lightweight Components. Although awt components aren't transparent, you can always draw your own translucent text on the Frame and do manual hit testing, as suggested below. You might also check to see if your video source API supports Double Buffering and Page Flipping.
import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
/** #see http://stackoverflow.com/questions/6725618 */
public class AlphaFrame extends Frame {
private static final Font font = new Font("Dialog", Font.BOLD, 24);
private float alpha = 1f;
private Rectangle rect = new Rectangle();
public static void main(String[] args) {
AlphaFrame af = new AlphaFrame();
af.setTitle("Translucent Button");
af.setAlpha(0.5f);
af.setForeground(Color.green);
af.setBackground(Color.black);
af.setVisible(true);
}
public AlphaFrame() {
this.setSize(320, 240);
this.setLocationRelativeTo(null);
this.setBackground(Color.white);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (rect.contains(e.getPoint())) {
System.out.println("Pressed.");
}
}
});
repaint();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alpha));
g2.setColor(getForeground());
g2.setFont(font);
FontMetrics fm = g2.getFontMetrics();
String s = getTitle();
Insets i = getInsets();
int dx = i.left + 10;
int dy = i.top + fm.getHeight() + 10;
Rectangle2D bounds = fm.getStringBounds(s, g);
rect.x = dx + (int) bounds.getX() - 1;
rect.y = dy + (int) bounds.getY() - 1;
rect.width = (int) bounds.getWidth() + 1;
rect.height = (int) bounds.getHeight() + 1;
System.out.println(i + " \n" + bounds + "\n" + rect);
g2.drawRect(rect.x, rect.y, rect.width, rect.height);
g2.drawString(s, dx, dy);
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
}
}
import java.awt.event.*;
import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class ButtonTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest().createAndShowGUI();
}
});
}
private JFrame frame;
private SoftJButton softButton1;
public void createAndShowGUI() {
softButton1 = new SoftJButton("Transparent Button");
softButton1.setPreferredSize(new Dimension(800, 600));
frame = new JFrame();
frame.add(softButton1);
frame.setLocation(150, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
Timer alphaChanger = new Timer(30, new ActionListener() {
private float incrementer = -.03f;
#Override
public void actionPerformed(ActionEvent e) {
float newAlpha = softButton1.getAlpha() + incrementer;
if (newAlpha < 0) {
newAlpha = 0;
incrementer = -incrementer;
} else if (newAlpha > 1f) {
newAlpha = 1f;
incrementer = -incrementer;
}
softButton1.setAlpha(newAlpha);
}
});
alphaChanger.start();
Timer uiChanger = new Timer(5500, new ActionListener() {
private LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
private int index = 1;
#Override
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(laf[index].getClassName());
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception exc) {
exc.printStackTrace();
}
index = (index + 1) % laf.length;
}
});
uiChanger.start();
}
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();
}
}
}