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
Related
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);
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);
}
}
I'm newbie in the swing and have a question how better to draw this shape:
I thought in two ways
to draw regular rectangle and to write custom border to it?
to draw regular rectangle + compound border(which contains 2 or 3 borders). But here i do not succeed to draw border inside the shape, is is possible at all? Something like this :
figure.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBor‌​der(outside top,left,bottom, right, Color.WHITE), createMatteBorder(inside top,left,bottom, right, Color.WHITE)), where the inside border is small rectangle, and outside is big rectangle - not sure if it is possible???
Please advise and an examples will be highly appreciated!
Take a look at the Java 2D API. It helps you to draw complex shapes.
E.g.
class IrregularShape extends JComponent {
private int strokeWidth;
IrregularShape(int strokeWidth){
this.strokeWidth = strokeWidth;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D newGraphics = (Graphics2D) g.create();
Insets borderInsets = new Insets(0, 0, 0, 0);
Border border = getBorder();
if (border != null) {
borderInsets = border.getBorderInsets(this);
}
BasicStroke basicStroke = new BasicStroke(strokeWidth);
newGraphics.setStroke(basicStroke);
int x = getX() + borderInsets.left + strokeWidth;
int y = getY() + borderInsets.top + strokeWidth;
int width = getWidth() - x - borderInsets.right - strokeWidth;
int height = getHeight() - y - borderInsets.bottom - strokeWidth;
Double outterRactangleDouble = new Rectangle2D.Double(x, y, width, height);
Area outterRectangle = new Area(outterRactangleDouble);
Area innerRectangle = new Area(outterRactangleDouble);
AffineTransform affineTransform = new AffineTransform();
affineTransform.scale(0.5, 0.5);
affineTransform.translate(x + width * 0.10, y + height * 1.2);
innerRectangle.transform(affineTransform);
outterRectangle.subtract(innerRectangle);
newGraphics.draw(outterRectangle);
}
}
public class MainFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Irregular Shape");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.add(new IrregularShape(3));
frame.setSize(640, 150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Result
and it's also resizeable
you can use the polygon class (java.awt.Polygon)
int xs = new int[]{1,2,3...7}; //your x-coordinates
int ys = new int[]{1,2,3...7}; //your y-coordinates
Shape irr = new Polygon(xs, ys, xs.length);
if you want to use certain borders you can use Graphics2D
public void paintComponent(Graphics gr){
Graphics2D g2d = (Graphics2D)gr;
GradientPaint redToWhite = new GradientPaint(0,0,color.RED,100, 0,color.WHITE);
g2d.setPaint(redtowhite)
g2d.fill(irr); //fill special color
Stroke customBorder = getCustomBorder();
g2d.setStroke(customBorder);
g2d.draw(irr); //draw 'special' borders
}
have a look at stroke and fill
note that Polygon implements the contains(double x, double y)method which lets you detect if you're inside or not
You could use a Area for example...
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Area area = new Area(new Rectangle(10, 10, getWidth() - 20, getHeight() - 20));
area.subtract(new Area(new Rectangle(20, getHeight() / 2, getWidth() / 2, getHeight() - 10)));
g2d.draw(area);
g2d.dispose();
}
}
You define a custom shape...
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Path2D path = new Path2D.Float();
path.moveTo(10, 10);
path.lineTo(getWidth() - 20, 10);
path.lineTo(getWidth() - 20, getHeight() - 20);
path.lineTo(getWidth() / 2, getHeight() - 20);
path.lineTo(getWidth() / 2, getHeight() / 2);
path.lineTo(20, getHeight() / 2);
path.lineTo(20, getHeight() - 20);
path.lineTo(10, getHeight() - 20);
path.closePath();
g2d.draw(path);
g2d.dispose();
}
}
Actually writing a custom border would be very, very difficult, because of the irregular style of shape, where would the components actually be contained?
It might be possible to create two or more borders, which could then be laid out so that the appeared as one
See Working with Geometry for more details
Updated with Border example...
Getting a Border to actually work is far more difficult, as the expectation is that the internal area of the border will be rectangular.
Based on the complex shape you've provided, one solution would be to actually create two borders, a left and right borer, which take care of generating a "safe" area for components to be laid out within, for example:
public class LeftBorder implements Border {
private int offset;
public LeftBorder(int offset) {
this.offset = offset;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Path2D path = new Path2D.Float();
int xOffset = x + offset;
int yOffset = y + offset;
width -= offset;
height -= offset * 2;
float gap = width * 0.1f;
path.moveTo(xOffset, yOffset);
path.lineTo(xOffset + width, yOffset);
path.moveTo(xOffset, yOffset);
path.lineTo(xOffset, yOffset + height);
path.lineTo(xOffset + gap, yOffset + height);
path.lineTo(xOffset + gap, yOffset + (height - (height / 2)));
path.lineTo(xOffset + width, yOffset + (height - (height / 2)));
((Graphics2D)g).draw(path);
}
#Override
public Insets getBorderInsets(Component c) {
int height = c.getHeight();
height -= (height / 2);
System.out.println(height);
return new Insets(offset + 4, offset + 4, height + 4, 0);
}
#Override
public boolean isBorderOpaque() {
return false;
}
}
public class RightBorder implements Border {
private int offset;
public RightBorder(int offset) {
this.offset = offset;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Path2D path = new Path2D.Float();
int xOffset = x;
int yOffset = y + offset;
width -= offset;
height -= offset * 2;
path.moveTo(xOffset, yOffset);
path.lineTo(xOffset + width, yOffset);
path.lineTo(xOffset + width, yOffset + height);
path.lineTo(xOffset, yOffset + height);
path.lineTo(xOffset, yOffset + (height - (height / 2)));
((Graphics2D)g).draw(path);
}
#Override
public Insets getBorderInsets(Component c) {
return new Insets(offset + 4, 0, offset + 4, offset + 4);
}
#Override
public boolean isBorderOpaque() {
return false;
}
}
This would then require you to provide at least two panels of equal height, for example:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.geom.Path2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
public class Main {
public static void main(String args[]) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(new LeftPane());
frame.add(new RightPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class RightPane extends JPanel {
public RightPane() {
setBorder(new RightBorder(10));
setLayout(new GridBagLayout());
add(new JLabel("Righty"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class LeftPane extends JPanel {
public LeftPane() {
setBorder(new LeftBorder(10));
setLayout(new GridBagLayout());
add(new JLabel("Lefty"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
This will also be relient on the layout manager been able to layout the two components next to each other
In addition to my first answer https://stackoverflow.com/a/34287251/974186
You can also implement it as a Border.
class IrregularBorder implements Border {
private int thickness;
public IrregularBorder(int thickness) {
this.thickness = thickness;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width,
int height) {
Graphics2D graphics2d = (Graphics2D) g;
BasicStroke basicStroke = new BasicStroke(thickness);
graphics2d.setStroke(basicStroke);
int halfThickness = thickness / 2;
Double outterRactangleDouble = new Rectangle2D.Double(
x + halfThickness, y + halfThickness, width - thickness,
height - thickness);
Area outterRectangle = new Area(outterRactangleDouble);
Area innerRectangle = computeInnerRect(x, y, width, height,
outterRactangleDouble);
outterRectangle.subtract(innerRectangle);
graphics2d.draw(outterRectangle);
}
private Area computeInnerRect(int x, int y, int width, int height,
Double outterRactangleDouble) {
Area innerRectangle = new Area(outterRactangleDouble);
AffineTransform affineTransform = new AffineTransform();
affineTransform.scale(0.5, 0.5);
affineTransform.translate(x + width * 0.10, y + height * 1.2);
innerRectangle.transform(affineTransform);
return innerRectangle;
}
#Override
public Insets getBorderInsets(Component c) {
int left = (int) (thickness + (c.getWidth() * 0.6));
return new Insets(thickness, left, thickness, thickness);
}
#Override
public boolean isBorderOpaque() {
return true;
}
}
and use it as usual
public class MainFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Irregular Shape");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.add(mainPanel);
JPanel irregularShapeBorderedPanel = new JPanel(new BorderLayout());
irregularShapeBorderedPanel.add(new JButton("Button"),
BorderLayout.CENTER);
irregularShapeBorderedPanel.setBorder(new IrregularBorder(2));
mainPanel.add(irregularShapeBorderedPanel);
frame.setSize(640, 150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I am currently having lots of difficulty in one of my assignments. The task for this assignment is to create an aviation radar, VOR, with java's GUI features. When the user presses either the left/right arrow on their keyboard, the circular radar should rotate, and a needle in the middle of the radar should move left/right.
I am very close to finishing, but I am stuck on one part. I drew an image of the radar, and I attempted to draw a line on top of it. However, I was only successful when I was able to make all JPanels transparent. This causes a problem because it is difficult to see what I drew on top of it.
So, my question is, how would I draw it on top of the radar image without making everything transparent? Below is my code
public class finalVORGUI extends JPanel{
private JPanel rotationPanel;
private JPanel needle;
private JPanel attributes;
private int degrees;
private String CurrentRadial;
private int x;
private int y1;
private int y2;
final int WIDTH = 600;
final int HEIGHT = 600;
private ImageIcon radar = new ImageIcon("image/vor1.png");
/**
* The constructor for the class
* It's going to set the dimension of the program to 600x600, the
* background is going to be white (in order to blend in with the
* vor image), and it is going to add in the VOR radar and a radial
* indicator that will let the user know which radial he/she is on
*/
public finalVORGUI(){
JLayeredPane lp = new JLayeredPane();
lp.setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.white);
lp.setLayout(null);
lp.setFocusable(true);
lp.addKeyListener(new KeyboardListener());
rotationPanel = new JPanel();
rotationPanel = new TurningCanvas();
needle = new JPanel();
needle = new DrawNeedle();
attributes = new JPanel();
attributes = new DrawAttributes();
lp.add(rotationPanel, Integer.valueOf(1));
lp.add(needle, Integer.valueOf(2));
lp.add(attributes, Integer.valueOf(3));
needle.setBounds(100,0, needle.getPreferredSize().width, needle.getPreferredSize().height);
rotationPanel.setBounds(100, 100, rotationPanel.getPreferredSize().width, rotationPanel.getPreferredSize().height);
attributes.setBounds(100, 100, rotationPanel.getPreferredSize().width, rotationPanel.getPreferredSize().height);
add(lp);
degrees = 360; //to edit: this is going to be the radial the radar is currently facing
x = 172; //x is the location of the needle
y1 = 155;
y2 = 330;
CurrentRadial = "Radial: " + degrees; //A string that is always going to be above the radar. it's going to let the user know the current radial
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString(CurrentRadial, 250, 100);
}
public class DrawAttributes extends JPanel{
public DrawAttributes(){
setOpaque(false);
add(new Attributes());
}
public class Attributes extends JPanel{
int w = 500;
int h = 400;
public Attributes(){
setPreferredSize(new Dimension(w,h));
setBackground(Color.white);
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.drawString("To",300,400);
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.3f));
g2.setStroke(new BasicStroke(3));
super.paintComponent (g);
g2.dispose();
}
}
}
public class DrawNeedle extends JPanel{ //todo: make sure this works and adds correctly to the LayeredPane
public DrawNeedle(){
setOpaque(false);
add(new Needle());
}
public class Needle extends JPanel{
int w = 500;
int h = 400;
public Needle(){
setPreferredSize(new Dimension(w,h));
setBackground(Color.white);
}
private void doDrawing(Graphics g){
Graphics2D g4 = (Graphics2D) g;
g4.drawString("TO", 190, 200);
g4.drawString("FROM",190, 300);
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
RenderingHints hints = new RenderingHints(null);
hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(hints);
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.3f));
g2.setStroke(new BasicStroke(3));
doDrawing(g);
g2.drawLine(x,y1,x,y2);
super.paintComponent (g);
g2.dispose();
}
}
}
public class TurningCanvas extends JPanel{
public TurningCanvas(){
setOpaque(false);
add(new TurningImage());
}
public class TurningImage extends JPanel{
int w = radar.getIconWidth()- 20;
int h = radar.getIconHeight() -20;
public TurningImage(){
setPreferredSize(new Dimension(w,h));
setBackground(Color.white);
}
public void paintComponent(Graphics g){
super.paintComponent (g);
Graphics2D g2 = (Graphics2D) g;
RenderingHints hints = new RenderingHints(null);
hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(hints);
g2.rotate (Math.toRadians(degrees),w/2, h/2);
g2.drawImage(radar.getImage(), 0, 0, this);
//g2.drawLine(171,0,x,300);
g2.dispose();
}
}
}
/**
* This is the keyboard listener that this program will be using
* Depending on what the user wishes, or what type of keyboard they have,
* they will be able to find their desired radial by using the arrow keys
* or the "a" and "d" buttons. Left arrow to minus radial, right arrow to plus radial, etc etc...
*
*/
public class KeyboardListener implements KeyListener{
public void keyPressed (KeyEvent event) {
if(event.getKeyCode() == KeyEvent.VK_LEFT){
degrees--;
x--;
if(degrees <= 0){
degrees = 360;
}
if(x <= 89){
x = 89;
}
CurrentRadial = "Radial: " + degrees;
repaint();
}
if(event.getKeyCode() == KeyEvent.VK_RIGHT){
degrees++;
x++;
if(degrees >= 360){
degrees = 1;
}
if(x >= 250){
x = 250;
}
CurrentRadial = "Radial: " + degrees;
repaint();
}
}
public void keyTyped (KeyEvent event) {}
public void keyReleased (KeyEvent event) {}
}
/**
* The main method of this class
* This is going to make a new JFrame, which will hold the new
* VOR radar
* #param args
*/
public static void main(String[] args){
finalVORGUI test = new finalVORGUI();
JFrame frame = new JFrame("VOR Radar");
frame.setContentPane(test);
frame.pack();
frame.setVisible(true);
}
}
I could add a rounded corner border to my JDialog as in How to create a rounded title border in Java Swing. But it is still one color. I want to make the border looks like 3D.
Here is how I tried.
Graphics2D g2d = (Graphics2D) g;
Color c1 = getBackground();
Color c2 = color1.darker();
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, c1,
0, h, c2);
g2d.setPaint(gp);
g2d.fill3DRect(0,0, w, h,true);
Then, no 3D look, but the border has been widen more with its border color.
How can I achieve this?
Any sample code or links will be highly appreciated.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.border.*;
public class ThreeDimensionalBorder extends AbstractBorder {
private static final long serialVersionUID = 1L;
private Color color;
private int thickness = 8;
private int radii = 8;
private Insets insets = null;
private BasicStroke stroke = null;
private int strokePad;
RenderingHints hints;
int shadowPad = 3;
ThreeDimensionalBorder(Color color) {
this(color, 128, 8);
}
ThreeDimensionalBorder(Color color, int transparency, int shadowWidth) {
this.color = color;
shadowPad = shadowWidth;
stroke = new BasicStroke(thickness);
strokePad = thickness/2;
hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int pad = radii + strokePad;
int bottomPad = pad + strokePad + shadowPad;
int rightPad = pad + strokePad + shadowPad;
insets = new Insets(pad,pad,bottomPad+shadowPad,rightPad);
}
#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-shadowPad;
RoundRectangle2D.Double bubble = new RoundRectangle2D.Double(
0+strokePad,
0+strokePad,
width-thickness-shadowPad,
bottomLineY,
radii,
radii
);
Area area = new Area(bubble);
g2.setRenderingHints(hints);
g2.setColor(color);
g2.setStroke(stroke);
g2.draw(area);
Area shadowArea = new Area(new Rectangle(0,0,width,height));
shadowArea.subtract(area);
g.setClip(shadowArea);
Color shadow = new Color(color.getRed(),color.getGreen(),color.getBlue(),128);
g2.setColor(shadow);
g2.translate(shadowPad,shadowPad);
g2.draw(area);
AffineTransform at = g2.getTransform();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel p = new JPanel();
String t = "The quick brown fox jumps over the lazy dog!";
JLabel l1 = new JLabel(t);
l1.setBorder(new ThreeDimensionalBorder(Color.MAGENTA.darker(),128,4));
p.add(l1);
JLabel l2 = new JLabel(t);
l2.setBorder(new ThreeDimensionalBorder(Color.BLACK,200,5));
p.add(l2);
JLabel l3 = new JLabel(t);
l3.setBorder(new ThreeDimensionalBorder(Color.BLUE,40,6));
p.add(l3);
JOptionPane.showMessageDialog(null, p);
}
});
}
}
Would this suffice??
It's far from perfect, but the basic idea works...
public class MyRoundedBorder implements Border {
protected static final Insets DEFAULT_INSETS = new Insets(4, 4, 4, 4);
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.setColor(Color.WHITE);
Shape corner = new RoundedShape(width - 8, height - 8);
g2d.translate(x + 2, y + 2);
g2d.draw(corner);
g2d.transform(AffineTransform.getRotateInstance(Math.toRadians(180), (width - 8) / 2, (height - 8) / 2));
g2d.setColor(Color.LIGHT_GRAY);
g2d.draw(corner);
g2d.dispose();
}
#Override
public Insets getBorderInsets(Component c) {
return DEFAULT_INSETS;
}
#Override
public boolean isBorderOpaque() {
return true;
}
public class RoundedShape extends Path2D.Float {
public RoundedShape(int width, int height) {
moveTo(0, height - 20);
append(new Arc2D.Float(0, height - 20, 20, 20, 180, 45, Arc2D.CHORD), false);
lineTo(0, 20);
curveTo(0, 0, 0, 0, 20, 0);
lineTo(width - 10, 0);
append(new Arc2D.Float(width - 20, 0, 20, 20, 90, -45, Arc2D.CHORD), false);
}
}
}