0

I'm trying to make a chat application with Java; I chose to use JTextPane to display messages, because I read that it supports alignment. My problem is that I want to know how to align text in it. Like when I'm the sender, the sent message will be aligned in right; and when I'm the receiver it will be aligned in left.

Here is the code I wrote, but it aligns the whole text in right or left:

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

}

Does anyone know how to do that??

Karim
  • 637
  • 1
  • 5
  • 13
  • 3
    Possible duplicate of [Java Swing JTextArea write both left and right](https://stackoverflow.com/questions/37365522/java-swing-jtextarea-write-both-left-and-right) – Frakcool Jun 16 '17 at 15:13
  • @Frakcool it didn't work form – Karim Jun 16 '17 at 15:19
  • 4
    What didn't work? Please [edit] your question and post a valid [mcve] that demonstrates your issue, explaining why the linked question doesn't work – Frakcool Jun 16 '17 at 15:25
  • @Frakcool i edited the post i'm waiting for your answer – Karim Jun 16 '17 at 17:31
  • Where are you StaticData and HelperMethods classes? The code you included won't compile without them, and the app doesn't do anything with it commented out. Include a short, compilable example so we can help you out! – Amber Jun 16 '17 at 21:06
  • The first problem I see in your code is in "setTextToTextPane" you're inserting "txt="\n"". I can only assume you meant to write ""txt + "\n". Without this change it wasn't printing anything. Also, what you're doing in "setTextToPane" is correct (if you do a unit test). It does switch the text left or right depending on the value of "received". – Amber Jun 16 '17 at 21:23
  • @Amber its as You said thank you can you post it as an answer please and thank you again?? – Karim Jun 17 '17 at 09:04

1 Answers1

0

In "setTextToTextPane" in your code sample you're inserting "txt="\n"". This should be ""txt + "\n". Without this change it won't printing anything. What you're doing in "setTextToPane" is correct in terms of setting the attributes. If you do a unit test it correctly positions the text left or right depending on the value of "received".

Amber
  • 2,413
  • 1
  • 15
  • 20