Mega Code Archive

 
Categories / Java / 2D Graphics GUI
 

Drawing Text with Mixed Styles

import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.text.AttributedString; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel {   public void paint(Graphics g) {     Graphics2D g2d = (Graphics2D) g;     AttributedString astr = new AttributedString("aString");     astr.addAttribute(TextAttribute.FONT, new Font("", 1, 30), 1, 2);     astr.addAttribute(TextAttribute.BACKGROUND, Color.red, 2, 3);     TextLayout tl = new TextLayout(astr.getIterator(), g2d.getFontRenderContext());     tl.draw(g2d, 10, 20);   }   public static void main(String[] args) {     JFrame frame = new JFrame("Basic Shapes");     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.add(new Main());     frame.setSize(350, 250);     frame.setLocationRelativeTo(null);     frame.setVisible(true);   } }