gpt4 book ai didi

java - 如何从右到左设置 JTextArea 的方向(在 JOptionPane 内)

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:42 25 4
gpt4 key购买 nike

我有 JScrollPane 和里面的 JTextArea 我试图将 JTextArea 的方向设置为从右到左,这样它里面的文本将从右边和滚动条开始会在左边

我已经尝试了以下但它们并没有影响方向的方向:

txt.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setAlignmentX(JTextArea.RIGHT_ALIGNMENT);

编辑:

camickr 和 trashgod 提供的两个答案工作正常,但在我使用 JTextArea 作为对象 Message 并将其传递给 OptionPane 的程序中却没有。

编辑 2:

我发现如果我将 setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 应用于 JOptionPane 内容,它就不起作用了。这个问题是否有替代解决方案?

类似于我的代码:

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);

文本从右侧开始,但仍会在您键入时追加到末尾,而不是插入到行首。

更新:

我不知道为什么它在选项 Pane 中不起作用。这是一个简单的解决方案:

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);
}
});
}
}

关于java - 如何从右到左设置 JTextArea 的方向(在 JOptionPane 内),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6475320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com