【问题标题】:How to set alignement in JTextPane?如何在 JTextPane 中设置对齐方式?
【发布时间】:2017-06-17 23:12:06
【问题描述】:

我正在尝试用 Java 制作一个聊天应用程序;我选择使用JTextPane 来显示消息,因为我读到它支持对齐。我的问题是我想知道如何在其中对齐文本。就像我是发件人一样,发送的消息将右对齐;当我是接收者时,它将向左对齐。

这是我写的代码,但它使整个文本左右对齐:

package memory;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

import java.awt.Toolkit;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextPane;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;

import javax.swing.ScrollPaneConstants;
import java.awt.Font;

@SuppressWarnings("serial")
public class ChatFrame extends JFrame {

private JPanel contentPane;
private JTextPane textPane= new JTextPane();;
private String msg=null;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ChatFrame frame = new ChatFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

//setRemote Text
//false->me true->him 
public void setTextToTextPane(String txt,boolean received) throws BadLocationException{
    StyledDocument doc=textPane.getStyledDocument();

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

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

    if(received==false){
        doc.insertString(doc.getLength(), txt="\n", right);
        doc.setParagraphAttributes(doc.getLength(), 1, right, false);
    }else{
        doc.insertString(doc.getLength(), txt="\n", left);
        doc.setParagraphAttributes(doc.getLength(), 1, left, false);
    }

}

/**
 * Create the frame.
 */
public ChatFrame() {
    setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\PC-HOME\\Desktop\\design\\Speech Bubble-41.png"));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 299, 380);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    JPanel panel = new JPanel();
    contentPane.add(panel, BorderLayout.CENTER);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    JScrollPane scrollPane_1 = new JScrollPane();
    GroupLayout gl_panel = new GroupLayout(panel);
    gl_panel.setHorizontalGroup(
        gl_panel.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_panel.createSequentialGroup()
                .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 272, GroupLayout.PREFERRED_SIZE)
                    .addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE, 272, GroupLayout.PREFERRED_SIZE))
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    gl_panel.setVerticalGroup(
        gl_panel.createParallelGroup(Alignment.LEADING)
            .addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
                .addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE))
    );
    textPane.setFont(new Font("Consolas", Font.PLAIN, 14));
    textPane.setEditable(false);

    scrollPane_1.setViewportView(textPane);

    JTextArea textArea = new JTextArea();
    textArea.setFont(new Font("Consolas", Font.PLAIN, 14));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.addKeyListener(new KeyAdapter() {
        @SuppressWarnings("unchecked")
        @Override
        public void keyPressed(KeyEvent event) {
            if(event.getKeyCode()==KeyEvent.VK_ENTER){
                if(event.isShiftDown())
                    textArea.setText(textArea.getText()+"\n");
                else{
                    msg=textArea.getText();
                    event.consume();
                    textArea.setText(null);
                    try {
                        //HelperMethods.sendMessageSocket(msg,port);
                        setTextToTextPane(msg,false);
                    } catch (BadLocationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    ArrayList<String> sendMsg=new ArrayList<>();
                    sendMsg.add(getTitle());
                    sendMsg.add(msg);
                    StaticData.sendMsg.add(sendMsg);
                }
            }
        }
    });

    addWindowListener(new WindowListener() {

        @Override
        public void windowOpened(WindowEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void windowIconified(WindowEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void windowDeiconified(WindowEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void windowDeactivated(WindowEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void windowClosing(WindowEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void windowClosed(WindowEvent e) {
            // TODO Auto-generated method stub
            String name=getTitle();
            StaticData.frameMap.remove(name);
        }

        @Override
        public void windowActivated(WindowEvent e) {
            // TODO Auto-generated method stub

        }
    });

    scrollPane.setViewportView(textArea);
    panel.setLayout(gl_panel);
}

}

有人知道怎么做吗?

【问题讨论】:

  • @Frakcool 它不起作用
  • 什么不起作用?请edit您的问题并发布一个有效的minimal reproducible example来证明您的问题,解释为什么链接的问题不起作用
  • @Frakcool 我编辑了我正在等待你的回答的帖子
  • StaticData 和 HelperMethods 类在哪里?没有它们,您包含的代码将无法编译,并且应用程序不会对它进行任何注释。包含一个简短的可编译示例,以便我们为您提供帮助!

标签: java swing


【解决方案1】:

在代码示例的“setTextToTextPane”中,您插入了“txt="\n"”。这应该是“”txt + “\n”。如果没有此更改,它将不会打印任何内容。 在设置属性方面,您在“setTextToPane”中所做的事情是正确的。如果您进行单元测试,它会根据“received”的值正确地将文本定位在左侧或右侧。

【讨论】:

    猜你喜欢
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2011-10-19
    相关资源
    最近更新 更多