Attaching images to JLabel's border - java

I want to write a custom subclass of JLabel that would have two images attached to the border, that can be moved by moving the mouse. Real effects like this:
Here's my subclass, how could I add these attached images?
public class Rect extends JLabel{
private int width,height;
public Rect (int width,int height){
this.width = width;
this.height = height;
setText("b1");
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(0, 0, this.width, this.height);
}
public void reDraw(){
this.repaint();
}
public void setWidth(int width) {
this.width = width;
repaint();
}
public void setHeight(int height) {
this.height = height;
repaint();
}
}

To do this there are 4 things you should to do:
Extend an AbstractBorder not a Jlabel, then you can easily add your custom border to any component, not just a jLabel.
Override the paintBorder method so that you can draw your border.
Add an mouse action listeners to keep track of your border images.
And lastly you need a bit of logic to manage your border images.
I found this question interesting so I took a crack at making something as a test. It came out well, and does what you want, but will need a bit of work to get it looking correct. See below for a break down of each point.
Example image before we look at the code:
Extend an AbstractBorder:
public class MyCustomBorder extends AbstractBorder
{
private Color borderColour;
private int borderThickness = 10;
private Point firstSlider = new Point(0, 0);
private Point secondSlider = new Point(0, 0);
private BufferedImage firstSliderImage;
private BufferedImage secondSliderImage;
Boolean draggingFirst = false;
Boolean draggingSecond = false;
//See usage info
public MyCustomBorder(Color colour, int thickness, Point firstSlider, BufferedImage firstSliderImage, Point secondSlider, BufferedImage secondSliderImage)
{
borderColour = colour;
borderThickness = thickness;
this.firstSlider = firstSlider;
this.secondSlider = secondSlider;
this.firstSliderImage = firstSliderImage;
this.secondSliderImage = secondSliderImage;
}
Override the paintBorder method and insets:
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
{
super.paintBorder(c, g, x, y, width, height);
Graphics2D g2d = null;
if (g instanceof Graphics2D)
{
g2d = (Graphics2D) g;
//Draw border fill (currently hard coded to white, but can be changed)
g2d.setColor(Color.white);
//Top
g2d.fill(new Rectangle2D.Double(0, 0, width, borderThickness));
//Left
g2d.fill(new Rectangle2D.Double(0, 0, borderThickness, height));
//Bottom
g2d.fill(new Rectangle2D.Double(0, height-borderThickness, width, borderThickness));
//Right
g2d.fill(new Rectangle2D.Double(width-borderThickness, 0, borderThickness, height));
//draw black seperator
g2d.setColor(borderColour);
//Top
g2d.fill(new Rectangle2D.Double(borderThickness, borderThickness, width-(borderThickness*2), 1));
//Left
g2d.fill(new Rectangle2D.Double(borderThickness, borderThickness, 1, height-(borderThickness*2)));
//Bottom
g2d.fill(new Rectangle2D.Double(borderThickness, height-borderThickness-1, width-(borderThickness*2), 1));
//Right
g2d.fill(new Rectangle2D.Double(width-borderThickness-1, borderThickness, 1, height-(borderThickness*2)));
//draw sliders an custom position
g2d.drawImage(scale(secondSliderImage), null, secondSlider.x, secondSlider.y);
g2d.drawImage(scale(firstSliderImage), null, firstSlider.x, firstSlider.y);
}
}
#Override
public Insets getBorderInsets(Component c)
{
return (getBorderInsets(c, new Insets(borderThickness, borderThickness, borderThickness, borderThickness)));
}
#Override
public Insets getBorderInsets(Component c, Insets insets)
{
insets.left = insets.top = insets.right = insets.bottom = borderThickness;
return insets;
}
#Override
public boolean isBorderOpaque()
{
return false;
}
}
Add mouse action listeners:
//listeners for dragging
void addListeners(Component button)
{
button.addMouseMotionListener(new java.awt.event.MouseMotionAdapter()
{
public void mouseDragged(java.awt.event.MouseEvent evt)
{
//Only drag if a slider was selected
if (draggingFirst)
{
//update position of silder
firstSlider = snapToEdge(evt.getPoint(), evt.getComponent());
evt.getComponent().repaint();
}
else if (draggingSecond)
{
//update position of silder
secondSlider = snapToEdge(evt.getPoint(), evt.getComponent());
evt.getComponent().repaint();
}
}
});
button.addMouseListener(new java.awt.event.MouseAdapter()
{
//check if a slider was selected
public void mousePressed(java.awt.event.MouseEvent evt)
{
if (isInside(evt.getPoint(), firstSlider))
{
draggingFirst = true;
}
else if (isInside(evt.getPoint(), secondSlider))
{
draggingSecond = true;
}
}
public void mouseReleased(java.awt.event.MouseEvent evt)
{
//cancel selected slider
draggingFirst = false;
draggingSecond = false;
}
});
}
Logic:
//check if a slider was selected
private Boolean isInside(Point clicked, Point toCheck)
{
if (clicked.x > toCheck.x && clicked.x < toCheck.x + borderThickness)
{
if (clicked.y > toCheck.y && clicked.y < toCheck.y + borderThickness)
{
return true;
}
}
return false;
}
//snap a sliders co-ords to as edge
private Point snapToEdge(Point dragged, Component label)
{
//work out how close to each edge
int topEdge = dragged.y;
int leftEdge = dragged.x;
int rightEdge = label.getWidth()- dragged.x;
int bottomEdge = label.getHeight() - dragged.y;
//snap to slider co-ords to closest edge
if (topEdge < leftEdge && topEdge < rightEdge && topEdge < bottomEdge)
{
dragged.y = 0;
}
else if (leftEdge < rightEdge && leftEdge < bottomEdge)
{
dragged.x = 0;
}
else if (rightEdge < bottomEdge)
{
dragged.x = label.getWidth()-borderThickness;
}
else
{
dragged.y = label.getHeight()-borderThickness;
}
return dragged;
}
//scale slider images to fit border size
public BufferedImage scale(BufferedImage image)
{
BufferedImage resizedImage = null;
if (image != null)
{
double border = borderThickness;
resizedImage = new BufferedImage(borderThickness, borderThickness, TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance(border / (double)image.getWidth(), border / (double)image.getHeight());
g.drawRenderedImage(image, at);
}
return resizedImage;
}
The full code to copy and paste can be found here:
https://github.com/sorifiend/customBorder/blob/master/MyCustomBorder.java
Usage Example:
You can put this code in your form class to add a border to most swing components. In this example I added it to a jLabel called my_jLabel:
//Create border
MyCustomBorder border = new MyCustomBorder(Color.BLACK, 10, new Point(0, 0), img1, new Point(0, 0), img2);
//Add border to component called my_jLabel
my_jLabel.setBorder(border);
//Add action listeners for dragging sliders (very important)
border.addListeners(my_jLabel);

Related

How should I make the RoundedBorder background transparent? [duplicate]

The following screenshot shows a test of TextBubbleBorder1. I would like to make the corners of the component that are outside the rectangle to be entirely transparent & show whatever component is beneath it. I found a way to restrict the BG color of a label to 'inside the border' by setting a Clip (representing the area outside the rounded corners) on the Graphics2D instance and calling clearRect(). That can be seen in Label 1.
However you can see the downside of this approach when there is a red BG (or any non-standard color) on the parent panel. The corners default to the default panel color (easiest to see in Panel 2).
Ultimately I would like this to work for a non-standard color in the parent container, but it was partly inspired by What do I need to do to replicate this component with gradient paint?
Does anybody know a way to get those corners transparent?
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new GridLayout(1,0,5,5));
gui.setBorder(new EmptyBorder(10,10,10,10));
gui.setBackground(Color.RED);
AbstractBorder brdr = new TextBubbleBorder(Color.BLACK,2,16,0);
JLabel l1 = new JLabel("Label 1");
l1.setBorder(brdr);
gui.add(l1);
JLabel l2 = new JLabel("Label 2");
l2.setBorder(brdr);
l2.setBackground(Color.YELLOW);
l2.setOpaque(true);
gui.add(l2);
JPanel p1 = new JPanel();
p1.add(new JLabel("Panel 1"));
p1.setBorder(brdr);
p1.setOpaque(false);
gui.add(p1);
JPanel p2 = new JPanel();
p2.add(new JLabel("Panel 2"));
p2.setBorder(brdr);
gui.add(p2);
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class TextBubbleBorder extends AbstractBorder {
private Color color;
private int thickness = 4;
private int radii = 8;
private int pointerSize = 7;
private Insets insets = null;
private BasicStroke stroke = null;
private int strokePad;
private int pointerPad = 4;
RenderingHints hints;
TextBubbleBorder(
Color color) {
new TextBubbleBorder(color, 4, 8, 7);
}
TextBubbleBorder(
Color color, int thickness, int radii, int pointerSize) {
this.thickness = thickness;
this.radii = radii;
this.pointerSize = pointerSize;
this.color = color;
stroke = new BasicStroke(thickness);
strokePad = thickness / 2;
hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int pad = radii + strokePad;
int bottomPad = pad + pointerSize + strokePad;
insets = new Insets(pad, pad, bottomPad, pad);
}
#Override
public Insets getBorderInsets(Component c) {
return insets;
}
#Override
public Insets getBorderInsets(Component c, Insets insets) {
return getBorderInsets(c);
}
#Override
public void paintBorder(
Component c,
Graphics g,
int x, int y,
int width, int height) {
Graphics2D g2 = (Graphics2D) g;
int bottomLineY = height - thickness - pointerSize;
RoundRectangle2D.Double bubble = new RoundRectangle2D.Double(
0 + strokePad,
0 + strokePad,
width - thickness,
bottomLineY,
radii,
radii);
Polygon pointer = new Polygon();
// left point
pointer.addPoint(
strokePad + radii + pointerPad,
bottomLineY);
// right point
pointer.addPoint(
strokePad + radii + pointerPad + pointerSize,
bottomLineY);
// bottom point
pointer.addPoint(
strokePad + radii + pointerPad + (pointerSize / 2),
height - strokePad);
Area area = new Area(bubble);
area.add(new Area(pointer));
g2.setRenderingHints(hints);
Area spareSpace = new Area(new Rectangle(0, 0, width, height));
spareSpace.subtract(area);
g2.setClip(spareSpace);
g2.clearRect(0, 0, width, height);
g2.setClip(null);
g2.setColor(color);
g2.setStroke(stroke);
g2.draw(area);
}
}
While the TextBubbleBorder was devised for Internal padding for JTextArea with background Image (& ended up using a JLabel since the text area was a mess for the reasons mentioned above), by specifying a pointerSize of 0 we end up with a 'rounded rectangle' instead.
N.B. There is a clipping bug in this code, which is fixed in the accepted answer to paintComponent() is drawing on other components. This should only be considered as a solution if the 'clipping bug fix' is incorporated.
// Paint the BG color of the parent, everywhere outside the clip
// of the text bubble.
See this point in the code for the source that shows correctly as:
import java.awt.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new GridLayout(2,0,5,5));
gui.setBorder(new EmptyBorder(10,10,10,10));
gui.setBackground(Color.RED);
AbstractBorder brdrLeft = new TextBubbleBorder(Color.BLACK,2,16,16);
AbstractBorder brdrRight = new TextBubbleBorder(Color.BLACK,2,16,16,false);
JLabel l1 = new JLabel("Label 1");
l1.setBorder(brdrRight);
gui.add(l1);
JLabel l2 = new JLabel("Label 2");
l2.setBorder(brdrLeft);
l2.setBackground(Color.YELLOW);
l2.setOpaque(true);
gui.add(l2);
JPanel p1 = new JPanel();
p1.add(new JLabel("Panel 1"));
p1.setBorder(brdrRight);
p1.setOpaque(false);
gui.add(p1);
JPanel p2 = new JPanel();
p2.add(new JLabel("Panel 2"));
p2.setBorder(brdrLeft);
gui.add(p2);
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class TextBubbleBorder extends AbstractBorder {
private Color color;
private int thickness = 4;
private int radii = 8;
private int pointerSize = 7;
private Insets insets = null;
private BasicStroke stroke = null;
private int strokePad;
private int pointerPad = 4;
private boolean left = true;
RenderingHints hints;
TextBubbleBorder(
Color color) {
this(color, 4, 8, 7);
}
TextBubbleBorder(
Color color, int thickness, int radii, int pointerSize) {
this.thickness = thickness;
this.radii = radii;
this.pointerSize = pointerSize;
this.color = color;
stroke = new BasicStroke(thickness);
strokePad = thickness / 2;
hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int pad = radii + strokePad;
int bottomPad = pad + pointerSize + strokePad;
insets = new Insets(pad, pad, bottomPad, pad);
}
TextBubbleBorder(
Color color, int thickness, int radii, int pointerSize, boolean left) {
this(color, thickness, radii, pointerSize);
this.left = left;
}
#Override
public Insets getBorderInsets(Component c) {
return insets;
}
#Override
public Insets getBorderInsets(Component c, Insets insets) {
return getBorderInsets(c);
}
#Override
public void paintBorder(
Component c,
Graphics g,
int x, int y,
int width, int height) {
Graphics2D g2 = (Graphics2D) g;
int bottomLineY = height - thickness - pointerSize;
RoundRectangle2D.Double bubble = new RoundRectangle2D.Double(
0 + strokePad,
0 + strokePad,
width - thickness,
bottomLineY,
radii,
radii);
Polygon pointer = new Polygon();
if (left) {
// left point
pointer.addPoint(
strokePad + radii + pointerPad,
bottomLineY);
// right point
pointer.addPoint(
strokePad + radii + pointerPad + pointerSize,
bottomLineY);
// bottom point
pointer.addPoint(
strokePad + radii + pointerPad + (pointerSize / 2),
height - strokePad);
} else {
// left point
pointer.addPoint(
width - (strokePad + radii + pointerPad),
bottomLineY);
// right point
pointer.addPoint(
width - (strokePad + radii + pointerPad + pointerSize),
bottomLineY);
// bottom point
pointer.addPoint(
width - (strokePad + radii + pointerPad + (pointerSize / 2)),
height - strokePad);
}
Area area = new Area(bubble);
area.add(new Area(pointer));
g2.setRenderingHints(hints);
// Paint the BG color of the parent, everywhere outside the clip
// of the text bubble.
Component parent = c.getParent();
if (parent!=null) {
Color bg = parent.getBackground();
Rectangle rect = new Rectangle(0,0,width, height);
Area borderRegion = new Area(rect);
borderRegion.subtract(area);
g2.setClip(borderRegion);
g2.setColor(bg);
g2.fillRect(0, 0, width, height);
g2.setClip(null);
}
g2.setColor(color);
g2.setStroke(stroke);
g2.draw(area);
}
}
Try this:
JPanel p = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension arcs = new Dimension(15,15); //Border corners arcs {width,height}, change this to whatever you want
int width = getWidth();
int height = getHeight();
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//Draws the rounded panel with borders.
graphics.setColor(getBackground());
graphics.fillRoundRect(0, 0, width-1, height-1, arcs.width, arcs.height);//paint background
graphics.setColor(getForeground());
graphics.drawRoundRect(0, 0, width-1, height-1, arcs.width, arcs.height);//paint border
}
};
With my test:
JFrame f = new JFrame();
f.setLayout(null);
f.setDefaultCloseOperation(3);
f.setSize(500, 500);
JPanel p = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension arcs = new Dimension(15,15);
int width = getWidth();
int height = getHeight();
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//Draws the rounded opaque panel with borders.
graphics.setColor(getBackground());
graphics.fillRoundRect(0, 0, width-1, height-1, arcs.width, arcs.height);//paint background
graphics.setColor(getForeground());
graphics.drawRoundRect(0, 0, width-1, height-1, arcs.width, arcs.height);//paint border
}
};
p.setBounds(10,10,100,30);
p.setOpaque(false);
f.getContentPane().setBackground(Color.red);
f.add(p);
f.show();
the result is:
Thanks #BackSlash, nice and simple. I expanded upon this so it's more reusable. This also allows setting a background color in the constructor. And I show how you can make a circular panel for fun.
import java.awt.*;
import javax.swing.*;
public class RoundedPanelExample extends JFrame
{
public RoundedPanelExample()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Rounded Panel Example");
setResizable(true);
setDefaultLookAndFeelDecorated(true);
setSize(500, 500);
Container pane = getContentPane();
pane.setLayout(null);
pane.setBackground(Color.LIGHT_GRAY);
JPanel p1 = new RoundedPanel(10, Color.CYAN);
p1.setBounds(10,10,100,60);
p1.setOpaque(false);
pane.add(p1);
JPanel p2 = new RoundedPanel(15, Color.RED);
p2.setBounds(150,10,50,50);
p2.setOpaque(false);
pane.add(p2);
JPanel p3 = new RoundedPanel(30);
p3.setBounds(230,10,100,150);
p3.setOpaque(false);
pane.add(p3);
JPanel p4 = new RoundedPanel(20);
p4.setBounds(10,200,100,100);
p4.setBackground(Color.GREEN);
p4.setOpaque(false);
pane.add(p4);
JPanel p5 = new RoundedPanel(200);
p5.setBounds(150,200,200,200);
p5.setBackground(Color.BLUE);
p5.setOpaque(false);
pane.add(p5);
}
public static void main(String[] args)
{
RoundedPanelExample gui = new RoundedPanelExample();
gui.setVisible(true);
}
class RoundedPanel extends JPanel
{
private Color backgroundColor;
private int cornerRadius = 15;
public RoundedPanel(LayoutManager layout, int radius) {
super(layout);
cornerRadius = radius;
}
public RoundedPanel(LayoutManager layout, int radius, Color bgColor) {
super(layout);
cornerRadius = radius;
backgroundColor = bgColor;
}
public RoundedPanel(int radius) {
super();
cornerRadius = radius;
}
public RoundedPanel(int radius, Color bgColor) {
super();
cornerRadius = radius;
backgroundColor = bgColor;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension arcs = new Dimension(cornerRadius, cornerRadius);
int width = getWidth();
int height = getHeight();
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//Draws the rounded panel with borders.
if (backgroundColor != null) {
graphics.setColor(backgroundColor);
} else {
graphics.setColor(getBackground());
}
graphics.fillRoundRect(0, 0, width-1, height-1, arcs.width, arcs.height); //paint background
graphics.setColor(getForeground());
graphics.drawRoundRect(0, 0, width-1, height-1, arcs.width, arcs.height); //paint border
}
}
}
Possible cheaper alternative
public class RoundedLabel extends JLabel {
private final Rectangle rv = new Rectangle();
#Override
public void updateUI() {
super.updateUI();
setBorder(new EmptyBorder(1, 3, 1, 3));
}
#Override
protected void paintComponent(Graphics g) {
getBounds(rv);
var g2 = (Graphics2D) g;
g2.setColor(getBackground());
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.fillRoundRect(rv.x, rv.y, rv.width, rv.height, 8, 8);
super.paintComponent(g);
}
}

