Break lines in g.drawString in Java SE

This is exactly what I'm trying to do:

Graphics2D g2 = (Graphics2D) g; g2.setFont(new Font("Serif", Font.PLAIN, 5)); g2.setPaint(Color.black); g2.drawString("Line 1\nLine 2", x, y); 

This line is printed as follows:

 Line1Line2 

I want like this:

 Line1 Line2 

How to do this in drawString ?

How can I make a tab for a row

+4
source share
2 answers



        private void drawString (Graphics g, String text, int x, int y) {
                 for (String line: text.split ("\ n"))
                     g.drawString (line, x, y + = g.getFontMetrics (). getHeight ());
             }

        private void drawtabString (Graphics g, String text, int x, int y) {
             for (String line: text.split ("\ t"))
                 g.drawString (line, x + = g.getFontMetrics (). getHeight (), y);
         }


             Graphics2D g2 = (Graphics2D) g;
             g2.setFont (new Font ("Serif", Font.PLAIN, 5));
             g2.setPaint (Color.black);
             drawString (g2, "Line 1 \ nLine 2", 120, 120);
             drawtabString (g2, "Line 1 \ tLine 2", 130, 130);

 
+5
source

Here is a snippet that I used to draw text in JPanel with tab expansion and multiple lines:

 import javax.swing.*; import java.awt.*; import java.awt.geom.Rectangle2D; public class Scratch { public static void main(String argv[]) { JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paint(Graphics graphics) { graphics.drawRect(100, 100, 1, 1); String message = "abc\tdef\n" + "abcx\tdef\tghi\n" + "xxxxxxxxdef\n" + "xxxxxxxxxxxxxxxxghi\n"; int x = 100; int y = 100; FontMetrics fontMetrics = graphics.getFontMetrics(); Rectangle2D tabBounds = fontMetrics.getStringBounds( "xxxxxxxx", graphics); int tabWidth = (int)tabBounds.getWidth(); String[] lines = message.split("\n"); for (String line : lines) { int xColumn = x; String[] columns = line.split("\t"); for (String column : columns) { if (xColumn != x) { // Align to tab stop. xColumn += tabWidth - (xColumn-x) % tabWidth; } Rectangle2D columnBounds = fontMetrics.getStringBounds( column, graphics); graphics.drawString( column, xColumn, y + fontMetrics.getAscent()); xColumn += columnBounds.getWidth(); } y += fontMetrics.getHeight(); } } @Override public Dimension getPreferredSize() { return new Dimension(400, 200); } }; frame.getContentPane().add(panel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } } 

It seemed to me that Utilities.drawTabbedText() was promising, but I could not understand what it needed for input.

0
source

Source: https://habr.com/ru/post/1388556/


All Articles