Java image viewer - java

I am trying to create an image viewer the the idea is that the viewer will pop up with one image a random button and a reset button to let the user to click the button and cycle through a list of different images randomly. I can open the viewer but cant get the viewer to rotate the images. here is the code. I would be grateful for any help
import java.awt.*;
import javax.swing.*;
public class CreateImage extends JFrame {
private JButton jbtRandom = new JButton("Random");
private JButton jbtReset = new JButton ("Reset");
public CreateImage() {
JPanel panel = new JPanel();
panel.add(jbtRandom);
panel.add(jbtReset);
Image image1 = new ImageIcon("kobe.jpg").getImage();
Image image2 = new ImageIcon("joe.jpg").getImage();
Image image3 = new ImageIcon("sidney.jpg").getImage();
Image image4 = new ImageIcon("bugs.gif").getImage();
Image image5 = new ImageIcon("mac.jpg").getImage();
Image image6 = new ImageIcon("snooki.jpg").getImage();
setLayout(new GridLayout(2, 0, 5, 5));
add(new ImageViewer(image1));
/*add(new ImageViewer(image2));// <== extra lines form first viewer attempt
add(new ImageViewer(image3)); //, <== which showed all images at once.
add(new ImageViewer(image4));// <== only need one image and to flip
add(new ImageViewer(image5));// <== to a random image
add(new ImageViewer(image6));// <== */
}
public class ImageViewer extends JPanel {
private java.awt.Image image;
private boolean stretched = true;
private int xCoordinate;
private int yCoordinate;
public ImageViewer() {
}
public ImageViewer(Image image) {
this.image = image;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null)
if (isStretched())
g.drawImage(image, xCoordinate, yCoordinate, getWidth(), getHeight(), this);
else
g.drawImage(image, xCoordinate, yCoordinate, this);
}
public java.awt.Image getImage() {
return image;
}
public void setImage(java.awt.Image image) {
this.image = image;
repaint();
}
public boolean isStretched() {
return stretched;
}
public void setStretched(boolean stretched) {
this.stretched = stretched;
repaint();
}
public int getXCoordinate() {
return xCoordinate;
}
public void setXCoodinate(int xCoordinate) {
this.xCoordinate = xCoordinate;
}
public int getYCoordinate() {
return xCoordinate;
}
public void setYCoodinate(int yCoordinate) {
this.yCoordinate = yCoordinate;
repaint();
}
}
public static void main(String[] args) {
JFrame frame = new CreateImage();
frame.setTitle("Random Image-Click The Button");
frame.add(new JButton("Random"));
frame.add(new JButton("Reset"));
frame.setSize(400, 320);
frame.setLocationRelativeTo(null); //Center Frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Here are some steps you need to take to get started:
1) Instead of just creating and throwing away the images. Put them somewhere - like in a List or Map.
2) Add an event handler to your Random button.
3) On clicking that button, choose and show a new image from your List or Map.
Once you've done that post another more specific question if you're still stuck. You're quite far away from getting your end-goal at the moment so for now just focus on responding to a user event (clicking your buttons) to start with.
Refer to this to get started.

Related

How do I bring JFrame images to the front of my window in Java?