JSlider image behind track

I want to put an image (visualization of an audio) behind the JSlider which represents the audioplayer, the process of playing.
First I tried to overwrite the paint-method of the Slider
public void paintComponent(Graphics g) {
// Draw the previously loaded image to Component
g.drawImage(img, 0, -100, null);
super.paintComponent(g);
}
this worked, but the image is higher than the slider, so my next try was a JLayeredPane, where I put the JSlider above a JLabel with the image. Looks good for the first moment. But I mentioned that I need the image behind the track of the slider, not the whole slider. There is space to the left and right. Can anybody tell me a way how to calculate this space? Or the width and offset of the track to the border of the slider? This should run under Windows and MacOs, so different LookAndFeels, so I think hard coded values will not work.
Example Slider with background image
Thankyou.
My solution for this Problem is now to overwrite the SliderUI. So this is a very special component, so it's nonrelevant that it looks the same on all LookAndFeels.
It supports also jumping directly to mouse position, which is different to BasicSliderUI.
/**
*
* Custom SliderUI for AudioPlayer with audioimage in background
*/
public class AudioSliderUI extends BasicSliderUI {
private BasicStroke stroke = new BasicStroke(1f, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND, 0f);
public AudioSliderUI(AudioSlider b) {
super(b);
}
#Override
public void paint(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
super.paint(g, c);
}
#Override
protected Dimension getThumbSize() {
return new Dimension(2, 200);
}
#Override
public void paintTrack(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Stroke old = g2d.getStroke();
g2d.setStroke(stroke);
g2d.setPaint(Color.WHITE);
if (slider.getOrientation() == SwingConstants.HORIZONTAL) {
g2d.drawLine(trackRect.x, trackRect.y + trackRect.height / 2,
trackRect.x + trackRect.width, trackRect.y + trackRect.height / 2);
} else {
g2d.drawLine(trackRect.x + trackRect.width / 2, trackRect.y,
trackRect.x + trackRect.width / 2, trackRect.y + trackRect.height);
}
g2d.setStroke(old);
Image img = ((AudioSlider)slider).getImage();
g2d.drawImage(img, trackRect.x, trackRect.y, trackRect.width, trackRect.height, slider);
}
#Override
public void paintThumb(Graphics g) {
Rectangle knobBounds = thumbRect;
int w = knobBounds.width;
int h = 100;
int newStarty = knobBounds.height/2- h/2;
g.translate(knobBounds.x, knobBounds.y);
// "plain" version
g.setColor(Color.YELLOW);
g.fillRect(0, newStarty, w, h);
}
#Override
protected TrackListener createTrackListener(JSlider slider) {
return new TrackListener() {
#Override
public void mousePressed(MouseEvent e) {
if (UIManager.getBoolean("Slider.onlyLeftMouseButtonDrag")
&& SwingUtilities.isLeftMouseButton(e)) {
JSlider slider = (JSlider) e.getComponent();
switch (slider.getOrientation()) {
case SwingConstants.VERTICAL:
slider.setValue(valueForYPosition(e.getY()));
break;
case SwingConstants.HORIZONTAL:
slider.setValue(valueForXPosition(e.getX()));
break;
default:
throw new IllegalArgumentException(
"orientation must be one of: VERTICAL, HORIZONTAL");
}
super.mousePressed(e); // isDragging = true;
super.mouseDragged(e);
} else {
super.mousePressed(e);
}
}
#Override
public boolean shouldScroll(int direction) {
return false;
}
};
}
}
Matching Slider:
public class AudioSlider extends JSlider {
private Image img;
public AudioSlider() {
setOpaque(false);
}
/**
* #return the img
*/
public Image getImage() {
return img;
}
public void setImage(Image img) {
this.img = img;
}
}
Works for me, maybe covers not all prospects.

