Java 将区域底部对齐

Java 将区域底部对齐,java,Java,我正在用java进行聊天,代码如下: text += sendField.getText(); messageArea.setText(text); 我得到了这个: 但是我希望文本在JTextArea的底部对齐,有可能吗 我怎样才能把它变成这样? 谢谢你抽出时间 我希望文本在JTextArea的底部对齐,可以吗 文本组件不支持此功能。您需要编写一个自定义UI,以便从组件底部而不是组件顶部(这高于我的技能水平)绘制文本 但是,您可以利用Swing布局管理器使文本显示在底部: import j

我正在用java进行聊天,代码如下:

text += sendField.getText();
messageArea.setText(text);
我得到了这个:

但是我希望文本在JTextArea的底部对齐,有可能吗

我怎样才能把它变成这样?

谢谢你抽出时间

我希望文本在JTextArea的底部对齐,可以吗

文本组件不支持此功能。您需要编写一个自定义UI,以便从组件底部而不是组件顶部(这高于我的技能水平)绘制文本

但是,您可以利用Swing布局管理器使文本显示在底部:

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

public class TextAreaBottom extends JPanel implements DocumentListener
{
    private JTextArea textArea;

    public TextAreaBottom(JTextArea textArea)
    {
        this.textArea = textArea;

        setLayout( new BorderLayout() );
        setBackground( textArea.getBackground() );
        setBorder( textArea.getBorder() );
        textArea.getDocument().addDocumentListener(this);

        add(textArea, BorderLayout.SOUTH);
    }

    @Override
    public void insertUpdate(DocumentEvent e)
    {
        adjustHeight();
    }

    @Override
    public void removeUpdate(DocumentEvent e)
    {
        adjustHeight();
    }

    @Override
    public void changedUpdate(DocumentEvent e)  {}

    private void adjustHeight()
    {
        int rows = textArea.getLineCount();
        textArea.setRows(rows);
    }

    private static void createAndShowUI()
    {
        final JTextArea textArea = new JTextArea(5, 20);
        textArea.setEditable( false );

        final JTextField textField = new JTextField(20);
        JButton send = new JButton( "Send" );
        send.addActionListener( new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if(textArea.getDocument().getLength() > 0)
                    textArea.append("\n");

                textArea.append( textField.getText() );

                textField.setText("");
                textField.requestFocusInWindow();
            }
        });

        JPanel panel = new JPanel( new BorderLayout() );
        panel.add(textField);
        panel.add(send, BorderLayout.EAST);

        JFrame frame = new JFrame("TextAreaBottom");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane( new TextAreaBottom(textArea) ) );
        frame.add(panel, BorderLayout.SOUTH );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}
或者,为了获得更好的方法,您可以使用JTextPane。我修改了代码,在底部绘制文本。这是一个简单的单行更改,因为困难的部分已经完成:

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

public class TextPaneCenter
{
    private static void createAndShowUI()
    {
        JTextPane edit = new JTextPane();
        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JScrollPane(edit));
        frame.setSize(300,300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        edit.setSelectionColor( Color.GREEN );


        try
        {
            edit.setEditorKit(new MyEditorKit());
            SimpleAttributeSet attrs=new SimpleAttributeSet();
            StyleConstants.setAlignment(attrs,StyleConstants.ALIGN_CENTER);
            StyledDocument doc=(StyledDocument)edit.getDocument();
            doc.insertString(0,"111\n2222222\n33333333333333",attrs);
            doc.setParagraphAttributes(0,doc.getLength()-1,attrs,false);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }

    static class MyEditorKit extends StyledEditorKit
    {
        public ViewFactory getViewFactory()
        {
            return new StyledViewFactory();
        }

        static class StyledViewFactory implements ViewFactory
        {
            public View create(Element elem)
            {
                String kind = elem.getName();

                if (kind != null)
                {
                    if (kind.equals(AbstractDocument.ContentElementName))
                    {
                        return new LabelView(elem);
                    }
                    else if (kind.equals(AbstractDocument.ParagraphElementName))
                    {
                        return new ParagraphView(elem);
                    }
                    else if (kind.equals(AbstractDocument.SectionElementName))
                    {
                        return new CenteredBoxView(elem, View.Y_AXIS);
                    }
                    else if (kind.equals(StyleConstants.ComponentElementName))
                    {
                        return new ComponentView(elem);
                    }
                    else if (kind.equals(StyleConstants.IconElementName))
                    {
                        return new IconView(elem);
                    }
                }

            // default to text display
            return new LabelView(elem);
            }
        } // class StyledViewFactory
     } // class MyEditorKit

    static class CenteredBoxView extends BoxView
    {
        public CenteredBoxView(Element elem, int axis)
        {
            super(elem,axis);
        }

        protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans)
        {
            super.layoutMajorAxis(targetSpan,axis,offsets,spans);

            int textBlockHeight = 0;
            int offset = 0;

            for (int i = 0; i < spans.length; i++)
            {
                textBlockHeight += spans[ i ];
            }

            // display text vertically at the bottom
            offset = (targetSpan - textBlockHeight);

            // display text vertically centered
            //offset = (targetSpan - textBlockHeight) / 2;

            for (int i = 0; i < offsets.length; i++)
            {
                offsets[ i ] += offset;
            }
        }
    }
}
import javax.swing.*;
导入javax.swing.text.*;
导入java.awt.*;
公共类TextPaneCenter
{
私有静态void createAndShowUI()
{
JTextPane edit=新建JTextPane();
JFrame=新JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane();
框架。设置尺寸(300300);
frame.setLocationRelativeTo(空);
frame.setVisible(true);
编辑.setSelectionColor(Color.GREEN);
尝试
{
setEditorKit(新的MyEditorKit());
SimpleAttributeSet attrs=新的SimpleAttributeSet();
setAlignment(attrs,StyleConstants.ALIGN_CENTER);
StyledDocument文档=(StyledDocument)编辑.getDocument();
文档插入字符串(0,“111\n2222222\n33333”,属性);
doc.setParagraphAttributes(0,doc.getLength()-1,attrs,false);
}
捕获(例外情况除外)
{
例如printStackTrace();
}
}
公共静态void main(字符串[]args)
{
invokeLater(新的Runnable()
{
公开募捐
{
createAndShowUI();
}
});
}
静态类MyEditorKit扩展了StyledEditorKit
{
公共ViewFactory getViewFactory()
{
返回新的StyledViewFactory();
}
静态类StyledViewFactory实现ViewFactory
{
公共视图创建(元素元素)
{
字符串种类=elem.getName();
如果(种类!=null)
{
if(kind.equals(AbstractDocument.ContentElementName))
{
返回新的LabelView(elem);
}
else if(kind.equals(AbstractDocument.ParagraphElementName))
{
返回新段落视图(elem);
}
else if(kind.equals(AbstractDocument.SectionElementName))
{
返回新的CenteredBoxView(元素,视图Y_轴);
}
else if(kind.equals(StyleConstants.ComponentElementName))
{
返回新组件视图(elem);
}
else if(kind.equals(StyleConstants.IconElementName))
{
返回新的IconView(元素);
}
}
//默认为文本显示
返回新的LabelView(elem);
}
}//类StyledViewFactory
}//类MyEditorKit
以静态类为中心的BoxView扩展了BoxView
{
公共中心框视图(元素元素,内轴)
{
超级(元素,轴);
}
受保护的空心布局主轴线(int targetSpan、int轴、int[]偏移量、int[]跨距)
{
超级布局主轴线(目标跨度、轴、偏移、跨度);
int textBlockHeight=0;
整数偏移=0;
对于(int i=0;i