I know how to draw a rounded rectangle but I want to define roundness for each corner separately and draw something like the image below :
There's probably a few ways to achieve this, but the easiest I can think of would be to, as Andrew has already hinted, would be to define your own Shape
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Path2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SimpleShape {
public static void main(String[] args) {
new SimpleShape();
}
public SimpleShape() {
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.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private RightEnd rightEnd;
public TestPane() {
rightEnd = new RightEnd(100, 100, 40);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - 100) / 2;
int y = (getHeight()- 100) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.translate(x, y);
g2d.fill(rightEnd);
g2d.dispose();
}
}
public class RightEnd extends Path2D.Float {
public RightEnd(float width, float height, float radius) {
moveTo(0, 0);
lineTo(width - radius, 0);
curveTo(width, 0, width, 0, width, radius);
lineTo(width, height - radius);
curveTo(width, height, width, height, width - radius, height);
lineTo(0, height);
closePath();
}
}
}
Related
I have this code. I need to make this square flexible when I resize JFrame. The size of square should change in percentage. this.getWidth(),this.getHeight() returns (0,0);
super.getWidth(), super.getHeight() returns (0,0);
getWidth(), getHeight() returns (0,0);
No examples found by me. I have nothing more to add. Thank you very much!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Parker {
public static void main(String[] args) {
new Parker();
}
public Parker() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ControlPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ControlPane extends JPanel {
private JSlider slider;
private DrawPane myPanel;
public ControlPane() {
setLayout(new BorderLayout());
myPanel = new DrawPane();
myPanel.setBackground(Color.WHITE);
Dimension dim = myPanel.getSize();
slider = new JSlider(SwingConstants.HORIZONTAL,0,100,20);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setValue(0);
slider.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Slider"),
BorderFactory.createEmptyBorder(15,10,15,10)
)
);
slider.addChangeListener(
new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
myPanel.setScale(slider.getValue());
}
}
);
add(slider,BorderLayout.SOUTH);
add(myPanel,BorderLayout.CENTER);
}
}
public class DrawPane extends JPanel {
double scale = 1;
double angle = 0;
//here i tried different methods to find current size of frame, you can
//set some int values like 10 or 100 to watch that everything works
//properly
int rectWidth = ;
int rectHeight = ;
public void componentResized(ComponentEvent e) {
Dimension newSize = e.getComponent().getBounds().getSize();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int originX = getWidth() / 2;
int originY = getHeight() / 2;
int xOffset = -(rectWidth / 2);
int yOffset = -(rectHeight / 2);
g.setColor(Color.BLACK);
Graphics2D g2d = (Graphics2D) g.create();
g2d.translate(originX, originY);
g2d.scale(scale, scale);
g2d.fill(new Rectangle2D.Double(xOffset, yOffset, rectWidth, rectHeight));
g2d.dispose();
g.setColor(Color.RED);
g.drawRect(originX + xOffset, originY + yOffset, rectWidth, rectWidth);
}
public void setScale(int scale) {
this.scale = (scale / 100d);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
}
}
you should register a ComponentListener to your ControlPanel which is the main content pane of your JFrame for listening resize event's (also listens for initial resizing) and make the rectangle resize,
try this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.Rectangle2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Parker {
public static void main(String[] args) {
new Parker();
}
public Parker() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ControlPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ControlPane extends JPanel {
private JSlider slider;
private DrawPane myPanel;
public ControlPane() {
setLayout(new BorderLayout());
myPanel = new DrawPane();
myPanel.setBackground(Color.WHITE);
Dimension dim = myPanel.getSize();
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
Dimension dim = e.getComponent().getSize();
myPanel.resizeRectangle(dim.width / 2, dim.height / 2);
}
});
slider = new JSlider(SwingConstants.HORIZONTAL, 0, 100, 20);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setValue(0);
slider.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Slider"),
BorderFactory.createEmptyBorder(15, 10, 15, 10)));
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
myPanel.setScale(slider.getValue());
}
});
add(slider, BorderLayout.SOUTH);
add(myPanel, BorderLayout.CENTER);
}
}
public class DrawPane extends JPanel {
double scale = 1;
double angle = 0;
int rectWidth = 50;
int rectHeight = 50;
public void componentResized(ComponentEvent e) {
Dimension newSize = e.getComponent().getBounds().getSize();
}
public void resizeRectangle(int width, int height) {
rectWidth = width;
rectHeight = height;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int originX = getWidth() / 2;
int originY = getHeight() / 2;
int xOffset = -(rectWidth / 2);
int yOffset = -(rectHeight / 2);
g.setColor(Color.BLACK);
Graphics2D g2d = (Graphics2D) g.create();
g2d.translate(originX, originY);
g2d.scale(scale, scale);
g2d.fill(new Rectangle2D.Double(xOffset, yOffset, rectWidth, rectHeight));
g2d.dispose();
g.setColor(Color.RED);
g.drawRect(originX + xOffset, originY + yOffset, rectWidth, rectWidth);
}
public void setScale(int scale) {
this.scale = (scale / 100d);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
}
}
I am trying to create an extended JPanel that acts as a way to highlight some region of the screen. I have taken some code from this SO answer but would like to extend it further though I am not sure how to go about it.
I would like to be able to have my JPanel (MatchAreaPanel below) disappear after a given timeout is reached. That is the JPanel sets its visible property to false and subsequently disposes of itself.
What would be the best way to go about doing this?
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class MatchAreaPanel extends JPanel
{
public MatchAreaPanel()
{
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(128, 128, 128, 64));
g2d.fillRect(0, 0, getWidth(), getHeight());
float dash1[] = {10.0f};
BasicStroke dashed = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 3, getHeight() - 3);
g2d.dispose();
}
}
You could use a Swing Timer to simply schedule a callback after a given delay and close the associated window or hide the component based on your needs, for example...
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Rectangle bounds = getVirtualBounds();
Random rnd = new Random();
int x = bounds.x + (rnd.nextInt(bounds.width) - 100);
int y = bounds.y + (rnd.nextInt(bounds.height) - 100);
MatchAreaPanel pane = new MatchAreaPanel();
JWindow frame = new JWindow();
frame.setBackground(new Color(0, 0, 0, 0));
frame.add(pane);
frame.setBounds(x, y, 100, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
pane.start();
}
});
}
public static Rectangle getVirtualBounds() {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
bounds.add(gd.getDefaultConfiguration().getBounds());
return bounds;
}
public class MatchAreaPanel extends JPanel {
public MatchAreaPanel() {
setOpaque(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
SwingUtilities.windowForComponent(MatchAreaPanel.this).dispose();
}
});
}
public void start() {
Timer timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.windowForComponent(MatchAreaPanel.this).dispose();
}
});
timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(128, 128, 128, 64));
g2d.fillRect(0, 0, getWidth(), getHeight());
float dash1[] = {10.0f};
BasicStroke dashed = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 3, getHeight() - 3);
g2d.dispose();
}
}
}
See How to use Swing Timers for more details
Updated...
Now, simply "hiding" the panel is, boring, it's also possible for the user to miss the panel, as suddenly showing up is no guarantee that the user will see it, so instead, you could add in a fade out effect.
In this example, you can fade the panel out by clicking it (but I did this as part of my testing, so you don't need it) or after the specified time out...
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Rectangle bounds = getVirtualBounds();
Random rnd = new Random();
int x = bounds.x + (rnd.nextInt(bounds.width) - 100);
int y = bounds.y + (rnd.nextInt(bounds.height) - 100);
MatchAreaPanel pane = new MatchAreaPanel();
JWindow frame = new JWindow();
frame.setBackground(new Color(0, 0, 0, 0));
frame.add(pane);
frame.setBounds(x, y, 100, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
pane.start();
}
});
}
public static Rectangle getVirtualBounds() {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
bounds.add(gd.getDefaultConfiguration().getBounds());
return bounds;
}
public static class MatchAreaPanel extends JPanel {
protected static final long FADE_OUT_TIME = 2500;
private float alpha = 1f;
private long fadeStartAt;
private Timer fadeTimer;
private Timer waitTimer;
public MatchAreaPanel() {
setOpaque(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
fadeOut();
}
});
fadeTimer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
long runTime = System.currentTimeMillis() - fadeStartAt;
float progress = 0f;
if (runTime >= FADE_OUT_TIME) {
progress = 1f;
} else {
progress = (float) runTime / (float) FADE_OUT_TIME;
if (progress > 1f) {
progress = 1f;
}
}
alpha = 1f - progress;
if (progress >= 1f) {
((Timer) e.getSource()).stop();
SwingUtilities.windowForComponent(MatchAreaPanel.this).dispose();
}
repaint();
}
});
waitTimer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((Timer) e.getSource()).stop();
fadeOut();
}
});
}
protected void fadeOut() {
waitTimer.stop();
fadeStartAt = System.currentTimeMillis();
fadeTimer.start();
}
public void start() {
if (!waitTimer.isRunning() && !fadeTimer.isRunning()) {
waitTimer.start();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
g2d.setColor(new Color(128, 128, 128, 64));
g2d.fillRect(0, 0, getWidth(), getHeight());
float dash1[] = {10.0f};
BasicStroke dashed = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 3, getHeight() - 3);
g2d.dispose();
}
}
}
Can anyone help me figure out how to make a 2d graphic tree? This is all I have so far. I have no clue what I am doing:/ Can someone teach me how to..please? & thank you!
import java.awt.Color;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Polygon;
public class Tree extends Canvas {
public Tree() {
350 200 100 350
249 0 249
}
}
Start by having a look at 2D Graphics. You might also like to have a look at Painting in AWT and Swing and Performing Custom Painting for more details about painting in Swing and AWT
Simple tree...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Forest {
public static void main(String[] args) {
new Forest();
}
public Forest() {
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.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
g2d.setColor(new Color(139, 69, 19));
g2d.fillRect((width / 2) - 20, height / 2, 40, height / 2);
g2d.setColor(Color.GREEN);
int radius = 60;
g2d.fillOval((width / 2) - radius, (height / 2) - (radius), radius * 2, radius * 2);
g2d.dispose();
}
}
}
Complex Tree...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Forest {
public static void main(String[] args) {
new Forest();
}
public Forest() {
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.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
g2d.setColor(new Color(139, 69, 19));
g2d.fillRect((width / 2) - 20, height / 2, 40, height / 2);
g2d.setColor(Color.GREEN);
int radius = 60;
g2d.fillOval((width / 2) - radius, (height / 2) - (radius * 2), radius * 2, radius * 2);
g2d.fillOval((width / 2) - radius, (height / 2) - radius, radius * 2, radius * 2);
g2d.fillOval((width / 2) - (radius * 2), (height / 2) - radius, radius * 2, radius * 2);
g2d.fillOval((width / 2), (height / 2) - radius, radius * 2, radius * 2);
g2d.dispose();
}
}
}
I want the string to have different width so that I set the stroke of Graphics2D and the code is here:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class StrokeTest {
public static void main(String[] args) {
StrokeTest test = new StrokeTest();
test.createUI();
}
public void createUI(){
JFrame frame = new JFrame();
frame.add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#SuppressWarnings("serial")
class MainPanel extends JPanel{
public MainPanel(){
setPreferredSize(new Dimension(400, 300));
}
protected void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.red);
g2d.setStroke(new BasicStroke(10));
g2d.drawString("I am a string", 100, 100);
}
}
}
However, it doesn't work when I use g2d.setStroke(new BasicStroke(10));
Thanks in advance for your help.
Basically, fonts/text are rendered using a different process then other graphics elements, so they are generally unaffected by such things as stroke.
In order to render text with a stroke, you need to convert it to a Shape first, for example...
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TextStroke {
public static void main(String[] args) {
new TextStroke();
}
public TextStroke() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
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() {
Font font = getFont();
setFont(font.deriveFont(Font.PLAIN, 80));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
FontRenderContext frc = g2d.getFontRenderContext();
String s = "Look ma, I'm Stroked";
TextLayout textTl = new TextLayout(s, getFont(), frc);
Shape outline = textTl.getOutline(null);
FontMetrics fm = g2d.getFontMetrics(getFont());
int x = (getWidth() - outline.getBounds().width) / 2;
int y = ((getHeight() - outline.getBounds().height) / 2) + fm.getAscent();
g2d.translate(x, y);
// Stroke stroke = g2d.getStroke();
g2d.setColor(Color.BLACK);
g2d.fill(outline);
g2d.setStroke(new BasicStroke(5));
g2d.setColor(Color.RED);
g2d.draw(outline);
g2d.dispose();
}
}
}
Given the following :
public class NavigationCanvas extends Canvas implements MouseListener,MouseMotionListener,KeyListener {
public void paint(Graphics g)
{
// some code
// more
// ...
g.setColor(Color.black);
// drawing each Line
for (int i=0; i<length; i++)
{
Line2D currLine = m_lines.get(i);
g.drawLine((int)currLine.getX1(),(int)currLine.getY1(),
(int)currLine.getX2(),(int)currLine.getY2());
g.drawLine((int)currLine.getX1()+1,(int)currLine.getY1()+1
,(int)currLine.getX2()+1,(int)currLine.getY2()+1);
g.drawLine((int)currLine.getX1()+2,(int)currLine.getY1()+2
,(int)currLine.getX2()+2,(int)currLine.getY2()+2);
}
}
...
}
When I draw the lines of currLine I get this :
As you can see , I made 3 calls to drawline() , to make it more bold ,but it still doesn't quite
as I wanted .
How can I draw one bold line ?
Graphics2D#setStroke controls the style of line that is painted. BasicStroke is the default implementation of Stroke and has a number of parameters, the one you're most interested in is the width.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestStroke {
public static void main(String[] args) {
new TestStroke();
}
public TestStroke() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
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 {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
int xDif = width / 4;
int yDif = height / 4;
g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.drawLine(xDif, yDif, width - xDif, yDif);
g2d.setStroke(new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.drawLine(width - xDif, yDif, width - xDif, height - yDif);
g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.drawLine(width - xDif, height - yDif, xDif, height - yDif);
g2d.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.drawLine(xDif, height - yDif, xDif, yDif);
g2d.dispose();
}
}
}
Have a look at Stroking and filling Graphics Primitives for more details
Use the setStroke() method located in the Graphics library: http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Graphics2D.html
setStroke(Stroke s)
Sets the Stroke for the Graphics2D context.
It takes a Stroke object, http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Stroke.html