Change Color BufferImage - java

I want to change the color of my BufferdImage.
When I do it like in this post: BufferedImage draw white when I say red it works only in my method which constructs my JFrame with all the components.
But when I want to use it in an ActionEvent in my Controller class, it does nothing, but the rest of the ActionEvent works, like for example change text in text field.
Methods in the JPanel class:
public void testImage(){
System.out.println("Methode suc. called");
Graphics g = image.getGraphics();
tempC = Color.GREEN;
g.setColor(tempC);
g.fillRect(150, 300, 100, 100);
tempC = Color.CYAN;
g.setColor(tempC);
g.fillOval(0, 0, 100, 100);
g.dispose();
if(image == null){System.out.println("Image is null");}
}
public void clearImage(){
Graphics g = image.getGraphics();
tempC = Color.WHITE;
g.setColor(tempC);
g.fillRect(0, 0, darstellungsBreite, darstellungsHoehe);
g.dispose();
}
The ActionListener:
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals(view.ACTION_CLEAR))
{
//Clear Graphics
view.drawArea.clearImage();
//view.useClear();
}

Related

Is it possible to write paint on screen program in java/swing?

I'm writing paint on screen program using Java Swing. It working on ubuntu linux. But windows shows black screen instead of transparent panel. I included similar example code. What is wrong in my code?
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Example {
public static final Color COLOR_TRANSPARENT = new Color(0,0,0,0);
public Example() {
Canvas drawArea = new Canvas();
drawArea.setBackground(COLOR_TRANSPARENT);
drawArea.setOpaque(true);
JWindow drawingFrame = new JWindow();
drawingFrame.setBackground(COLOR_TRANSPARENT);
drawingFrame.setContentPane(drawArea);
drawingFrame.pack();
drawingFrame.setSize(640, 460);
drawingFrame.setVisible(true);
drawingFrame.setLocationRelativeTo(null);
drawingFrame.setAlwaysOnTop(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(Example::new);
}
class Canvas extends JPanel{
private Image image;
private Graphics2D g2;
public Canvas() {
super();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
g2.setPaint(Color.RED);
g2.fillOval(x-10, y-10, 20, 20);
repaint(x-10, y-10, 20, 20);
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null){
image = createImage(getWidth(), getHeight());
g2 = (Graphics2D) image.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setBackground(COLOR_TRANSPARENT);
clear();
}
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, 0,0, null);
}
public void clear(){
System.out.println("clearing canvas ");
g2.setComposite(AlphaComposite.Clear);
g2.setBackground(COLOR_TRANSPARENT);
g2.setColor(COLOR_TRANSPARENT);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.clearRect(0, 0, getWidth(), getHeight());
g2.setPaint(Color.RED);
g2.setComposite(AlphaComposite.SrcOver);
repaint();
}
}
}
Here is screenshot what I wanted.
Example code updated. Now code should work without any other additional code.
For windows I made a couple of changes:
image = createImage(getWidth(), getHeight());
image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
I used a BufferedImage to you can set the alpha values of the image to be transparent.
//public static final Color COLOR_TRANSPARENT = new Color(0,0,0,0);
public static final Color COLOR_TRANSPARENT = new Color(0,0,0,1);
I made the alpha value non-zero, because a value of zero means the Java application won't receive the MouseEvent because it is passed to the application under the window.

