Find out the text boundary with BreakIterator in Java
Description
The following code shows how to find out the text boundary with BreakIterator.
Example
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.BreakIterator;
import java.util.Locale;
/*from w w w . j a va 2 s. c om*/
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
JFrame frame = new TextBoundaryFrame();
frame.show();
}
}
class TextBoundaryFrame extends JFrame {
Locale[] locales;
private BreakIterator currentBreakIterator;
private JComboBox localeCombo = new JComboBox();
private JTextArea inputText = new JTextArea(6, 40);
private JCheckBox characterCheckBox = new JCheckBox("Character");
private JCheckBox wordCheckBox = new JCheckBox("Word");
private JCheckBox lineCheckBox = new JCheckBox("Line");
private JCheckBox sentenceCheckBox = new JCheckBox("Sentence");
public TextBoundaryFrame() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
JPanel p = new JPanel();
p.add(characterCheckBox);
p.add(wordCheckBox);
p.add(lineCheckBox);
p.add(sentenceCheckBox);
add(new JLabel("Locale"));
add(localeCombo);
add(p);
add(new JScrollPane(inputText));
locales = BreakIterator.getAvailableLocales();
for (int i = 0; i < locales.length; i++)
localeCombo.addItem(locales[i].getDisplayName());
localeCombo.setSelectedItem(Locale.getDefault().getDisplayName());
localeCombo.addActionListener(listener);
inputText.setText("The quick, brown fox jump-ed\n"
+ "over the lazy \"dog.\" And then...what happened?");
updateDisplay();
}
public void updateDisplay() {
Locale currentLocale = locales[localeCombo.getSelectedIndex()];
BreakIterator currentBreakIterator = null;
currentBreakIterator = BreakIterator
.getCharacterInstance(currentLocale);
if (characterCheckBox.isSelected())
currentBreakIterator = BreakIterator
.getCharacterInstance(currentLocale);
else if (wordCheckBox.isSelected())
currentBreakIterator = BreakIterator.getWordInstance(currentLocale);
else if (lineCheckBox.isSelected())
currentBreakIterator = BreakIterator.getLineInstance(currentLocale);
else if (sentenceCheckBox.isSelected())
currentBreakIterator = BreakIterator
.getSentenceInstance(currentLocale);
String text = inputText.getText();
currentBreakIterator.setText(text);
int from = currentBreakIterator.first();
int to;
while ((to = currentBreakIterator.next()) != BreakIterator.DONE) {
System.out.println(text.substring(from, to) + "|");
from = to;
}
System.out.println(text.substring(from));
}
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
updateDisplay();
}
};
}
The code above generates the following result.