JTextPane: How to set the font size - java

Please have a look at the following code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Form extends JFrame
{
private JTextPane textPane;
private JLabel results;
private JPanel center,south;
private FlowLayout flow;
private ArrayList array;
private Color color;
private StyledDocument doc;
private Style style, fontSize;
public Form()
{
textPane = new JTextPane();
textPane.setMinimumSize(new Dimension(100,100));
doc = textPane.getStyledDocument();
doc.addDocumentListener(new TextActions());
results = new JLabel("Number of letters: ");
array = new ArrayList();
array.add("public");
array.add("static");
array.add("void");
array.add("private");
array.add("protected");
color = new Color(185,224,247);
//Adding styles
style = doc.addStyle("blue", null);
StyleConstants.setForeground(style, color);
fontSize = doc.addStyle("fontSize", null);
StyleConstants.setFontSize(fontSize, 25);
//Setting the font Size
doc.setCharacterAttributes(0, doc.getLength(), fontSize, false);
center = new JPanel();
flow = new FlowLayout();
center.setLayout(flow);
center.add(textPane);
south = new JPanel();
south.setLayout(new FlowLayout());
south.add(results);
getContentPane().add(textPane,"Center");
getContentPane().add(south,"South");
}
private class TextActions implements DocumentListener
{
#Override
public void insertUpdate(DocumentEvent e)
{
try {
highlighat();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
#Override
public void removeUpdate(DocumentEvent e)
{
try {
highlighat();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
#Override
public void changedUpdate(DocumentEvent e)
{
}
}
private void highlighat() throws BadLocationException
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
String text = "";
String content = null;
try {
content = doc.getText(0, doc.getLength()).toLowerCase();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
int last=0;
for(int i=0;i<array.size();i++)
{
text = array.get(i).toString();
if(content.contains(text))
{
while((last=content.indexOf(text,last))!=-1)
{
int end = last+text.length();
doc.setCharacterAttributes(last, end, textPane.getStyle("blue"), true);
last++;
}
}
}
}
}
);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
}
Form f = new Form();
f.setVisible(true);
f.setSize(800,600);
f.validate();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
In there, I am also trying to set the font size to 25, but as you can see, it is not working. "textPane.setFont()" also didn't work. How can I set the font size correctly? Please help..

Sure, you can create a font object and use it to set the font of your text pane.
Instantiate it like this:
Font f = new Font(Font.SANS_SERIF, 3, 5);

Maybe this code will help you, about Highlighter and StyledDocument, rest is described in the tutorial about JTextPane / EditorPane

Related

How to obtain the row from a mouse click on JEditorPane containg an HTML table

Is there a way to obtain the row index within an HTML table defined in a JEditorPane? I tried viewToModel method but this isn't what I was expecting.
pane.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
System.out.println( pane.viewToModel(e.getPoint()) );
}
...
Easy/lazy answer: of course you cannot. Even in a pure html page, you need some javascript to achive this.
JEditorPane can't handle javascript (i think, maybe i'm wrong), so no chance.
Now, you can use a different approach:
Change a field (or create a new one) with a link.
The link will have as url somenthing like #rowXXX, where XXX is the number of the row.
Some field
Add a HyperlinkListener to the jEditorPane:
editor.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
String rowcode = e.getDescription();
int row = Integer.parseInt(rowcode.replace("#row",""));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
});
Now in row you should have the number of the row.
Full example
package test;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private String HTML = "<html><table border=\"1\"><tr><td>First row</td></tr><tr><td>Second row</td></tr><tr><td>Third row</td></tr></table></html>";
private JPanel contentPane;
private JEditorPane editor;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App frame = new App();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public App() {
setTitle("HTML TABLE CLICKABLE");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 408, 235);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
editor = new JEditorPane();
editor.setEditable(false);
editor.setContentType("text/html");
contentPane.add(editor, BorderLayout.CENTER);
editor.setText(HTML);
editor.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
String rowcode = e.getDescription();
int row = Integer.parseInt(rowcode.replace("#row",""));
System.out.println(row);
}
}
});
}
}