How can I fix this NullPointerException when trying to render on a JPanel with Graphics2D? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I've been trying to make a shop for my game.
This has been unsuccessful.
I've tried drawComponent, didn't work.
No errors, code executed, but didn't work.
Now i'm trying to do:
private void render() {
Graphics2D g = (Graphics2D) graphics.getGraphics();
/////////////////////
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
/////////////////////
g.dispose();
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
}
Now i get a NullPointerException on g2d.
I've tried everything.
`Exception in thread "game" java.lang.NullPointerException
at com.johnythecarrot.game.Shop$DrawPane.access$2(Shop.java:123)
at com.johnythecarrot.game.Shop.render(Shop.java:154)
at com.johnythecarrot.game.Game.render(Game.java:75)
at com.johnythecarrot.game.Game.run(Game.java:112)
at java.lang.Thread.run(Unknown Source)`
My goals are to be able to have clickable buttons.
It DID work. But i had to restart almost everytime. Because mostly of the time to code wasn't even executed. So i tried to fix it. Now it's all messed up.
This is the code to it.
(DoubleInt is a part of my library it's nothing more than just x and y. )
public class Shop {
public BuildWindow window;
public static JWindow w;
private int WIDTH = 860, HEIGHT = 440;
private BufferedImage graphics = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
public DrawPane drawPane;
public Shop() {
//window = new BuildWindow().setSize(new DoubleInt(100, 100)).at(wi, he).setTitle("Shop").setOpacity(1).setDragable(false).showEmpty(true);
w = new JWindow();
w.setOpacity(1);
w.setSize(WIDTH, HEIGHT);
w.setLocation(800, 800);
w.setVisible(false);
w.setAlwaysOnTop(true);
//graphics = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
}
private void createShop() {
/***Graphics2D g = (Graphics2D) graphics.getGraphics();
g.setColor(Color.blue);
g.drawString("hey", WIDTH-50, HEIGHT-50);
g.fillRect(0, 0, WIDTH, HEIGHT);*/
}
public class DrawPane extends JPanel {
int width = WIDTH;
int height = HEIGHT;
private ArrayList<Shape> buttons;
private Shape btn1 = new Rectangle2D.Double(20, 60, width/2, height-20);
private Shape btnClose = new Rectangle2D.Double(width-25, 5, 20, 20);
Point wCoords;
Point mCoords;
public DrawPane() {
buttons = new ArrayList<>();
buttons.add(btn1);
buttons.add(btnClose);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
for(Shape s : buttons) {
if(s.contains(e.getPoint())) {
System.out.println("Clicked " + s.getBounds());
if(s == btnClose) {
w.dispose();
}
}
}
}
#Override
public void mousePressed(MouseEvent e) {
mCoords = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
mCoords = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
wCoords = e.getLocationOnScreen();
w.setLocation(wCoords.x - mCoords.x, wCoords.y - mCoords.y);
}
});
}
void repaintThis() {
repaint();
}
BufferedImage img = loadImageFrom.LoadImageFrom(Shop.class, "bar.png");
Graphics gb;
/**
* super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.red);
//g.fillRect(0, 0, width, 50);
g.drawImage(img, 0, 0, width, 50, null);
g.setColor(Color.WHITE);
g.drawString("SHOP", 15, 30);
g.drawString("X", width-20, 20);
for(Shape b : buttons) {
g2d.draw(b);
}
System.out.println("Built");
gb = g;
*/
private void render() {
Graphics2D g = (Graphics2D) graphics.getGraphics();
/////////////////////
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
/////////////////////
g.dispose();
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
}
public void Build() {
Graphics g = gb;
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.red);
//g.fillRect(0, 0, width, 50);
g.drawImage(img, 0, 0, width, 50, null);
g.setColor(Color.WHITE);
g.drawString("SHOP", 15, 30);
g.drawString("X", width-20, 20);
for(Shape b : buttons) {
g2d.draw(b);
}
System.out.println("Built");
}
}
public void render(Graphics2D g) {
drawPane.render();
}
public void addDrawPane() {
drawPane = new DrawPane();
w.add(drawPane);
}
}
If you need access to more code, just ask me.
You should override the paintComponent method like this:
public class DrawPane extends JPanel {
// all your variables and other things
#Override
paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// Your code goes here, use the g2d
}
}
then if you need to repaint your component, simply call repaint() on it.

Java JPanel getGraphics()

