import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.util.List;
class JustifyPanel extends JPanel
{
private String text;
public JustifyPanel(String text)
{
this.text = text;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawJustified(g, text, getWidth());
}
private void drawJustified(Graphics g, String s, int w)
{
List<String> allWords = Arrays.asList(s.split(" "));
FontMetrics fm = g.getFontMetrics();
double lineHeight = (int)fm.getStringBounds("fg", g).getHeight();
int index = 0;
int y = (int)lineHeight;
while (index < allWords.size())
{
List<String> subList = new ArrayList<String>();
index = computeSublist(g, allWords, index, subList, w);
int width = computeWidth(g, subList);
System.out.println("Words until "+index+": "+subList+" width "+width);
draw(g, subList, width, w, y);
y += lineHeight;
}
}
private int computeSublist(Graphics g, List<String> allWords, int startIndex, List<String> subList, int w)
{
FontMetrics fm = g.getFontMetrics();
double spaceWidth = (int)fm.getStringBounds(" ", g).getWidth();
double x = 0;
int index = startIndex;
while (index < allWords.size())
{
String word = allWords.get(index);
Rectangle2D r = fm.getStringBounds(word+" ", g);
x += (int)(r.getWidth() + spaceWidth);
if (x > w)
{
if (subList.size() == 0)
{
subList.add(word);
return index+1;
}
break;
}
subList.add(word);
index++;
}
return index;
}
private int computeWidth(Graphics g, List<String> words)
{
FontMetrics fm = g.getFontMetrics();
double spaceWidth = (int)fm.getStringBounds(" ", g).getWidth();
double width = 0;
for (int i=0; i<words.size(); i++)
{
Rectangle2D r = fm.getStringBounds(words.get(i)+" ", g);
width += (int)(r.getWidth() + spaceWidth);
}
return (int)width;
}
private void draw(Graphics g, List<String> words, int wordsWidth, int w, int y)
{
FontMetrics fm = g.getFontMetrics();
double remaining = (w - wordsWidth);
double fill = 0;
if (words.size() > 0)
{
fill = remaining / (words.size()-1);
}
double x = 0;
for (int i=0; i<words.size(); i++)
{
g.drawString(words.get(i), (int)x, y);
x += fm.getStringBounds(words.get(i)+" ", g).getWidth() + fill;
}
}
}
class JustifyTest
{
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JustifyPanel(
"Lorem ipsum dolor sit amet, consectetur adipisicing "+
"elit, sed do eiusmod tempor incididunt ut labore et "+
"dolore magna aliqua. Ut enim ad minim veniam, quis "+
"nostrud exercitation ullamco laboris nisi ut aliquip "+
"ex ea commodo consequat. Duis aute irure dolor in "+
"reprehenderit in voluptate velit esse cillum dolore eu "+
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat "+
"non proident, sunt in culpa qui officia deserunt mollit "+
"anim id est laborum."
));
f.setSize(300,300);
f.setVisible(true);
}
});
}
}