I have a following piece of code which uses JTextArea to display some text,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultCaret;
public class TextPane extends JFrame{
public static TextPane instance;
//private static JTextPane pane = new JTextPane(); //Uncomment to see alignment issue
private static JTextArea pane = new JTextArea(); // alignment works fine
private static JScrollPane scroll = new JScrollPane();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TextPane.getInstance().init();
}
});
}
private static TextPane getInstance() {
if(null == instance){
instance = new TextPane();
}
return instance;
}
private void init() {
pane.setFont(new Font("Courier new", Font.PLAIN, 12));
pane.setLayout(new BorderLayout());
pane.setFocusCycleRoot(true);
pane.setFocusTraversalKeysEnabled(false);
pane.setBackground(Color.black);
pane.setForeground(Color.white);
pane.setCaretColor(Color.green);
pane.setDragEnabled(false);
pane.setText("IOC_CONFUG_MMM.lag hkess.lag\t\t papdifs.lag\r\nMemSys.lag.txt\t eol.lag1\t\t papdifs.lag2\r\nopp.lag\t\t eol.lag2\t\t papm_by.lag1\r\n");
DefaultCaret caret = (DefaultCaret) pane.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
scroll.setViewportView(pane);
add(scroll);
setTitle("Test");
setSize(800 , 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
}
}
There was an issue in alignment of the setText string initially however after i add font as Courier New i got it resolved(if i remove setFont alignment will not work.)
recently due to some requirements i changed from JtextArea to JTextPane , now with same piece of code the text doesn't align properly in JTextPane but if i change it to JTextArea alignment works fine.
I couldn't understand this behaviour. How can i achieve the alignment in JTextPane. please help.
The JTextPane (or the editor kit you are using implicitly) has a different default behavior regarding tab placement which stems from the fact that it is intended to contain far more complex content than a JTextArea. You can create your desired simple fixed-width font tab placement manually and set it explicitly. Just insert the following lines right before invoking setText(…); on your pane:
int w=pane.getFontMetrics(pane.getFont()).charWidth(' ');
TabStop[] stops={ new TabStop(0), new TabStop(w*8), new TabStop(w*16),
new TabStop(w*24), new TabStop(w*32), new TabStop(w*40), new TabStop(w*48),
new TabStop(w*56), new TabStop(w*64), new TabStop(w*72), new TabStop(w*80) };
MutableAttributeSet attrs=new SimpleAttributeSet();
StyleConstants.setTabSet(attrs, new TabSet(stops) );
pane.setParagraphAttributes(attrs, false);
Related
I can't seem to find a solution online for why I'm getting this error on attempted run
I'm working on making a simple test system for a different program when are button press will yield value in a text box. I would like them to be on different lines to make it cleaner, so I looked into layouts. I decided a Box Layout would fit me best. I looked at different examples before attempting this and my code ended up looking like this, (apologies for the messy code)
Update
Got the box layout error to disappear but the code will not center them on the panel/frame. The label and button align left while the textfield becomes very large. I don't need it todo that
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import static javax.swing.BoxLayout.Y_AXIS;
import static javax.swing.SwingConstants.CENTER;
public class button extends JFrame {
static JFrame f;
static JButton b;
static JLabel l;
// main class
public static void main(String[] args)
{
// create a new frame to stor text field and button
f = new JFrame("panel");
BoxLayout layout = new BoxLayout(f, BoxLayout.Y_AXIS);
f.setLayout(layout);
// create a label to display text
l = new JLabel("panel label");
b = new JButton("button1");
JTextField textArea = new JTextField(5);
textArea.setEditable(false);
//textArea.append("Hello World");
// create a panel to add buttons
JPanel p = new JPanel();
// add buttons and textfield to panel
f.add(p);
f.setSize(300, 300);
p.add(l);
p.add(b);
p.setBackground(Color.white);
p.add(textArea);
f.show();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Random r = new Random();
textArea.setText(String.valueOf(r));
}
});
}
}
Error
Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared
at java.desktop/javax.swing.BoxLayout.checkContainer(BoxLayout.java:461)
at java.desktop/javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:245)
at java.desktop/javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:278)
at java.desktop/java.awt.Container.addImpl(Container.java:1152)
at java.desktop/java.awt.Container.add(Container.java:1029)
at java.desktop/javax.swing.JFrame.addImpl(JFrame.java:553)
at java.desktop/java.awt.Container.add(Container.java:436)
at button.main(button.java:36)
I would like the three items to all to be stacked one on top of another with a space between them. The order doesn't matter right now.
Swing was first added to the JDK in 1998 and has undergone a lot of changes since. Unfortunately, when you read Web pages about Swing, it is not obvious when that page was last updated. Consequently you may be learning outdated techniques for writing Swing code.
First of all, according to the code you posted, class button does not need to extend class JFrame since you use a static variable as your application's JFrame. Also, JFrame is a top-level container which makes it a special kind of container and not the same kind of continer as a JPanel. You need to set the layout manager for your JPanel and then add the JLabel, JTextField and JButton to that JPanel. And then add the JPanel to the JFrame.
Calling method pack() of class JFrame will automatically set the preferred sizes for the components inside the JFrame. It appears in the code below.
Please also look at Java coding conventions which allows others to more easily read and understand your code. And note that, according to these conventions, I renamed your class from button to Buttons and also because there are already several class in the JDK named Button.
Here is my rewrite of your code...
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class Buttons implements Runnable {
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
JFrame f = new JFrame("Box");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel p = new JPanel();
BoxLayout layout = new BoxLayout(p, BoxLayout.Y_AXIS);
p.setLayout(layout);
JLabel l = new JLabel("panel label");
JTextField textField = new JTextField(5);
JButton b = new JButton("button1");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Random r = new Random();
textField.setText(String.valueOf(r.nextBoolean()));
}
});
p.add(l);
p.add(textField);
p.add(b);
f.add(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
Buttons instance = new Buttons();
EventQueue.invokeLater(instance);
}
}
I've been trying to make a java swing based application to retrieve tweets from a user by using twitter4j..the code seems to be working when pretend on the console but not adding ..i've tried adding the scroll area and scroll bar to help with text wrapping and longer texts but it seems to be not working..
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import twitter4j.*;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
public class mainTwitter {
public static void main(String args[])
{
List<Status> statuses=null;
String user;
try{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("*************")
.setOAuthConsumerSecret("*************")
.setOAuthAccessToken("*************")
.setOAuthAccessTokenSecret("*************");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
if(args.length==1)
{
user=args[0];
statuses=twitter.getUserTimeline(user);
}
else
{
user = twitter.verifyCredentials().getScreenName();
statuses = twitter.getUserTimeline();
}
System.out.println("Showing "+user+"'s user timeline.");
/*
for(Status status: statuses)
{
System.out.println("#"+status.getUser().getScreenName()+"-"+status.getText());
}*/
}
catch(Exception e)
{
e.printStackTrace();
}
JFrame mainFrame = new JFrame("Twitter Montior");
mainFrame.setLocationByPlatform(true);
mainFrame.setLocation(360, 80);
JPanel tPanel = new JPanel();
JPanel bPanel = new JPanel();
mainFrame.setLayout(null);
///////////////////////////////////////////////////////////////////////////////
//Top Panel
JTextField t1 = new JTextField("Twitter Monitor!!");
t1.setBackground(Color.yellow);
t1.setHorizontalAlignment(JTextField.CENTER);
t1.setEditable(false);
Font new_f = new Font("Serif", Font.PLAIN, 30);
t1.setFont(new_f);
JTextArea userInfo=new JTextArea();
Font font2 = new Font("Serif", Font.PLAIN, 20);
userInfo.setFont(font2);
userInfo.setLineWrap(true);
userInfo.setWrapStyleWord(true);
userInfo.setBackground(Color.LIGHT_GRAY);
userInfo.setEditable(false);
userInfo.setLineWrap(true);
JScrollPane scrollArea = new JScrollPane(userInfo);
scrollArea.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollBar bar = new JScrollBar();
scrollArea.add(bar);
tPanel.add(scrollArea);
JButton retrieve = new JButton("Click");
tPanel.setLayout(null);
t1.setBounds(150, 2, 250, 30);
userInfo.setBounds(0,34,700,260);
retrieve.setBounds(260, 300, 50, 20);
tPanel.add(retrieve);
tPanel.add(t1);
tPanel.add(userInfo);
///////////////////////////////////////////////////////////////////////////////
///Bottom Panel..
///////////////////////////////////////////////////////////////////////////////
tPanel.setBounds(0, 0, 700, 350);
bPanel.setBounds(0,352,700,248);
handler h = new handler(statuses, userInfo);
retrieve.addActionListener(h);
mainFrame.add(tPanel);
mainFrame.add(bPanel);
mainFrame.setSize(700, 600);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
}
class handler implements ActionListener
{
List<Status> statuses2;
JTextArea t;
handler(List<Status> statuses1, JTextArea f)
{
statuses2=statuses1;
t=f;
}
#Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s=="Click")
{
for(Status status: statuses2)
{
System.out.println("#"+status.getUser().getScreenName()+"-"+status.getText());
t.setText("#"+status.getUser().getScreenName()+"-"+status.getText());
t.setText("\n");
}
}
}
}
I think your main problem is that you use null layout, and you need to choose size and place of every components inside mainFrame and your panels. In my opinion is very bad idea and it is generally not recommended. It would be much simpler to write it with use of BorderLayout for JFrame, and other for your JPanels. But it is up to you.
It this particular case, in my opinion your scrollArea is not working because:
You add userInfo twice, first to scrollArea, then to tPanel directly. So what you see when you run program, is userInfo in tPanel, because components could be added to only one container.
You use a null layout so it is necessary to setBounds() for every component inside container with such layout settings, but you didn't setBounds() for scrollArea.
So the quickest way to make it work:
delete line tPanel.add(userInfo);,
change scrollArea.setBounds(0,34,700,260); for userInfo.setBounds(0,34,700,260); - it is enough to change component it relete to,
After those changes it should work.
Aditional comments:
you dont't need to add JScrollBar to JScrollPane, it has it by itself,
the mainFrame.setLocationByPlatform(true); line is not working and it is not necessary, becouse you setLocation() of mainFrame manually and use null layout,
you use userInfo.setLineWrap(true); twice, you can delete one line,
I want to set bold font style for selected text in JTextArea instance.
I tried this way:
textArea.getSelectedText().setFont(new Font("sansserif",Font.BOLD, 12));
But it does not work. Also I've tried JTextPane and JEditorPane instead of JTextArea but without effect.
How can I do that?
I want to set bold font style for selected text in JTextArea instance.
You can't do this for a JTextArea. You need to use a JTextPane.
Then you can use the default Action provided by the StyledEditorKit. Create a JButton or JMenuItem to do this:
JButton boldButton = new JButton( new StyledEditorKit.BoldAction() );
JMenuItem boldMenuItem = new JMenuItem( new StyledEditorKit.BoldAction() );
Add the button or menu item to the frame. Then the use can click on the button/menu item to bold the text after it has been selected. This is the way most editor work. You can also add an acceleration to the Action to the Action can be invoked just by using the keyboard.
Read the section from the Swing tutorial on Text Component Features for more information and a working example.
Introduction
The (useful) answers for how to do what you want to do have already been posted by #Freek de Bruijn and #Gilbert Le Blanc, but none of them explain why what you're trying to do doesn't work. This isn't an answer for
How can I do that?
but an explanation for
But it does not work.
Edit: #camickr posted what I believe is the correct approach.
Answer
From the tutorial about about JTextArea:
You can customize text areas in several ways. For example, although a given text area can display text in only one font and color, you can set which font and color it uses.
(all emphasis in quotes are mine) and
If you want the text area to display its text using multiple fonts or other styles, you should use an editor pane or text pane.
This is because JTextArea uses PlainDocument (see this):
PlainDocument provides a basic container for text where all the text is displayed in the same font.
However, a JTextPane uses DefaultStyledDocument:
a container for styled text in no particular format.
You have to set up a caret listener on a JTextPane to listen for when some or all of the text is selected.
Here's the GUI I created.
And here's the code:
package com.ggl.testing;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
public class JTextPaneTest implements Runnable {
private JTextPane textPane;
private StyledDocument styledDocument;
public static void main(String[] args) throws BadLocationException {
SwingUtilities.invokeLater(new JTextPaneTest());
}
public JTextPaneTest() throws BadLocationException {
this.styledDocument = new DefaultStyledDocument();
this.styledDocument.insertString(0, displayText(), null);
addStylesToDocument(styledDocument);
}
#Override
public void run() {
JFrame frame = new JFrame("JTextPane Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
textPane = new JTextPane(styledDocument);
textPane.addCaretListener(new SelectedText());
textPane.setPreferredSize(new Dimension(250, 125));
JScrollPane scrollPane = new JScrollPane(textPane);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
private String displayText() {
return "This is some sample text. Pick part of the text to select "
+ "by double clicking on a word.";
}
private void addStylesToDocument(StyledDocument styledDocument) {
Style def = StyleContext.getDefaultStyleContext().getStyle(
StyleContext.DEFAULT_STYLE);
Style s = styledDocument.addStyle("bold", def);
StyleConstants.setBold(s, true);
}
private class SelectedText implements CaretListener {
#Override
public void caretUpdate(CaretEvent event) {
int dot = event.getDot();
int mark = event.getMark();
if (dot != mark) {
if (dot < mark) {
int temp = dot;
dot = mark;
mark = temp;
}
boldSelectedText(mark, dot);
}
}
private void boldSelectedText(int mark, int dot) {
try {
int length = dot - mark;
String s = styledDocument.getText(mark, length);
styledDocument.remove(mark, length);
styledDocument.insertString(mark, s,
styledDocument.getStyle("bold"));
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
You could use a JTextPane component similar to changing the color as described in the following answer: How to set font color for selected text in jTextArea.
For example:
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
public class BoldSelected {
public static void main(final String[] args) {
new BoldSelected().launchGui();
}
private void launchGui() {
final String title = "Set bold font style for selected text in JTextArea instance";
final JFrame frame = new JFrame("Stack Overflow: " + title);
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JTextPane textPane = new JTextPane();
textPane.setText(title + ".");
final Style style = textPane.addStyle("Bold", null);
StyleConstants.setBold(style, true);
textPane.getStyledDocument().setCharacterAttributes(4, 33, style, false);
frame.getContentPane().add(textPane);
frame.setVisible(true);
}
}
So I asked something similar to this earlier and got the answer to the question I asked, but I apparently didn't ask the right question. So, what I'm trying to accomplish here is have the text area populate only in the center of the jFrame. As you can see, it is set up as a borderlayout, and there are buttons on the bottom, a label on the top (which will then - on the full version of this program - be copied into the text frame when it is replaced with text from the action listener on the button)
The problem is, the text area fills the entire window and covers up every other component on the window. I've tried to use preferred size, and I tried to specify columns/rows and I've read the tutorials on docs.oracle, although I suppose since I'm still having trouble i may have missed one.
Also, the offset commented lines I found in the docs.oracle information and it would be a good idea for this to text-wrap because it's going to be a log of what has occurred. I tried adding all the imports suggested on that website but netbeans still gives me a red underline that they're not recognized as commands. Have they been deprecated, did I not use them right, or am I missing an import?
I know I'm asking a lot, but thanks for your time and patience!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package theproblem;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.TextArea;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/**
*
* #author Heather
*/
public class TheProblem {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JFrame window2 = new JFrame();
TextArea battleLogging = new TextArea(3,10);
JScrollPane logScrollPane = new JScrollPane(battleLogging);
JLabel BattleLog = new JLabel();
JLabel p1HPLabel= new JLabel();
JLabel p2HPLabel= new JLabel();
String attack1ButtonContents = "Just an attack";
String attack2ButtonContents = "Just another attack";
JButton attack1=new JButton(attack1ButtonContents);
JButton attack2=new JButton(attack2ButtonContents);
window2.setLayout(new BorderLayout());
window2.setSize(400,400);
JPanel attackPanel = new JPanel();
attackPanel.add(attack1);
attackPanel.add(attack2);
window2.add(battleLogging, BorderLayout.CENTER);
battleLogging.setEditable(false);
logScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logScrollPane.setPreferredSize(new Dimension(50, 50));
//battleLogging.setLineWrap(true);
//battleLogging.setWrapStyleWord(true);
window2.add(BattleLog, BorderLayout.NORTH);
window2.add(p1HPLabel, BorderLayout.WEST);
window2.add(p2HPLabel, BorderLayout.EAST);
window2.setVisible(true);
window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Problems:
When adding any component BorderLayout.CENTER, it fills the center position, no matter what size or preferred size you give it.
You shouldn't even be setting sizes.
Don't use TextAreas with Swing apps. Use JTextAreas
Set the JTextArea's column and row count and let that do its sizing for you.
Don't forget to pack your GUI before displaying it.
For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class TheProblem2 {
private static void createAndShowGUI() {
int rows = 5;
int cols = 20;
JTextArea textArea = new JTextArea(rows, cols);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 1");
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
btnPanel.add(button1);
btnPanel.add(button2);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(scrollPane);
mainPanel.add(btnPanel, BorderLayout.SOUTH);
JFrame frame = new JFrame("EG 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I have JScrollPane with JTextArea inside it and I am trying to set the JTextArea's orientation from right to left so the text inside it will start from the right and the scrollbar will be on the left
I've tried the following but they didn't affect the direction of the orientation:
txt.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setAlignmentX(JTextArea.RIGHT_ALIGNMENT);
EDIT:
the two answers camickr & trashgod provided work fine but not in my program where I use my JTextArea as an object Message and pass it to OptionPane.
EDIT2:
I figured out that setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); doesn't work if I apply it on the JOptionPane contents .. is there an alternative solution to this issue?
Similar to my code:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class TextArea extends JPanel
{
private JTextArea txt = new JTextArea();
public TextArea()
{
setLayout(new GridLayout());
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JScrollPane scroll = new JScrollPane(txt);
scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setPreferredSize(new Dimension(200,200));
this.add(scroll);
}
private void display()
{
Object[] options = {this};
JOptionPane pane = new JOptionPane();
int option = pane.showOptionDialog(null, null, "Title", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
public static void main(String[] args)
{
new TextArea().display();
}
}
and the scrollbar will be on the left
scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
so the text inside it will start from the right
textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
The text starts on the right side, but still gets append to the end as you type instead of being inserted at the beginning of the line.
Update:
I don't know why it doesn't work in an option pane. Here is a simple solution:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class Test
{
public static void main(String args[]) throws Exception
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTextArea textArea = new JTextArea(4, 20);
JScrollPane scrollPane = new JScrollPane( textArea );
JPanel panel = new JPanel();
panel.add( scrollPane );
scrollPane.addAncestorListener( new AncestorListener()
{
public void ancestorAdded(AncestorEvent e)
{
JScrollPane scrollPane = (JScrollPane)e.getComponent();
scrollPane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
public void ancestorMoved(AncestorEvent e) {}
public void ancestorRemoved(AncestorEvent e) {}
});
JOptionPane.showMessageDialog(null, panel);
}
});
}
}
This seems to work.
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/** #see http://stackoverflow.com/questions/6475320 */
public class RTLTextArea extends JPanel {
private static final String s = "مرحبا العالم";
private JTextArea jta = new JTextArea(7, 5);
private Locale arabic = new Locale("ar", "KW");
private ComponentOrientation arabicOrientation =
ComponentOrientation.getOrientation(arabic);
public RTLTextArea() {
this.setLayout(new GridLayout());
this.add(new JScrollPane(jta));
this.applyComponentOrientation(arabicOrientation);
for (int i = 0; i < 8; i++) {
jta.append(s + "\n");
}
}
private void display() {
JFrame f = new JFrame("RTLTextAre");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new RTLTextArea().display();
}
});
}
}
this line
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT)
change the correct order of the words.
i have this result
KBytes 80.78
The following lines solved my problem:
jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
jTextArea1.setText(<text>);
They serve to:
setComponentOrientation() changes the orientation of the TextArea; and,
setText() refreshes TextArea immediately so it displays properly
Simply setting ComponentOrientation to RIGHT_TO_LEFT is not sufficient by itself. repaint() doesn't force the text to realign itself. A quick solution for me was to update the contents of the TextArea. That forced the text to realign itself.