So I'm currently having the problem that a large image will cover up smaller images in my program when i try to graphically display them in Java. I would like to know how to bring certain images to the front of the window so the large "background" image will stay in the background. Also, I do not believe it's a possibility in my program to simply implement the pictures in reverse order.
Here's the code I used:
my image manager class with the method I use to implement the images into the window,
import java.awt.*;
import javax.swing.*;
public class ImageManager extends JFrame {
private ImageIcon image1;
private JLabel label1;
private ImageIcon image2;
private JLabel label2;
private ImageIcon image3;
private JLabel label3;
public ImageManager() {
}
public void addBackground() {
image3 = new ImageIcon(getClass().getResource("background.png"));
label3 = new JLabel(image3);
add(label3);
}
public void addSeaweed() {
image1 = new ImageIcon(getClass().getResource("seaweed.png"));
label1 = new JLabel(image1);
add(label1);
}
public void addUnderwatervolcano() {
image2 = new ImageIcon(getClass().getResource("underwatervolcano.png"));
label2 = new JLabel(image2);
add(label2);
}
}
and here's where I use the methods from ImageManager:
a method to display a picture of seaweed using the grow() method,
public Seaweed() {
setLayout(new FlowLayout());
World.gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
World.gui.setVisible(true);
World.gui.pack();
World.gui.setTitle("seaweed and underwatervolcano");
carbon = 0;
}
public void grow() {
if(World.getOceanCarbon() >= 10) {
addCarbon(10);
World.addOceanCarbon(-10);
World.gui.addSeaweed();
World.gui.pack();
}
}
and heres the method in a different class that uses the grow() method from the Seaweed class and the gui.addBackground() from the ImageManager class,
public static void runWorld() {
gui.addBackground();
UnderwaterVolcano volcano = new UnderwaterVolcano();
Seaweed seaweed = new Seaweed();
volcano.erupt();
seaweed.grow();
gui.setMinimumSize(new Dimension(905, 560));
}
}
i would like to know how i make it so gui.addBackground() does not cover up the picture of seaweed from gui.addSeaweed() (which was invoked in the seaweed.grow() method) while still invoking gui.addBackground() before invoking gui.addSeaweed(). Is there anyway I can manipulate at the method call the order in which images display in a window? I don't have a very good understanding of JFrame so please be very explanatory with your answers, all help appreciated.
Well your current logic adds all the images to the frame. Swing actually paints the last component added first. That is components are painted based on highest ZOrder being painted first. The default ZOrder of the component is simply the component count at the time the component is added to the panel. So yes based on your current logic the background will paint over top of the other images.
A couple of simple solutions:
1) Manage the ZOrder of your components.
After you add the component to frame you can reset the ZOrder so the component is painted last. So the basic code is
add(aComponent);
setComponentZOrder(aComponent, 0);
2) Add the child images to the background image instead of add all images to the frame. So you have a structure like:
- frame
- background image
- seaweed
- volcano
So the basic logic would be something like:
frame.add( background );
background.add( seaweed );
background.add( volcano );
Since in looks like the seaweed/volcano images are at random places on the background you would still need to manage the size/location of each of these images.
Note when adding child components to the background the child components must be fully contained within the background image or the child image will be truncated.
This is the approach I would use since it better describes the structure of your application. That is your frame contains a background and the background contains other child components. Nesting of components is common to get a desired layout of a frame.
You have to use a LayeredPane. Here is a working example of my own. You only have to replace the used images by some of yours.
The Main class:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Main{
static JFrameWin jFrameWindow;
public static void main(String[] args) {
SwingUtilities.invokeLater(runJFrameLater);
}
public static class JFrameWin extends JFrame{
public JFrameWin(){
// init
initJFrame(this);
JPanelSettings jPanelSettings = new JPanelSettings(this.getWidth(), this.getHeight(), this.getX(), this.getY());
JLayeredPane enclosingJLayeredPane = getEnclosingJLayeredPane(jPanelSettings);
jPanelSettings = new JPanelSettings(this.getWidth(), this.getHeight(), this.getX(), this.getY(), new File("billard_1.jpg"));
JPanel backgroundJPanel = getJPanel(jPanelSettings);
jPanelSettings = new JPanelSettings(this.getWidth()-100, this.getHeight()-100, this.getX()+5, this.getY()+20, new File("billard2.jpg"));
JPanel firstLayerJPanel = getJPanel(jPanelSettings);
jPanelSettings = new JPanelSettings(this.getWidth() - 200, this.getHeight() - 200, this.getX() + 60, this.getY() + 60, new File("painter.jpg"));
JPanel secondLayerJPanel = getJPanel(jPanelSettings);
// assemble
enclosingJLayeredPane.add(backgroundJPanel);
enclosingJLayeredPane.add(firstLayerJPanel);
enclosingJLayeredPane.add(secondLayerJPanel);
// adjust layers
enclosingJLayeredPane.setLayer(backgroundJPanel, 0);
enclosingJLayeredPane.setLayer(firstLayerJPanel, 1);
enclosingJLayeredPane.setLayer(secondLayerJPanel, 2);
// add object to JFrame
this.add(enclosingJLayeredPane, BorderLayout.CENTER);
}
}
static Runnable runJFrameLater = new Runnable() {
#Override
public void run() {
jFrameWindow = new JFrameWin();
jFrameWindow.setVisible(true);
}
};
private static void initJFrame(JFrame jFrame) {
jFrame.setTitle("Boxing Test");
jFrame.setSize(600, 600);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static JLayeredPane getEnclosingJLayeredPane(JPanelSettings jPanelSettings){
JLayeredPane jLayeredPane = new JLayeredPane();
jLayeredPane.setBounds(jPanelSettings.getXPosition(), jPanelSettings.getYPosition(), jPanelSettings.getWidth(), jPanelSettings.getHeight());
return jLayeredPane;
}
private static JPanel getJPanel(JPanelSettings jPanelSettings){
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(jPanelSettings.getImagePath());
} catch (IOException ex) {
System.out.println("Error" + ex.toString());
}
// fit image to frame size
Image scaledBufferedImage = bufferedImage.getScaledInstance(jPanelSettings.getWidth(), jPanelSettings.getHeight(), Image.SCALE_DEFAULT);
JLabel jLabel = new JLabel(new ImageIcon(scaledBufferedImage));
JPanel jPanel = new JPanel();
jPanel.setBounds(jPanelSettings.getXPosition(), jPanelSettings.getYPosition(), jPanelSettings.getWidth(), jPanelSettings.getHeight());
jPanel.add(jLabel);
return jPanel;
}
}
A helper-class
import java.io.File;
public class JPanelSettings {
private int height;
private int width;
private int xPosition;
private int yPosition;
private File imagePath;
// Basic constructor
public JPanelSettings(){ }
// size and positioning constructor
public JPanelSettings(int width,int height, int xPosition, int yPosition ){
setWidth(width);
setHeight(height);
setXPosition(xPosition);
setYPosition(yPosition);
}
// Full constructor
public JPanelSettings(int width,int height, int xPosition, int yPosition, File imagePath ){
setWidth(width);
setHeight(height);
setXPosition(xPosition);
setYPosition(yPosition);
setImagePath(imagePath);
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getXPosition() {
return xPosition;
}
public void setXPosition(int xPosition) {
this.xPosition = xPosition;
}
public int getYPosition() {
return yPosition;
}
public void setYPosition(int yPosition) {
this.yPosition = yPosition;
}
public File getImagePath() {
return imagePath;
}
public void setImagePath(File imagePath) {
this.imagePath = imagePath;
}
}

How can i use my ImageArray extend JPanel class into another class extend JApplet

My programmer was to make a program that translate each word you enter into another languages and shows the image of each word enter.
The translator of English words into french Words by using Jfield and StringArray works. But i got a big problem for setting each images. I don't know how to call them in JApplet Class.
The goal is to use ImageArray class for setup each image corresponding to each world enter in Jfield.
THis is my ImageArray class:
Heading1
public class ImageArray extends JPanel implements ActionListener {
Image[] pics;
String[] names;
int NUM_PICS;
JPanel controls, imagePanel;
JButton randomize;
Image currentImage;
ImageIcon icon;
JLabel imageLabel;
public ImageArray() {
setImages();
setLayout(new BorderLayout());
loadImages();
currentImage=pics[0];
setUpControls();
setUpImagePanel();
}
public void setUpControls(){
controls=new JPanel(new FlowLayout());
randomize=new JButton("randomize");
randomize.addActionListener(this);
controls.add(randomize);
add(controls, BorderLayout.SOUTH);
}
public void setUpImagePanel(){
imagePanel=new JPanel(new FlowLayout());
imageLabel=new JLabel();
imageLabel.setHorizontalAlignment(JLabel.CENTER);
icon=new ImageIcon();
icon.setImage(currentImage);
imageLabel.setIcon(icon);
imagePanel.add(imageLabel);
add(imagePanel, BorderLayout.CENTER);
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(currentImage,0,0,250,250,this);
}
public void setImages(){
pics = new Image[NUM_PICS];
NUM_PICS=names.length;
names[0]= "apple.jpg";
names[1]= "bags.jpg";
names[2] = "bathroom.jpg";
names[3] = "battled.jpg";
names[4]= "car.png";
names[5]= "chairs.jpg";
names[6] = "Computer.jpg";
names[7] = "family.jpg";
names[8] = "flowers.jpg";
names[9] = "god.jpg";
names[10] = "house.png";
names[11] = "map.jpg";
names[12] = "men.jpg";
names[13] = "pencil.jpg";
names[14] = "sisters.jpg";
names[15] = "tomato.jpg";
names[16] = "watch.jpg";
names[17] = "women.jpg";
names[18] ="book.gif";
}
public void loadImages(){
for(int i=0; i<names.length; i++){
currentImage=pics[NUM_PICS];
icon.setImage(currentImage);
repaint();
}
}
public int indexOfImages(ImageIcon userInput)
{
for(int i=0;i<names.length;i++)
{
if(userInput.equals(names[i])){return i;}
}
return -1;
}
#Override
public void actionPerformed(ActionEvent e) {
Object button=e.getSource();
if(button==randomize){
int random=(int)(Math.random()*pics.length);
currentImage=pics[random];
icon.setImage(currentImage);
repaint();
}
}
}

JPanel not showing background picture when it is scaled

im trying to set a background image on a JPanel that resizes with the panel. I have no problem in showing the picture, but as soon as I use:
background = background.getScaledInstance(300, -1, Image.SCALE_SMOOTH );
nothing is shown. Any ideas on why?
The code:
import javax.swing.*;
import java.awt.*;
public class LoginJPanel extends JPanel
{
private Image background;
public LoginJPanel()
{
super();
background = new ImageIcon("C:\\ASYS\\Stories\\Authentication UI\\AVDsplashscreen_tiny.jpg").getImage();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
background = background.getScaledInstance(300, -1, Image.SCALE_SMOOTH );
g.drawImage(background, 0, 0, this);
}
public static void main (String[] args)
{
LoginJPanel ip = new LoginJPanel();
JFrame jf = new JFrame ();
jf.setLayout (new BorderLayout ());
jf.add (ip, BorderLayout.CENTER);
jf.setSize (1000, 600);
jf.setLocation (150, 150);
jf.setVisible (true);
jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
}
In the end what I made is (as suggested by the comments) to move the scaling outside the paint method. I created a public method which is called from the parent components to notify the panel about the new size, and scale the picture acording to that:
public void initSize(int _width, int _height)
{
int h = background.getHeight(null);
int w = background.getWidth(null);
if (w - _width > h - _height)
{
scaleVertically(_width, _height);
}
else
{
scaleHorizontally(_width, _height);
}
}
I guess I should do this on some listener because this is not very elegant, but I didn't know how to do so.

JScrollPane doesn't update JScrollBar on JSplitPane

I want to create simple app able to edit images. Main view of app contains JSplitPane with two JScrollPane. Each JScrollPane contains JPanel. The right JPanel has several buttons etc. and the left JPanel is my drawing area.
Here is my problem...
When I first created JPanelDrawingArea I could set preferred size. If the size is bigger than size of JScrollPane the JScrollBars show up (in default it is equal). But when I load image to JPanelDrawingArea scroll bars don't update. Despite the fact I set new preferred size of JPanelDrawingArea (bigger than size of JScrollPane) scroll bars don't update unless I manually change the JSplitPanes divider position.
Here is my JSplitPane custom class:
public class DrawingPaneView extends JSplitPane{
private DrawingWorkMode drawingWorkMode;
private ImageWorkerView imageWorker;
JScrollPane workScrollPane;
JScrollPane pictureScrollPane;
private DrawingPaneController controller;
private Dimension minimumSize = new Dimension(100, 200);
private JPanel imagePanel;
public DrawingPaneView() {
setPreferredSize(new Dimension(ConfigClass.APP_WIDTH,ConfigClass.DRAWING_PANE_HEIGHT));
controller = new DrawingPaneController(this);
//Panel
drawingWorkMode = new DrawingWorkMode();
workScrollPane = new JScrollPane(drawingWorkMode);
//Image
imageWorker = new ImageWorkerView();
pictureScrollPane = new JScrollPane(imageWorker);
workScrollPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
//addJPanels
this.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
this.setRightComponent(workScrollPane);
this.setLeftComponent(pictureScrollPane);
//addLeftPanelWithJButtonOnly
imagePanel = new ImagePanelView();
pictureScrollPane.setRowHeaderView(imagePanel);
this.setDividerLocation(ConfigClass.DRAWING_PANE_WIDTH);
this.setOneTouchExpandable(true);
}
//Change mode
public void changeMode(String mode){
drawingWorkMode.changeMode(mode);
}
}
And there is my custom JPanel which perform drawing:
public class ImageWorkerView extends JPanel {
private BufferedImage img;
private ImageWorkerController controller;
private int defaultBounds = 50;
private double scale=1.0;
int imgW;
int imgH;
public ImageWorkerView() {
//setLayout(new BorderLayout(0, 0));
controller = new ImageWorkerController(this);
}
public void setScale(double scale) {
this.scale = scale;
}
public void setImage(File image) {
try {
img = ImageIO.read(image);
if (img.getType() != BufferedImage.TYPE_INT_RGB) {
BufferedImage img2 =
new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics big = img2.getGraphics();
big.drawImage(img, 0, 0, null);
img = img2;
}
} catch (IOException e) {
System.out.println("Image could not be read");
}
}
private void adjustPreferredSize(Boolean defaultSize){
if(defaultSize){
//Calculate the proper size of drawing area
imgW = ConfigClass.DRAWING_PANE_WIDTH - ImagePanelView.PREFERRED_WIDTH-10;
imgH = ConfigClass.DRAWING_PANE_HEIGHT-50;
setPreferredSize(new Dimension(imgW,imgH));
controller.setWindowHeight(imgH);
}
else{
imgW = (int)(img.getWidth() * scale + (defaultBounds*2));
imgH = (int)(img.getHeight() * scale + (defaultBounds*2));
setPreferredSize(new Dimension(imgW,imgH));
controller.setWindowHeight(imgH);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(img!=null){
if(scale!=1.0){
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp aop =
new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
g2.drawImage(img, aop, defaultBounds, defaultBounds);
}
else
g2.drawImage(img, defaultBounds, defaultBounds, null);
adjustPreferredSize(false);
}
else{
adjustPreferredSize(true);
}
}
}
And how i load image:
public class ImageWorkerController {
ImageWorkerView view;
ImageModel model;
public ImageWorkerController(ImageWorkerView workerView) {
this.view = workerView;
this.model = ApplicationContext.getObject(ImageModel.class);
//Load image
ApplicationContext.getObject(Context.class).addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(Context.IMAGE_LOADED.equals(evt.getPropertyName())){
view.setImage((File) evt.getNewValue());
view.repaint();
}
}
});
public void setWindowHeight(int h){
model.setDrawingWindowHeight(h);
}
}
As you can see there is adjustPreferredSize() method, when it is first called, and it sets preferredSize bigger than JScrollPane, JScrollBars appear. But when it is called again it does nothing.
What is interesting, when I manually change divider's location JScrollBars show up, on screen below you have an example:
http://s17.postimage.org/e1nkja3zx/liliebead.jpg
So there is some kind of event, which makes JScrollPane to update? I've tried several ways: updateUI(), repaint(), revalidate(). None of them worked.
Any ideas what I am doing wrong?
In short, you need to revalidate() your ImageWorkerView (right where you call repaint()). This will ask the component and its parent for "re-layout" and that in turn will trigger necessary adjustments for the scroll bars.
Thanks for your answer! Your suggestion made me think. What actually I did wrong is call revalidate() immediatelly after repaint() so in fact revalidate() executes before paintComponent method in ImageWorkerView (I found this out during debugging). The proper way to do this is:
ApplicationContext.getObject(Context.class).addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(Context.IMAGE_LOADED.equals(evt.getPropertyName())){
view.setImage((File) evt.getNewValue());
//view.repaint();
view.paintImmediately(new Rectangle(1, 1));
view.revalidate();
}
}
});
So now paintComponent sets preferred size and then revalidate() adjust scroll bars.

Java transparent panels & custom effect on panels

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.

Categories

Resources