Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Swing Code Examples

JTextPane Attributes

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
JTextPane Attributes import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class TextPaneAttributes extends JFrame { public TextPaneAttributes() { JTextPane textPane = new JTextPane(); StyledDocument doc = textPane.getStyledDocument(); // Set alignment to be centered for all paragraphs MutableAttributeSet standard = new SimpleAttributeSet(); StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER); doc.setParagraphAttributes(0, 0, standard, true); // Define a keyword attribute MutableAttributeSet keyWord = new SimpleAttributeSet(); StyleConstants.setForeground(keyWord, Color.red); StyleConstants.setItalic(keyWord, true); // Add initial text textPane.setText( "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n" ); // Highlight some keywords doc.setCharacterAttributes(0, 3, keyWord, false); doc.setCharacterAttributes(19, 4, keyWord, false); // Add some text try { doc.insertString(0, "Start of text\n", null ); doc.insertString(doc.getLength(), "End of text\n", keyWord ); } catch(Exception e) {} // Add text pane to frame JScrollPane scrollPane = new JScrollPane( textPane ); scrollPane.setPreferredSize( new Dimension( 200, 200 ) ); getContentPane().add( scrollPane ); // Add a bold button JButton button = new JButton("bold"); getContentPane().add(button, BorderLayout.SOUTH); button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { new StyledEditorKit.BoldAction().actionPerformed(null); } }); } public static void main(String[] args) { TextPaneAttributes frame = new TextPaneAttributes(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.pack(); frame.setVisible(true); } }