Since Java only supports single inheritance, I desire to paint directly on an instance of a JPanel that is a member of the class Panel. I grab an instance of Graphics from the member and then paint whatever I desire onto it.
How can I not inherit from JComponent or JPanel and still utilize getGraphics() for painting on this without overriding public void paintComponent(Graphics g)?
private class Panel {
private JPanel panel;
private Graphics g;
public Panel() {
panel = new JPanel();
}
public void draw() {
g = panel.getGraphics();
g.setColor(Color.CYAN);
g.draw(Some Component);
panel.repaint();
}
}
The panel is added to a JFrame that is made visible prior to calling panel.draw(). This approach is not working for me and, although I already know how to paint custom components by inheriting from JPanel and overriding public void paintComponent(Graphics g), I did not want to inherit from JPanel.
Here are some very simple examples which show how to paint outside paintComponent.
The drawing actually happens on a java.awt.image.BufferedImage, and we can do that anywhere, as long as we're on the Event Dispatch Thread. (For discussion of multithreading with Swing, see here and here.)
Then, I'm overriding paintComponent, but only to paint the image on to the panel. (I also paint a little swatch in the corner.)
This way the drawing is actually permanent, and Swing is able to repaint the panel if it needs to without causing a problem for us. We could also do something like save the image to a file easily, if we wanted to.
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
/**
* Holding left-click draws, and
* right-clicking cycles the color.
*/
class PaintAnyTime {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new PaintAnyTime();
}
});
}
Color[] colors = {Color.red, Color.blue, Color.black};
int currentColor = 0;
BufferedImage img = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D imgG2 = img.createGraphics();
JFrame frame = new JFrame("Paint Any Time");
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Creating a copy of the Graphics
// so any reconfiguration we do on
// it doesn't interfere with what
// Swing is doing.
Graphics2D g2 = (Graphics2D) g.create();
// Drawing the image.
int w = img.getWidth();
int h = img.getHeight();
g2.drawImage(img, 0, 0, w, h, null);
// Drawing a swatch.
Color color = colors[currentColor];
g2.setColor(color);
g2.fillRect(0, 0, 16, 16);
g2.setColor(Color.black);
g2.drawRect(-1, -1, 17, 17);
// At the end, we dispose the
// Graphics copy we've created
g2.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(img.getWidth(), img.getHeight());
}
};
MouseAdapter drawer = new MouseAdapter() {
boolean rButtonDown;
Point prev;
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
prev = e.getPoint();
}
if (SwingUtilities.isRightMouseButton(e) && !rButtonDown) {
// (This just behaves a little better
// than using the mouseClicked event.)
rButtonDown = true;
currentColor = (currentColor + 1) % colors.length;
panel.repaint();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (prev != null) {
Point next = e.getPoint();
Color color = colors[currentColor];
// We can safely paint to the
// image any time we want to.
imgG2.setColor(color);
imgG2.drawLine(prev.x, prev.y, next.x, next.y);
// We just need to repaint the
// panel to make sure the
// changes are visible
// immediately.
panel.repaint();
prev = next;
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
prev = null;
}
if (SwingUtilities.isRightMouseButton(e)) {
rButtonDown = false;
}
}
};
PaintAnyTime() {
// RenderingHints let you specify
// options such as antialiasing.
imgG2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
imgG2.setStroke(new BasicStroke(3));
//
panel.setBackground(Color.white);
panel.addMouseListener(drawer);
panel.addMouseMotionListener(drawer);
Cursor cursor =
Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
panel.setCursor(cursor);
frame.setContentPane(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
It's also possible to set up a JLabel with an ImageIcon, although personally I don't like this method. I don't think JLabel and ImageIcon are required by their specifications to see changes we make to the image after we've passed it to the constructors.
This way also doesn't let us do stuff like painting the swatch. (For a slightly more complicated paint program, on the level of e.g. MSPaint, we'd want to have a way to select an area and draw a bounding box around it. That's another place we'd want to be able to paint directly on the panel, in addition to drawing to the image.)
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
/**
* Holding left-click draws, and
* right-clicking cycles the color.
*/
class PaintAnyTime {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new PaintAnyTime();
}
});
}
Color[] colors = {Color.red, Color.blue, Color.black};
int currentColor = 0;
BufferedImage img = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D imgG2 = img.createGraphics();
JFrame frame = new JFrame("Paint Any Time");
JLabel label = new JLabel(new ImageIcon(img));
MouseAdapter drawer = new MouseAdapter() {
boolean rButtonDown;
Point prev;
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
prev = e.getPoint();
}
if (SwingUtilities.isRightMouseButton(e) && !rButtonDown) {
// (This just behaves a little better
// than using the mouseClicked event.)
rButtonDown = true;
currentColor = (currentColor + 1) % colors.length;
label.repaint();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (prev != null) {
Point next = e.getPoint();
Color color = colors[currentColor];
// We can safely paint to the
// image any time we want to.
imgG2.setColor(color);
imgG2.drawLine(prev.x, prev.y, next.x, next.y);
// We just need to repaint the
// label to make sure the
// changes are visible
// immediately.
label.repaint();
prev = next;
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
prev = null;
}
if (SwingUtilities.isRightMouseButton(e)) {
rButtonDown = false;
}
}
};
PaintAnyTime() {
// RenderingHints let you specify
// options such as antialiasing.
imgG2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
imgG2.setStroke(new BasicStroke(3));
//
label.setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
label.setBackground(Color.white);
label.setOpaque(true);
label.addMouseListener(drawer);
label.addMouseMotionListener(drawer);
Cursor cursor =
Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
label.setCursor(cursor);
frame.add(label, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class SomeComponent extends JComponent {
private Graphics2D g2d;
public void paintComponent(Graphics g) {
g2d = (Graphics2D) g.create();
g2d.setColor(Color.BLACK);
g2d.scale(scale, scale);
g2d.drawOval(0, 0, importance, importance);
}
public Graphics2D getG2d() {
return g2d;
}
public void setG2d(Graphics2D g2d) {
this.g2d = g2d;
}
}
then you can do the following
get the SomeComponent instance in the panel and modify it
Graphics2D x= v.getPanel().get(i).getG2d;
x.setColor(Color.BLUE);
v.getPanel().get(i).setG2d(x);
v.getPanel().repaint();
v.getPanel().revalidate();
V is a class that extends JFrame and contains the panel in it AND
i is instance of SomeComponent

How to make the Panels on JLayeredPane transparent?

I have a JLayeredPane with 4 layers added to it. 1 base layer, which is opaque and three 'transparent' layers (setOpaque(false)).
The problem is that although the panels are drawn onto, with every refresh a gray color is shown. The same thing happens if there is no refresh happening. In other words, instead of showing whatever was drawn onto the base layer, a gray color is shown, I assume this is from one of the layers above.
Here is a SSCCE - I'm not sure if this is short enough but it shows my problem.
public class SSCCE extends JLayeredPane{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(950, 600);
frame.add(new SSCCE());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// private fields
private boolean drawInitial = true;
private boolean drawn = false;
private JPanel overlay, base, iconPanel, middle;
private BufferedImage baseBuffer, midBuffer, overlayBuffer, iconBuffer;
private boolean updateInit = true;
private Rectangle2D stored = new Rectangle2D.Double(60, 60, 40, 100);
public SSCCE() {
setBorder(new LineBorder(Color.BLACK));
setDoubleBuffered(false);
setOpaque(true);
setSize(new Dimension(950, 600));
setPreferredSize(new Dimension(950, 600));
base = new JPanel();
base.setBackground(new Color(0,0,0,0));
base.setSize(new Dimension(getWidth(), getHeight()));
this.add(base, new Integer(0));
middle = new JPanel();
middle.setSize(new Dimension(getWidth(), getHeight()));
middle.setBackground(new Color(0,0,0,0));
middle.setOpaque(false);
this.add(middle, new Integer(1));
overlay = new JPanel();
overlay.setBackground(new Color(0,0,0,0));
overlay.setOpaque(false);
overlay.setSize(new Dimension(getWidth(), getHeight()));
this.add(overlay, new Integer(2));
iconPanel = new JPanel();
iconPanel.setBackground(new Color(0,0,0,0));
iconPanel.setSize(getWidth(), getHeight());
iconPanel.setOpaque(false);
this.add(iconPanel, new Integer(3));
}
public void update() {
if(updateInit){
checkBuffer();
updateInit = false;
}
drawInfoRect();
drawIcon();
highlightPath(stored);
}
public void render() {
if (drawInitial) {
Graphics2D baseGraphics = (Graphics2D) base.getGraphics();
baseGraphics.drawImage(baseBuffer, 0, 0, null);
}
setResistanceColor((Graphics2D)baseBuffer.getGraphics());
middle.getGraphics().drawImage(midBuffer, 0, 0, null);
iconPanel.getGraphics().drawImage(iconBuffer, 0, 0, null);
drawInfoRect();
base.getGraphics().drawImage(baseBuffer, 0, 0, null);
if (drawn) {
overlay.getGraphics().drawImage(overlayBuffer, 0, 0, null);
}
repaint();
}
// /**
// * draws the appropriate colour
// */
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
update();
render();
}
/**
* sets the appropriate colours according to the resistance
* #param g2
*/
private void setResistanceColor(Graphics2D g2) {
Rectangle2D sp = new Rectangle2D.Double(50,50, 50, 50);
g2.setColor(Color.GREEN);
g2.fill(sp);
g2.setColor(Color.BLACK);
}
/**
* checks if there already exists an image to buffer with
*/
private void checkBuffer() {
if (baseBuffer == null) {
baseBuffer = (new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB));
// background color
Graphics2D g2 = (Graphics2D) baseBuffer.getGraphics();
g2.setColor(Color.decode("#729fcf"));
Rectangle2D rect = new Rectangle2D.Double(0, 0, baseBuffer.getWidth(), baseBuffer.getHeight());
g2.fill(rect);
}
if (midBuffer == null) {
midBuffer = (new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB));
// background color
Graphics2D g2 = (Graphics2D) midBuffer.getGraphics();
g2.setColor(Color.RED);
Rectangle2D rect = new Rectangle2D.Double(0, 0, midBuffer.getWidth(), midBuffer.getHeight());
g2.fill(rect);
}
if (overlayBuffer == null) {
overlayBuffer = (new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB));
}
if (iconBuffer == null) {
iconBuffer = (new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB));
}
}
public void highlightPath(Shape enlighten) {
Area area = new Area();
area.add(new Area(enlighten));
// clearing image before drawing
Graphics2D midBufferG = (Graphics2D) midBuffer.getGraphics();
clearImage(midBufferG);
midBufferG.setColor(Color.white);
// adds a transparent overlay
midBufferG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.50f));
midBufferG.fill(area);
}
public void drawIcon() {
Graphics2D iconG = (Graphics2D) iconBuffer.getGraphics();
clearImage(iconG);
}
public void drawInfoRect() {
Graphics2D graph = (Graphics2D) overlayBuffer.getGraphics();
Rectangle2D visible = getVisibleRect();
int boxX = (int) (visible.getX() + 50);
int boxY = (int) (visible.getY() + 450);
RoundRectangle2D rect = new RoundRectangle2D.Double(boxX, boxY, 200, 150, 25, 25);
graph.setColor(Color.decode("#729fcf").darker());
graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f));
graph.fill(rect);
graph.setColor(Color.BLACK);
drawn = true;
}
private void clearImage(Graphics2D graph){
graph.setComposite(AlphaComposite.Clear);
graph.fillRect(0, 0, overlayBuffer.getWidth(), overlayBuffer.getHeight());
graph.setComposite(AlphaComposite.SrcOver);
}
}
It might be some basic mistake I made. Thanks for your help!
One of the previously suggested answers actually solved my question, but for some reason they deleted their answer.
Setting the Background of my panels to setBackground(new
Color(0,0,0,0)); solved my problems.
According to the person that suggested this, the cause of that is the fact that JComponent may or may not draw transparent if not explicitly specified.
Thanks again!