PrintScreen image capturing

I need to write a program that I will create a runnable jar and distribute. The functions should be like below:
when double click the jar, it will open a window.
it will ask the path where to save the image files.
it will then ask whether to add any prefix / suffix / both on every image along with timestamp for unique name.
it will also ask what image format to use.
the app can be minimized and closed
it will take a full screenshot whenever PrintScreen is pressed and save.
Please provide a programme that is complete. I have gathered pieces but could not put them in one. Here is my code :-
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainClass
{
static String location = "";
static String prefix = "";
static String format = "";
static Date timestamp = new Date();
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
JFrame f = new JFrame("Text Field Examples");
f.getContentPane().setLayout(new FlowLayout());
final JTextField textField1 = new JTextField("Enter Location To Save Image Files");
textField1.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField1.setText("");
}
});
textField1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
location = textField1.getText();
System.out.println(location);
}
});
f.getContentPane().add(textField1);
final JTextField textField2 = new JTextField("Enter Prefix or Leave Empty");
textField2.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField2.setText("");
}
});
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
prefix = textField2.getText();
System.out.println(prefix);
}
});
f.getContentPane().add(textField2);
String jlistData[] =
{
"GIF",
"PNG",
"JPG"
};
final JComboBox jlist = new JComboBox<String>( jlistData );
jlist.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
format = jlist.getSelectedItem().toString();
System.out.println(format);
}
});
f.getContentPane().add(jlist);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
try
{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
RenderedImage image = (RenderedImage) t.getTransferData(DataFlavor.imageFlavor);
ImageIO.write(image, format, new File(new String(location+prefix+image+timestamp)));
}
catch(Exception e)
{
}
}
}
The first try catch block can open a window, take image format, prefix and storage location. The second try catch block alone can take screen shot when run not when printscreen key is pressed but with the first try catch it does not print anything. So, what to do to take the screenshot when printscreen key is pressed ?
I have approached the solution in a little bit another way.
As people always works with mouse while on online meeting, I removed the clause of PrintScreen button from keyboard and instead the attendees can click on swing window button to capture screen.
My solution as follows:
MainClass.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainClass{
static String location = "";
static String prefix = "";
static String format = "";
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
final JFrame f = new JFrame("ENTER ALL DETAILS BELOW");
f.setAlwaysOnTop(true);
f.getContentPane().setLayout(new FlowLayout());
final JTextField textField1 = new JTextField("Enter Location To Save Image Files");
textField1.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField1.setText("");
}
});
f.getContentPane().add(textField1);
final JTextField textField2 = new JTextField("Enter MeetingID");
textField2.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField2.setText("");
}
});
f.getContentPane().add(textField2);
String jlistData[] =
{
"GIF",
"PNG",
"JPG"
};
final JComboBox jlist = new JComboBox<String>( jlistData );
f.getContentPane().add(jlist);
final JButton jButton = new JButton("OKAY");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
location = textField1.getText();
prefix = textField2.getText();
format = jlist.getSelectedItem().toString();
System.out.println(location);
System.out.println(prefix);
System.out.println(format);
f.setVisible(false);
PrintButton.printButton();
}
});
f.getContentPane().add(jButton);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
}
}
PrintButton.java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class PrintButton
{
static void printButton()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//final JFrame f = new JFrame("Print Screen App");
Dlg f = new Dlg(new JFrame(), "PRINT");
f.setAlwaysOnTop(true);
f.getContentPane().setLayout(new FlowLayout());
final JButton jButton = new JButton("OKAY");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PrintScreen.printScreen();
}
});
f.getContentPane().add(jButton);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
}
}
class Dlg extends JDialog {
public Dlg(JFrame frame, String str) {
super(frame, str);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
PrintScreen.java
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.awt.image.RenderedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class PrintScreen
{
static void printScreen()
{
try
{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
RenderedImage image = (RenderedImage) t.getTransferData(DataFlavor.imageFlavor);
ImageIO.write(image, MainClass.format, new File(new String(MainClass.location+ "\\" +MainClass.prefix+"_"+System.currentTimeMillis()+"."+MainClass.format)));
}
catch(Exception e)
{
}
}
}
I hope this will be helpfull to some freinds. Is there any scope to improve this?
How to create a installable version for Windows and Linux/Ubuntu and Linux/RedHat ?

java drop and drag label to join correct image

this code is only allowing me to reject a string the second time to try to drop in a textArea where there is all ready a string.
public GridLayoutTest() {
JFrame frame = new JFrame("GridLayout test");
connection = getConnection();
try {
statement = (PreparedStatement) connection
result = statement.executeQuery();
while (result.next()) {
byte[] image = null;
image = result.getBytes("image");
JPanel cellPanel = new JPanel(new BorderLayout());
cellPanel.add(cellLabel, BorderLayout.NORTH);
cellPanel.add(droplabel, BorderLayout.CENTER);
gridPanel.add(cellPanel);
}
}
catch (SQLException e) {
e.printStackTrace();}
}
So, two things, first...
public void DropTargetTextArea(String string1, String string2) {
Isn't a constructor, it's a method, note the void. This means that it is never getting called. It's also the reason why DropTargetTextArea textArea = new DropTargetTextArea(); works, when you think it shouldn't.
Second, you're not maintaining a reference to the values you pass in to the (want to be) constructor, so you have no means to references them later...
You could try using something like...
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this, true);
}
And then use something like...
if (values[0].equals(dragContents) || values[1].equals(dragContents)) {
In the drop method.
In your dragEnter, dragOver and dropActionChanged methods you have the oppurtunity to accept or reject the drag action using something like dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); or dtde.rejectDrag();
Updated with test code
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DragAndDropExample {
public static void main(String[] args) {
ImageIcon ii1 = new ImageIcon("C:\\Users\\Desktop\\home.jpg");
ImageIcon ii = new ImageIcon("C:\\Users\\Desktop\\images (2).jpg");
// Create a frame
JFrame frame = new JFrame("test");
JLabel label = new JLabel(ii);
JLabel label1 = new JLabel(ii1);
JPanel panel = new JPanel(new GridLayout(2, 4, 10, 10));
JLabel testLabel = new DraggableLabel("test");
JLabel testingLabel = new DraggableLabel("testing");
panel.add(testLabel);
panel.add(testingLabel);
panel.add(label);
panel.add(label1);
Component textArea = new DropTargetTextArea("test", "testing");
frame.add(textArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static class DraggableLabel extends JLabel implements DragGestureListener, DragSourceListener {
DragSource dragSource1;
public DraggableLabel(String text) {
setText(text);
dragSource1 = new DragSource();
dragSource1.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
public void dragGestureRecognized(DragGestureEvent evt) {
Transferable transferable = new StringSelection(getText());
dragSource1.startDrag(evt, DragSource.DefaultCopyDrop, transferable, this);
}
public void dragEnter(DragSourceDragEvent evt) {
System.out.println("Drag enter");
}
public void dragOver(DragSourceDragEvent evt) {
System.out.println("Drag over");
}
public void dragExit(DragSourceEvent evt) {
System.out.println("Drag exit");
}
public void dropActionChanged(DragSourceDragEvent evt) {
System.out.println("Drag action changed");
}
public void dragDropEnd(DragSourceDropEvent evt) {
System.out.println("Drag action End");
}
}
public static class DropTargetTextArea extends JLabel implements DropTargetListener {
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void dragEnter(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag enter");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragOver(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag over");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragExit(DropTargetEvent evt) {
System.out.println("Drop exit");
}
public void dropActionChanged(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject dropActionChanged");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void drop(DropTargetDropEvent evt) {
if (!getText().isEmpty()) {
evt.rejectDrop();
} else {
try {
Transferable transferable = evt.getTransferable();
if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String dragContents = (String) transferable.getTransferData(DataFlavor.stringFlavor);
evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
if (values[0].equals(dragContents) || (values[1]).equals(dragContents)) {
System.out.println("Accept Drop");
setText(getText() + " " + dragContents);
evt.getDropTargetContext().dropComplete(true);
} else {
System.out.println("Reject Drop");
}
}
} catch (IOException e) {
evt.rejectDrop();
evt.dropComplete(false);
} catch (UnsupportedFlavorException e) {
}
}
}
}
}

Java string replaceAll()

I've been wondering if for example:
JTextPane chatTextArea = new JTextPane();
s.replaceAll(":\\)", emoticon());
public String emoticon(){
chatTextArea.insertIcon(new ImageIcon(ChatFrame.class.getResource("/smile.png")));
return "`";
}
can put a picture and a "`" everywhere ":)" is found. When I run it like this if s contains a ":)" then the whole s gets replaced just by the icon.
Is there a way to do it?
Here is a small example I made (+1 to #StanislavL for the original), simply uses DocumentListener and checks when a matching sequence for an emoticon is entered and replaces it with appropriate image:
NB: SPACE must be pressed or another character/emoticon typed to show image
import java.awt.Dimension;
import java.awt.Image;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.Utilities;
public class JTextPaneWithEmoticon {
private JFrame frame;
private JTextPane textPane;
static ImageIcon smiley, sad;
static final String SMILEY_EMOTICON = ":)", SAD_EMOTICON = ":(";
String[] emoticons = {SMILEY_EMOTICON, SAD_EMOTICON};
private void initComponents() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textPane = new JTextPane();
//add docuemntlistener to check for emoticon insert i.e :)
((AbstractDocument) textPane.getDocument()).addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(final DocumentEvent de) {
//We should surround our code with SwingUtilities.invokeLater() because we cannot change document during mutation intercepted in the listener.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
StyledDocument doc = (StyledDocument) de.getDocument();
int start = Utilities.getRowStart(textPane, Math.max(0, de.getOffset() - 1));
int end = Utilities.getWordStart(textPane, de.getOffset() + de.getLength());
String text = doc.getText(start, end - start);
for (String emoticon : emoticons) {//for each emoticon
int i = text.indexOf(emoticon);
while (i >= 0) {
final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start + i).getAttributes());
if (StyleConstants.getIcon(attrs) == null) {
switch (emoticon) {//check which emtoticon picture to apply
case SMILEY_EMOTICON:
StyleConstants.setIcon(attrs, smiley);
break;
case SAD_EMOTICON:
StyleConstants.setIcon(attrs, sad);
break;
}
doc.remove(start + i, emoticon.length());
doc.insertString(start + i, emoticon, attrs);
}
i = text.indexOf(emoticon, i + emoticon.length());
}
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(300, 300));
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {//attempt to get icon for emoticons
smiley = new ImageIcon(ImageIO.read(new URL("http://facelets.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/e/m/emoticons0001.png")).getScaledInstance(24, 24, Image.SCALE_SMOOTH));
sad = new ImageIcon(ImageIO.read(new URL("http://zambia.primaryblogger.co.uk/files/2012/04/sad.jpg")).getScaledInstance(24, 24, Image.SCALE_SMOOTH));
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JTextPaneWithEmoticon().initComponents();
}
});
}
}
References:
How to add smileys in java swing?

