/*
* DocumentTest.java
*/
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class DocumentTest extends JFrame {
public DocumentTest() {
super("Document Test");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400,300);
setLocationRelativeTo(null);
//JComponents erzeugen:
colorButton = new JButton("Text färben");
toolbar = new JToolBar();
document = new DefaultStyledDocument();
textpane = new JTextPane(document);
//Layout:
textpane.setText("Document Test");
toolbar.add(colorButton);
getContentPane().add(toolbar, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(textpane), BorderLayout.CENTER);
//Listener:
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textFaerben();
}
});
}
private void textFaerben() {
int ende = textpane.getSelectionEnd();
int anfang = textpane.getSelectionStart();
if (ende == anfang) {
JOptionPane.showMessageDialog(this, "Bitte Text auswählen",
"Document Test", JOptionPane.ERROR_MESSAGE);
return;
}
Color farbe = null;
farbe = JColorChooser.showDialog(this, "Farbe", farbe);
if (farbe != null) {
Style style = document.addStyle("Farbe:"+farbe.getRGB(), null);
StyleConstants.setForeground(style, farbe);
document.setCharacterAttributes(anfang, ende-anfang, style, true);
}
}
public static void main(String[] args) { new DocumentTest().setVisible(true); }
private JButton colorButton;
private JToolBar toolbar;
private StyledDocument document;
private JTextPane textpane;
}