How to draw an outline around text in AWT?

How can I draw an outline around any text in AWT, something similar to this picture?
two examples
Font and AffineTransform
Font, TextLayout and AffineTransform
output from this paint would be the BufferedImage, for AWT Components use method paint(), for Swing JComponents is there paintComponet()
Also, from code linked in a comment:
Try the following:
public void paintTextWithOutline(Graphics g) {
String text = "some text";
Color outlineColor = Color.white;
Color fillColor = Color.black;
BasicStroke outlineStroke = new BasicStroke(2.0f);
if (g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D) g;
// remember original settings
Color originalColor = g2.getColor();
Stroke originalStroke = g2.getStroke();
RenderingHints originalHints = g2.getRenderingHints();
// create a glyph vector from your text
GlyphVector glyphVector = getFont().createGlyphVector(g2.getFontRenderContext(), text);
// get the shape object
Shape textShape = glyphVector.getOutline();
// activate anti aliasing for text rendering (if you want it to look nice)
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(outlineColor);
g2.setStroke(outlineStroke);
g2.draw(textShape); // draw outline
g2.setColor(fillColor);
g2.fill(textShape); // fill the shape
// reset to original settings after painting
g2.setColor(originalColor);
g2.setStroke(originalStroke);
g2.setRenderingHints(originalHints);
}
}
Not sure how you're drawing the text now, but one way you could do it is use a BufferedImage as an overlay to whatever it is that you're drawing on.
Create BufferedImage using the dimensions of the string and font you are wanting to draw with (look at FontMetrics class for this).
Fill the BufferedImage with transparency.
Draw your string onto the BufferedImage with whatever color you want.
Iterate over every pixel in the BufferedImage and see how far away it is from a pixel of your text's color. If it's within a certain distance, draw that pixel black, and maybe more transparent if it's further away from the color of your text. Of course, if the pixel is already the same color as your text color, then ignore it.
Draw BufferedImage onto whatever it is that you're painting onto.
EDIT
There may be libraries out there that already do this, but if I had to code it from scratch, this is how I'd try to do it.
Here is a hacky example. It is not as sophisticated as others, but it is simpler to understand, and it behaves like a JLabel.
public class OutlineLabel extends JLabel {
private Color outlineColor = Color.WHITE;
private boolean isPaintingOutline = false;
private boolean forceTransparent = false;
public OutlineLabel() {
super();
}
public OutlineLabel(String text) {
super(text);
}
public OutlineLabel(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
}
public Color getOutlineColor() {
return outlineColor;
}
public void setOutlineColor(Color outlineColor) {
this.outlineColor = outlineColor;
this.invalidate();
}
#Override
public Color getForeground() {
if ( isPaintingOutline ) {
return outlineColor;
} else {
return super.getForeground();
}
}
#Override
public boolean isOpaque() {
if ( forceTransparent ) {
return false;
} else {
return super.isOpaque();
}
}
#Override
public void paint(Graphics g) {
String text = getText();
if ( text == null || text.length() == 0 ) {
super.paint(g);
return;
}
// 1 2 3
// 8 9 4
// 7 6 5
if ( isOpaque() )
super.paint(g);
forceTransparent = true;
isPaintingOutline = true;
g.translate(-1, -1); super.paint(g); // 1
g.translate( 1, 0); super.paint(g); // 2
g.translate( 1, 0); super.paint(g); // 3
g.translate( 0, 1); super.paint(g); // 4
g.translate( 0, 1); super.paint(g); // 5
g.translate(-1, 0); super.paint(g); // 6
g.translate(-1, 0); super.paint(g); // 7
g.translate( 0, -1); super.paint(g); // 8
g.translate( 1, 0); // 9
isPaintingOutline = false;
super.paint(g);
forceTransparent = false;
}
public static void main(String[] args) {
JFrame w = new JFrame();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
OutlineLabel label = new OutlineLabel("Test", OutlineLabel.CENTER);
label.setOpaque(true);
w.setContentPane(new JPanel(new BorderLayout()));
w.add(label, BorderLayout.CENTER);
w.pack();
w.setVisible(true);
}
}
some stupidest workarounds:
-type same words twice but one of them is black and the other is white, put white on top of the black one, you may get something similar.
-find a font looks like above the example, and use it.

Categories