Keeping the correct style on text retrieval

I am making an application similar to a chat. For that purpose I have two JTextPanes, one where I'm writing and one that displays messages. This is the code that handles the transferring of text from input to display :
String input = textPane.getText();
if(!input.endsWith("\n")){
input+="\n";
}
StyledDocument doc = displayPane.getStyledDocument();
int offset = displayPane.getCaretPosition();
textPane.setText("");
try {
doc.insertString(offset, input, set);
} catch (BadLocationException ex) {
Logger.getLogger(ChatComponent.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is that if i have colour on some words of the input text , the output is all coloured . So the colour is applied to all of the text when moved to display(while displayed correctly on input). Any suggestions on how i can move text properly?
Notice that same happens with other format as bold , italic etc
The text is already formatted on the input JTextPane . What i need to do
is transfer it as it is on a different JTextPane without having to check
the different style options
example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class Fonts implements Runnable {
private String[] fnt;
private JFrame frm;
private JScrollPane jsp;
private JTextPane jta;
private int width = 450;
private int height = 300;
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private StyledDocument doc;
private MutableAttributeSet mas;
private int cp = 0;
private Highlighter.HighlightPainter cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
private Highlighter.HighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
private Highlighter.HighlightPainter whitePainter = new DefaultHighlighter.DefaultHighlightPainter(Color.white);
private int _count = 0;
private int _lenght = 0;
public Fonts() {
jta = new JTextPane();
doc = jta.getStyledDocument();
jsp = new JScrollPane(jta);
jsp.setPreferredSize(new Dimension(height, width));
frm = new JFrame("awesome");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(new BorderLayout());
frm.add(jsp, BorderLayout.CENTER);
frm.setLocation(100, 100);
frm.pack();
frm.setVisible(true);
jta.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
fnt = ge.getAvailableFontFamilyNames();
mas = jta.getInputAttributes();
new Thread(this).start();
}
#Override
public void run() {
for (int i = 0; i < fnt.length; i++) {
StyleConstants.setBold(mas, false);
StyleConstants.setItalic(mas, false);
StyleConstants.setFontFamily(mas, fnt[i]);
StyleConstants.setFontSize(mas, 16);
dis(fnt[i]);
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, true);
dis(fnt[i] + " Bold");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setItalic(mas, true);
dis(fnt[i] + " Bold & Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, false);
dis(fnt[i] + " Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
}
jta.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void dis(String s) {
_count++;
_lenght = jta.getText().length();
try {
doc.insertString(cp, s, mas);
doc.insertString(cp, "\n", mas);
} catch (Exception bla_bla_bla_bla) {
bla_bla_bla_bla.printStackTrace();
}
if (_count % 2 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, cyanPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else if (_count % 3 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, redPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, whitePainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Fonts fs = new Fonts();
}
});
}
}
In the absence of a good SSCCE, I really don't know how you adding colour to the text on your JTextPane, but hopefully this method might sort things out for you :
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
private void appendToTextPane(String name, Color c, String f)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, f);
int len = Client.nPane.getDocument().getLength();
textPane.setCaretPosition(len);
textPane.setCharacterAttributes(aset, true);
textPane.replaceSelection(name);
}
With this you can give a different Color and Font to each String literal that will be added to your JTextPane.
Hope this new Code might help you in some way :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame
{
private JPanel topPanel;
private JPanel bottomPanel;
private JTextPane tPane1;
private JTextPane tPane2;
private JButton button;
public TextPaneTest()
{
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 2));
bottomPanel = new JPanel();
bottomPanel.setBackground(Color.BLACK);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLUE);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
tPane1 = new JTextPane();
tPane1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
tPane1.setCharacterAttributes(aset, false); // Add these settings to the other JTextPane also
tPane2 = new JTextPane();
tPane2.setCharacterAttributes(aset, false); // Mimic what the other JTextPane has
button = new JButton("ADD TO THE TOP JTEXTPANE");
button.setBackground(Color.DARK_GRAY);
button.setForeground(Color.WHITE);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tPane1.setText(tPane2.getText());
}
});
add(topPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
topPanel.add(tPane1);
topPanel.add(tPane2);
bottomPanel.add(button);
pack();
tPane2.requestFocusInWindow();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextPaneTest();
}
});
}
}
Regards
This has been solved by merging the document models of the two panes. The solution is in this question: Keeping the format on text retrieval

Categories