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...