0

Hi I am creating a simple Java-Server chat and I simply cannot get swing to play nice with long strings.

Image showing text not wrapping.

I don't want the horizontal scroll bar and I want the word to break when needed and flow to another line.

The code I have used to create the JTextPane is:

super("Message Server");
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(
        new ActionListener(){
            public void actionPerformed(ActionEvent event){
                sendMessage(event.getActionCommand());
                userText.setText("");
            }
        }
    );
    getContentPane().add(userText, BorderLayout.SOUTH);
    chatWindow = new JTextPane();
    JScrollPane scrollPane = new JScrollPane(chatWindow);
    getContentPane().add(scrollPane);

    setSize(300, 450); //Sets the window size
    setVisible(true);

    chatWindow.setEditable(false);
Adrian Heine
  • 4,051
  • 2
  • 30
  • 43
James McNee
  • 302
  • 2
  • 14

2 Answers2

2

Instead of using JTextPane you can use JTextArea and corresponding wrapping related methods setLineWrap() and setWrapStyleWord() to achieve what you want.

Yes you can set Font with JTextArea Eg.

JTextArea txtArea = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txtArea.setFont(font);
txtArea.setForeground(Color.BLUE);
txtArea.setText("Hellow World!");
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Hi, I was originally using a JTextArea, but the problem with this is that there is no colouring of text which I really do need to differentiate between who sent what message. Unless of-course I am mistaken and you actually can do this with a JTextArea? – James McNee Mar 22 '15 at 08:28
  • yes you can change the text color. Added a sample example. – Aniket Thakur Mar 22 '15 at 08:39
  • Yes, but that changes the color of all the text, I need it so that lets say the client can be red and the server blue. In my screenshot you can see that the server is black and the client is grey. – James McNee Mar 22 '15 at 08:41
  • yes you will not be able to do that in JTextArea. Then if you have to use JTextPane refer [this question](http://stackoverflow.com/questions/7036543/how-is-word-wrapping-implemented-in-jtextpane-and-how-do-i-make-it-wrap-a-strin). You will need to add custom code for it. – Aniket Thakur Mar 22 '15 at 08:44
  • Ooft that is a lot of code for something so trivial. I'll get implementing it now haha. Thanks for your help. Really appreciated! – James McNee Mar 22 '15 at 08:47
0

Try using a JTextArea and call setWrapStyleWord(true); on its instance this should do what you need.

avk
  • 871
  • 1
  • 9
  • 22
  • Hi someone just posted this too, please see the comment I left on that answer to avoid duplication, thanks for the help tho. – James McNee Mar 22 '15 at 08:29