【问题标题】:Java Swing JTextArea write both left and rightJava Swing JTextArea 左右写入
【发布时间】:2016-09-18 19:56:10
【问题描述】:

我正在使用 Java 制作一个简单的消息传递应用程序。我想在我的 textArea 的左侧和右侧显示消息,就像所有 whatsapp、messenger 等一样。更改方向会更改所有文本方向,因此它没有用。

非常感谢

【问题讨论】:

  • 这不是 Java - Align JTextArea to the Right 的副本。如果我没记错的话@Ilkin 需要在同一文本区域中左右对齐一些文本。话虽如此...除了用户键入/添加的每个段落的对齐方式必须更改之外,该问题的答案也有该问题的答案。
  • 同意上述评论。答案是关于更改整个文本窗格的对齐方式,而不是单个文本行。一个更好的例子可能是:stackoverflow.com/questions/36409784/…。由于该示例不可执行,因此我重新打开了此问题,因此可以发布完整的 SSCCE。
  • 是的,@MadPiranha,我已经提到过

标签: java swing user-interface


【解决方案1】:

您不能使用 JTextArea。

一种解决方案是使用JTextPane 并为您插入的每一行文本设置属性:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class TextPaneChat
{
    private static void createAndShowGUI()
    {
        JTextPane textPane = new JTextPane();

        StyledDocument doc = textPane.getStyledDocument();

        SimpleAttributeSet left = new SimpleAttributeSet();
        StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);
        StyleConstants.setForeground(left, Color.RED);

        SimpleAttributeSet right = new SimpleAttributeSet();
        StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
        StyleConstants.setForeground(right, Color.BLUE);

        try
        {
            doc.insertString(doc.getLength(), "Are you busy tonight?", left );
            doc.setParagraphAttributes(doc.getLength(), 1, left, false);
            doc.insertString(doc.getLength(), "\nNo", right );
            doc.setParagraphAttributes(doc.getLength(), 1, right, false);
            doc.insertString(doc.getLength(), "\nFeel like going to a movie?", left );
            doc.setParagraphAttributes(doc.getLength(), 1, left, false);
            doc.insertString(doc.getLength(), "\nSure", right );
            doc.setParagraphAttributes(doc.getLength(), 1, right, false);
        }
        catch(Exception e) { System.out.println(e); }

        JFrame frame = new JFrame("Text Pane Chat");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new JScrollPane( textPane ) );
        frame.setLocationByPlatform( true );
        frame.setSize(200, 200);
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }
}

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 2014-07-28
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    相关资源
    最近更新 更多