JAVA drawing rectangle

So I have code like this:
public class TestPane extends JPanel {
private Rectangle selection = new Rectangle();
private Point clickPoint;
private BufferedImage tempimage;
public TestPane() {
try {
tempimage = ImageIO.read(new File("/Users/droop//omega.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
int minX = Math.min(e.getX(), clickPoint.x);
int minY = Math.min(e.getY(), clickPoint.y);
int maxX = Math.max(e.getX(), clickPoint.x);
int maxY = Math.max(e.getY(), clickPoint.y);
selection.x = minX;
selection.y = minY;
selection.width = maxX - minX;
selection.height = maxY - minY;
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
clickPoint = new Point(e.getPoint());
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
#Override
public Dimension getPreferredSize() {
return tempimage == null ? new Dimension(200, 200) : new Dimension(tempimage.getWidth(), tempimage.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - tempimage.getWidth()) / 2;
int y = (getHeight() - tempimage.getHeight()) / 2;
g2d.drawImage(tempimage, x, y, this);
if (selection.width > 0 && selection.height > 0) {
g2d.setColor(new Color(0, 0, 255, 64));
g2d.fill(selection);
g2d.setColor(Color.BLUE);
g2d.draw(selection);
}
g2d.dispose();
}
}
What I am trying to do is: change this code so I can change the picture using a button click. SO I want to have my TestPane created and put on frame but load the image later on with a button click.
And there is one more problem : sometimes the picture is too big to display on TestPane so I added scrools but then x and y coordinates of the mouse click are not synchronized with drawing the shape. When scrolls are on and I do the mouse click then the rectangle is being drawn above NOT at the exact place.
please help

Custom Java Component Not Drawn Correctly

I have a custom button that is not being drawn properly. It shows up as a dot in the upper left hand corner. I have three classes. One for the button, one for the menu or drawing of several buttons and a main class that calls the menu.
Class 1 - button
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.white);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, this.x, this.y,this.getWidth(), this.getHeight(), null);
g2d.setFont(this.font);
g2d.drawString(this.label, x, y);
}
Class 2 - menu
public void draw(Graphics g, int width, int height) {
int x, y;
for(int i = 0; i < buttons.length; i++) {
x = (int) (width / 2 - buttons[i].getWidth() / 2);
y = (int) (height / 2 - buttons[i].getHeight() / 2);
buttons[i].setBounds(x, y + (i*60), buttons[i].getWidth(), buttons[i].getHeight());
buttons[i].paintComponent(g);
}
}
Class 3 - main
if(gMenu != null) {
gMenu.draw(g, gWindow.getWidth(), gWindow.getHeight());
}
Edit: To clarify what I'm trying to do is create a popup menu with a few custom buttons (components).
Edit: I got them to draw, but the mouse listener doesn't work.
here is the menu class
public class Menu extends JComponent {
GameWindow window;
public Menu(GameWindow window) {
this.window = window;
this.setVisible(true);
}
public void addChildToPanel(JComponent child) {
int width = (int) getWidth();
if(child.getWidth() > width) {
width = child.getWidth();
}
int height = (int) getHeight();
height += child.getHeight();
setSize(width, height);
Dimension screen = new Dimension(window.getWidth(), window.getHeight());
int x = (screen.width - width) / 2;
int y = (screen.height - height) / 2;
setBounds(x, y, width, height);
}
}
Here is the button class
public class MenuButton extends JComponent implements MouseListener {
private BufferedImage img;
private BufferedImage img_h;
private int x, y;
private String label;
private Font font;
private int state = 0;
// state 0 = normal
// state 1 = highlight
// state 2 = pressed
public MenuButton(BufferedImage img, BufferedImage img_h, String label, Font font) {
this.setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
this.img_h = img_h;
this.img = img;
this.label = label;
this.font = font;
setVisible(true);
setBounds(0, 0, img.getWidth(), img.getHeight());
this.addMouseListener(this);
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.white);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
switch (state) {
case 0:
g2d.drawImage(img, this.getBounds().x, this.getBounds().y,this.getWidth(), this.getHeight(), null);
break;
case 1:
g2d.drawImage(img_h, this.getBounds().x, this.getBounds().y,this.getWidth(), this.getHeight(), null);
break;
case 2:
g2d.drawImage(img, this.x, this.y,this.getWidth(), this.getHeight(), null);
break;
}
g2d.setFont(this.font);
int size = g2d.getFontMetrics(font).stringWidth(this.label);
int x = this.getBounds().x + this.getWidth() - 20 - size;
int y = this.getBounds().y + 29;
g2d.drawString(this.label,x, y);
}
public void setState(int state) {
this.state = state;
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
setState(1);
}
#Override
public void mouseExited(MouseEvent e) {
setState(0);
}
#Override
public void mousePressed(MouseEvent e) {
setState(2);
}
#Override
public void mouseReleased(MouseEvent e) {
setState(1);
}
}
Child class that I call draw on
public class PauseMenu extends Menu {
private int width;
private int height;
private MenuButton[] buttons = new MenuButton[4];
public PauseMenu(GameWindow window) {
super(window);
Font font = null;
BufferedImage img = null;
BufferedImage img_h = null;
try {
InputStream is = getClass().getResourceAsStream("/fonts/ALDOPC.ttf");
font = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.PLAIN, 24f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
img = ImageIO.read(getClass().getResourceAsStream("/gui/bg_menu_button_round.png"));
img_h = ImageIO.read(getClass().getResourceAsStream("/gui/bg_menu_button_round_highlight.png"));
}
catch(Exception e)
{
System.out.print("Failed to load resources");
System.out.println();
}
MenuButton resume = new MenuButton(img, img_h, "CONTINUE", font);
final MenuButton quit = new MenuButton(img, img_h, "QUIT", font);
MenuButton vid = new MenuButton(img, img_h, "VIDEO", font);
MenuButton sound = new MenuButton(img, img_h, "SOUND", font);
buttons[0] = resume;
buttons[1] = vid;
buttons[2] = sound;
buttons[3] = quit;
for(int i = 0; i < buttons.length; i++) {
int x = (window.getWidth() - img.getWidth()) / 2;
int y = (window.getHeight() - img.getHeight()) / 2;
buttons[i].setBounds(x, y + (i * img.getHeight()), img.getWidth(), img.getHeight());
this.addChildToPanel(buttons[i]);
}
}
public void draw(Graphics g) {
for(int i = 0; i < buttons.length; i++)
buttons[i].paintComponent(g);
}
}

