Originariamente inviato da TheWarLord
non ne ho idea

...ma... cosa centra?
Centra.
codice:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class TestFrame extends JFrame {
private JEditorPane editorPane;
public TestFrame() {
super("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
editorPane = new JEditorPane("text/html", "<html><body>
prova di testo <big>html</big></p></body></html>");
JScrollPane scrollPane = new JScrollPane(editorPane);
JButton insertButton = new JButton("Sostituisci selezione");
insertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String nuovoTesto = JOptionPane.showInputDialog(TestFrame.this, "Inserisci nuovo testo");
int start = editorPane.getSelectionStart();
int end = editorPane.getSelectionEnd();
SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, Color.RED);
StyleConstants.setItalic(attr, true);
StyleConstants.setBold(attr, true);
try {
HTMLDocument htmlDoc = (HTMLDocument) editorPane.getDocument();
htmlDoc.replace(start, end-start, nuovoTesto, null);
htmlDoc.setCharacterAttributes(start, nuovoTesto.length(), attr, false);
} catch (BadLocationException ex) {
// Non dovrebbe succedere.
}
}
});
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(insertButton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestFrame().setVisible(true);
}
});
}
}
Seleziona del testo, clicca sul pulsante, inserisci del testo e questo testo sostituirà la selezione e verrà messo come rosso/italico/grassetto (i set degli attributi mi sembrano chiari, no?).