JPanel Drop Shadow

I have a JPanel element and I would like added a drop shadow to it, how can I add a nice faded drop shadow to the element? Do I need to use external libraries or is there something that is built in that I can use?
Example:
So I looked into swingx which extends JPanel and was able to achieve the results I was looking for with the following code:
public class Canvas extends JXPanel{
public Canvas(){
DropShadowBorder shadow = new DropShadowBorder();
shadow.setShadowColor(Color.BLACK);
shadow.setShowLeftShadow(true);
shadow.setShowRightShadow(true);
shadow.setShowBottomShadow(true);
shadow.setShowTopShadow(true);
this.setBorder(shadow);
}
}
And the result:
This is a complete HACK
This will require you to have a copy of JH-Labs Filters for the blur implementation
This is an expensive operation as it uses a blur operation, the reason I use it is that will take into account the the shape of the component it is shadowing.
The main problem you have is that borders aren't them selves, transparent, there's no way to really have an opaque component and a transparent border. Hench the hack
public class TestDropShadowBorder {
public static void main(String[] args) {
new TestDropShadowBorder();
}
public TestDropShadowBorder() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.RED);
setBorder(new EmptyBorder(20, 20, 20, 20));
setLayout(new BorderLayout());
JPanel drop = new JPanel();
drop.setOpaque(false);
DropShadowBorder border = new DropShadowBorder();
border.setFillContentArea(true);
drop.setBorder(new CompoundBorder(border, new LineBorder(Color.BLACK)));
add(drop);
}
}
public static class DropShadowBorder implements Border {
protected static final int SHADOW_SIZE = 4;
protected static final Map<Component, DropShadowBorder.CachedBorder> BORDER_CACHE = new WeakHashMap<Component, CachedBorder>(5);
private boolean fillContentArea;
private int shadowSize;
private float shadowOpacity;
private Color shadowColor;
public DropShadowBorder() {
this(SHADOW_SIZE, Color.BLACK, 0.5f, true);
}
public DropShadowBorder(boolean paintContentArea) {
this(SHADOW_SIZE, Color.BLACK, 0.5f, paintContentArea);
}
public DropShadowBorder(int shadowSize) {
this(shadowSize, Color.BLACK, 0.5f, true);
}
public DropShadowBorder(Color shadowColor) {
this(SHADOW_SIZE, shadowColor, 0.5f, true);
}
public DropShadowBorder(int shadowSize, Color showColor) {
this(shadowSize, showColor, 0.5f, true);
}
public DropShadowBorder(int shadowSize, float opacity) {
this(shadowSize, Color.BLACK, opacity, true);
}
public DropShadowBorder(Color shadowColor, float opacity) {
this(SHADOW_SIZE, shadowColor, opacity, true);
}
public DropShadowBorder(int shadowSize, Color shadowColor, float opacity) {
this(shadowSize, shadowColor, opacity, true);
}
public DropShadowBorder(int shadowSize, boolean paintContentArea) {
this(shadowSize, Color.BLACK, 0.5f, paintContentArea);
}
public DropShadowBorder(Color shadowColor, boolean paintContentArea) {
this(SHADOW_SIZE, shadowColor, 0.5f, paintContentArea);
}
public DropShadowBorder(int shadowSize, Color showColor, boolean paintContentArea) {
this(shadowSize, showColor, 0.5f, paintContentArea);
}
public DropShadowBorder(int shadowSize, float opacity, boolean paintContentArea) {
this(shadowSize, Color.BLACK, opacity, paintContentArea);
}
public DropShadowBorder(Color shadowColor, float opacity, boolean paintContentArea) {
this(SHADOW_SIZE, shadowColor, opacity, paintContentArea);
}
public DropShadowBorder(int shadowSize, Color showColor, float opacity, boolean paintContentArea) {
setShadowSize(shadowSize);
setShadowColor(showColor);
setShadowOpacity(opacity);
setFillContentArea(paintContentArea);
}
public void setShadowColor(Color shadowColor) {
this.shadowColor = shadowColor;
}
public void setShadowOpacity(float shadowOpacity) {
this.shadowOpacity = shadowOpacity;
}
public Color getShadowColor() {
return shadowColor;
}
public float getShadowOpacity() {
return shadowOpacity;
}
public void setShadowSize(int size) {
shadowSize = size;
}
public int getShadowSize() {
return shadowSize;
}
public static GraphicsConfiguration getGraphicsConfiguration() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}
public static BufferedImage createCompatibleImage(int width, int height) {
return createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
public static BufferedImage createCompatibleImage(int width, int height, int transparency) {
BufferedImage image = getGraphicsConfiguration().createCompatibleImage(width, height, transparency);
image.coerceData(true);
return image;
}
public static BufferedImage generateShadow(BufferedImage imgSource, int size, Color color, float alpha) {
int imgWidth = imgSource.getWidth() + (size * 2);
int imgHeight = imgSource.getHeight() + (size * 2);
BufferedImage imgMask = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgMask.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
int x = Math.round((imgWidth - imgSource.getWidth()) / 2f);
int y = Math.round((imgHeight - imgSource.getHeight()) / 2f);
g2.drawImage(imgSource, x, y, null);
g2.dispose();
// ---- Blur here ---
BufferedImage imgGlow = generateBlur(imgMask, size, color, alpha);
//
// BufferedImage imgGlow = ImageUtilities.createCompatibleImage(imgWidth, imgHeight);
// g2 = imgGlow.createGraphics();
//
// g2.drawImage(imgMask, 0, 0, null);
// g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
// g2.setColor(color);
//
// g2.fillRect(x, y, imgSource.getWidth(), imgSource.getHeight());
// g2.dispose();
//
// imgGlow = filter.filter(imgGlow, null);
// ---- Blur here ----
// imgGlow = ImageUtilities.applyMask(imgGlow, imgMask, AlphaComposite.DST_OUT);
return imgGlow;
}
public static BufferedImage generateBlur(BufferedImage imgSource, int size, Color color, float alpha) {
GaussianFilter filter = new GaussianFilter(size);
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2d = imgBlur.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.drawImage(imgSource, 0, 0, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2d.setColor(color);
g2d.fillRect(0, 0, imgSource.getWidth(), imgSource.getHeight());
g2d.dispose();
imgBlur = filter.filter(imgBlur, null);
return imgBlur;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
/*
* Because of the amount of time it can take to render the drop shadow,
* we cache the results in a static cache, based on the component
* and the components size.
*
* This allows the shadows to repainted quickly so long as the component
* hasn't changed in size.
*/
BufferedImage dropShadow = null;
DropShadowBorder.CachedBorder cached = BORDER_CACHE.get(c);
if (cached != null) {
dropShadow = cached.getImage(c);
}
if (dropShadow == null) {
int shadowSize = getShadowSize();
float opacity = getShadowOpacity();
Color color = getShadowColor();
// Create a blank canvas, from which the actually border can be generated
// from...
// The ahadow routine can actually generate a non-rectangular border, but
// because we don't have a suitable template to run from, we need to
// set this up our selves...
// It would be nice to be able to user the component itself, but this will
// have to
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.fillRect(0, 0, width - (shadowSize * 2), height - (shadowSize * 2));
g2d.dispose();
// Generate the shadow
BufferedImage shadow = generateShadow(img, shadowSize, getShadowColor(), getShadowOpacity());
// We need to produce a clipping result, cause the border is painted ontop
// of the base component...
BufferedImage clipedShadow = createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d = clipedShadow.createGraphics();
Shape clip = g2d.getClip();
// First we create a "area" filling the avaliable space...
Area area = new Area(new Rectangle(width, height));
// Then we subtract the space left over for the component
area.subtract(new Area(new Rectangle(width - (shadowSize * 2), height - (shadowSize * 2))));
// And then apply the clip
g2d.setClip(area);
// Then draw the shadow image
// g2d.drawImage(shadow, -(shadowSize / 2), -(shadowSize / 2), c);
g2d.drawImage(shadow, 0, 0, c);
g2d.setClip(clip);
if (!c.isOpaque() && isFillContentArea()) {
area = new Area(new Rectangle(width - (shadowSize * 2), height - (shadowSize * 2)));
g2d.setColor(c.getBackground());
g2d.fill(area);
}
// g2d.setColor(Color.RED);
// g2d.drawRect(x, y, width - 1, height - 1);
//
// g2d.setColor(Color.GREEN);
// g2d.drawRect(x, y, width - (shadowSize * 2), height - (shadowSize * 2));
g2d.dispose();
dropShadow = clipedShadow;
BORDER_CACHE.put(c, new CachedBorder(dropShadow, c.getSize()));
}
g.drawImage(dropShadow, x, y, c);
// if (!c.isOpaque() && isFillContentArea()) {
//
// Graphics2D g2d = (Graphics2D) g;
//
// Area area = new Area(new Rectangle(width - (shadowSize * 2), height - (shadowSize * 2)));
// g2d.setColor(c.getBackground());
// g2d.fill(area);
//
// }
// g.setColor(Color.MAGENTA);
// g.drawRect(x + 1, y + 1, width - (shadowSize * 2) - 1, height - (shadowSize * 2) - 1);
}
public Insets getBorderInsets(Component cmpnt) {
return new Insets(0, 0, getShadowSize() * 2, getShadowSize() * 2);
}
public boolean isBorderOpaque() {
return false;
}
/**
* Returns if the content area should be painted by this border when the
* parent component is opaque...
*
* The problem is, the paintComponent method will paint the WHOLE component
* background, including the border area. This is a reasonable assumption to
* make, but it makes the shadow border really show up when the parent
* component is a different color.
*
* This allows the border to take control of that fact.
*
* When using it, you will need to try and make this the first border to get
* painted though :P
*
* #return
*/
public boolean isFillContentArea() {
return fillContentArea;
}
public void setFillContentArea(boolean fill) {
fillContentArea = fill;
}
protected class CachedBorder {
private BufferedImage image;
private Dimension size;
public CachedBorder(BufferedImage border, Dimension size) {
this.image = border;
this.size = size;
}
public BufferedImage getImage(Component comp) {
BufferedImage dropShadow = null;
if (comp.getSize().equals(size)) {
dropShadow = image;
}
return dropShadow;
}
}
}
}
UPDATED with additional Example
The drop shadow border has limitations, it can't take into consideration the shape of the component, as the time the border is painted, the component hasn't begin, so we have no reference point.
In order to be able to generate a drop shadow which takes into consideration the shape of the component, we need to create a custom component and inject our border directly into the paint process.
public class TestDropShadowBorder {
public static void main(String[] args) {
new TestDropShadowBorder();
}
public TestDropShadowBorder() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.RED);
setBorder(new EmptyBorder(20, 20, 20, 20));
setLayout(new BorderLayout());
add(new RoundedPane());
}
}
public class RoundedPane extends JPanel {
private int shadowSize = 5;
public RoundedPane() {
// This is very important, as part of the panel is going to be transparent
setOpaque(false);
}
#Override
public Insets getInsets() {
return new Insets(0, 0, 10, 10);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
int width = getWidth() - 1;
int height = getHeight() - 1;
Graphics2D g2d = (Graphics2D) g.create();
applyQualityProperties(g2d);
Insets insets = getInsets();
Rectangle bounds = getBounds();
bounds.x = insets.left;
bounds.y = insets.top;
bounds.width = width - (insets.left + insets.right);
bounds.height = height - (insets.top + insets.bottom);
RoundRectangle2D shape = new RoundRectangle2D.Float(bounds.x, bounds.y, bounds.width, bounds.height, 20, 20);
/**
* * THIS SHOULD BE CAHCED AND ONLY UPDATED WHEN THE SIZE OF THE
* COMPONENT CHANGES **
*/
BufferedImage img = createCompatibleImage(bounds.width, bounds.height);
Graphics2D tg2d = img.createGraphics();
applyQualityProperties(g2d);
tg2d.setColor(Color.BLACK);
tg2d.translate(-bounds.x, -bounds.y);
tg2d.fill(shape);
tg2d.dispose();
BufferedImage shadow = generateShadow(img, shadowSize, Color.BLACK, 0.5f);
g2d.drawImage(shadow, shadowSize, shadowSize, this);
g2d.setColor(getBackground());
g2d.fill(shape);
/**
* THIS ONE OF THE ONLY OCCASIONS THAT I WOULDN'T CALL
* super.paintComponent *
*/
getUI().paint(g2d, this);
g2d.setColor(Color.GRAY);
g2d.draw(shape);
g2d.dispose();
}
}
public static GraphicsConfiguration getGraphicsConfiguration() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}
public static BufferedImage createCompatibleImage(int width, int height) {
return createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
public static void applyQualityProperties(Graphics2D g2) {
g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
}
public static BufferedImage createCompatibleImage(int width, int height, int transparency) {
BufferedImage image = getGraphicsConfiguration().createCompatibleImage(width, height, transparency);
image.coerceData(true);
return image;
}
public static BufferedImage generateShadow(BufferedImage imgSource, int size, Color color, float alpha) {
int imgWidth = imgSource.getWidth() + (size * 2);
int imgHeight = imgSource.getHeight() + (size * 2);
BufferedImage imgMask = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgMask.createGraphics();
applyQualityProperties(g2);
int x = Math.round((imgWidth - imgSource.getWidth()) / 2f);
int y = Math.round((imgHeight - imgSource.getHeight()) / 2f);
// g2.drawImage(imgSource, x, y, null);
g2.drawImage(imgSource, 0, 0, null);
g2.dispose();
// ---- Blur here ---
BufferedImage imgShadow = generateBlur(imgMask, size, color, alpha);
return imgShadow;
}
public static BufferedImage generateBlur(BufferedImage imgSource, int size, Color color, float alpha) {
GaussianFilter filter = new GaussianFilter(size);
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2d = imgBlur.createGraphics();
applyQualityProperties(g2d);
g2d.drawImage(imgSource, 0, 0, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2d.setColor(color);
g2d.fillRect(0, 0, imgSource.getWidth(), imgSource.getHeight());
g2d.dispose();
imgBlur = filter.filter(imgBlur, null);
return imgBlur;
}
}
Simple drop shadow you can work off. You can see implemented on these JPanels.
public class DropShadowPanel extends JPanel {
private static final long serialVersionUID = 1L;
public int pixels;
public DropShadowPanel(int pix) {
this.pixels = pix;
Border border = BorderFactory.createEmptyBorder(pixels, pixels, pixels, pixels);
this.setBorder(BorderFactory.createCompoundBorder(this.getBorder(), border));
this.setLayout(new BorderLayout());
}
#Override
protected void paintComponent(Graphics g) {
int shade = 0;
int topOpacity = 80;
for (int i = 0; i < pixels; i++) {
g.setColor(new Color(shade, shade, shade, ((topOpacity / pixels) * i)));
g.drawRect(i, i, this.getWidth() - ((i * 2) + 1), this.getHeight() - ((i * 2) + 1));
}
}
}
Do you mean something like this:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ShadowTest {
private JFrame frame;
public ShadowTest() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ShadowTest();
}
});
}
private void initComponents() {
frame = new JFrame();
frame.setTitle("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//app exited when frame closes
frame.setResizable(false);
frame.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.HORIZONTAL;
gc.insets = new Insets(10, 10, 10, 10);
frame.add(new RoundedPanel(), gc);
//pack frame (size components to preferred size)
frame.pack();
frame.setVisible(true);//make frame visible
}
}
class RoundedPanel extends JPanel {
/**
* Stroke size. it is recommended to set it to 1 for better view
*/
protected int strokeSize = 1;
/**
* Color of shadow
*/
protected Color shadowColor = Color.black;
/**
* Sets if it drops shadow
*/
protected boolean shady = true;
/**
* Sets if it has an High Quality view
*/
protected boolean highQuality = true;
/**
* Double values for Horizontal and Vertical radius of corner arcs
*/
protected Dimension arcs = new Dimension(0, 0);
//protected Dimension arcs = new Dimension(20, 20);//creates curved borders and panel
/**
* Distance between shadow border and opaque panel border
*/
protected int shadowGap = 10;
/**
* The offset of shadow.
*/
protected int shadowOffset = 4;
/**
* The transparency value of shadow. ( 0 - 255)
*/
protected int shadowAlpha = 150;
int width = 300, height = 300;
public RoundedPanel() {
super();
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Color shadowColorA = new Color(shadowColor.getRed(),
shadowColor.getGreen(), shadowColor.getBlue(), shadowAlpha);
Graphics2D graphics = (Graphics2D) g;
//Sets antialiasing if HQ.
if (highQuality) {
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
//Draws shadow borders if any.
if (shady) {
graphics.setColor(shadowColorA);
graphics.fillRoundRect(
shadowOffset,// X position
shadowOffset,// Y position
width - strokeSize - shadowOffset, // width
height - strokeSize - shadowOffset, // height
arcs.width, arcs.height);// arc Dimension
} else {
shadowGap = 1;
}
//Draws the rounded opaque panel with borders.
graphics.setColor(getBackground());
graphics.fillRoundRect(0, 0, width - shadowGap,
height - shadowGap, arcs.width, arcs.height);
graphics.setColor(getForeground());
graphics.setStroke(new BasicStroke(strokeSize));
graphics.drawRoundRect(0, 0, width - shadowGap,
height - shadowGap, arcs.width, arcs.height);
//Sets strokes to default, is better.
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
}
Reference:
Rounded Border JPanel

Categories