Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (511)
Games in Android Showcase (119)
games submitted by our members
Games in WIP (577)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Simple "console like" chat  (Read 2988 times)
0 Members and 1 Guest are viewing this topic.
Offline williamwoles

Senior Newbie





« Posted 2011-02-27 23:49:05 »

Hello,

I want to share with you some code which I have recently finished, which gives respect to the game chat GUI. For the game I'm making, I needed some component, which would allow coloured text, content appending and removing when some limit of lines is reached and some scroll behaviour, which I'll post after I will implement it Wink.

The chat has following aspect


So, as main container of the content I have chosen JTextPane, since it allows HTML(which make possible full personalization of the text, including colour, text styles and much more). But there were several problems and challenges to solve, like appending and removing the text because JTextPane doesn't have such options.

I'm using the following code for creation of the JTextPane, note that there should be set HTMLEditorKit and HTMLDocument to the JTextPane, else HTML will not be rendered(thanks for people from StackOverflow helping me solve this issue)
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
this.text_panel = new JTextPane();
this.text_panel.setContentType("text/html");
this.text_panel.setEditable(false);
this.text_panel.setBackground(this.text_background_color);
this.text_panel_html_kit = new HTMLEditorKit();this.text_panel.setEditorKit(text_panel_html_kit);
this.text_panel.setDocument(new HTMLDocument());

scroll_pane = new JScrollPane(this.text_panel);
scroll_pane.setBounds(5,5,580,110);
scroll_pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll_pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
this.add(scroll_pane);


The next step was creating the append function. You will need to work directly with the HTMLDocument set to the JTextPane in previous step. My append function looks like:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
public void append(String line){
   SimpleDateFormat date_format = new SimpleDateFormat("HH:mm:ss");
   Date date = new Date();
     
   line = "<div><font size=3 color=GRAY>[" + date_format.format(date) + "]</font><font size=3 color=BLACK>"+ line + "</font></div>";
     
   try {
      this.text_panel_html_kit.insertHTML((HTMLDocument) this.text_panel.getDocument(), this.text_panel.getDocument().getLength(), line, 0, 0, null);
   } catch (Exception e) {
      e.printStackTrace();
   }
}


The next step is creating line limit and remove the lines from the start which pass the limit. For this step I have used LimitLinesDocumentListener taken from http://tips4java.wordpress.com/2008/10/15/limit-lines-in-document/ (read on the blog about how it's being used). Though I needed to do some changes in the removeLines function(which in my case will not use functions removeFromStart and removeFromEnd. And now it's looks like:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
private void removeLines(DocumentEvent e)
{
   Document document = e.getDocument();

   try {
      while (((HTMLDocument) document).getText(0, document.getLength()).split("\\n").length > maximumLines)
      {
         int end = document.getText(0, document.getLength()).split("\\n")[0].length();
           
         document.remove(0, end+1);
      }
   } catch (BadLocationException e1) {
      e1.printStackTrace();
   }
}


The last step is adding the listener to the text_panel, this is done with following code:

1  
2  
LimitLinesDocumentListener limitLinesListener = new LimitLinesDocumentListener(Configuration.getInstance().CHAT_VISIBLE_LINES);
this.text_panel.getDocument().addDocumentListener(limitLinesListener);


And before finishing note, there was also added some scroll behaviour, which makes the scroll jump to the last inserted item, achieved with following code:

1  
2  
DefaultCaret caret = (DefaultCaret)text_panel.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);


I hope this will help some1 and save some time implementing nice chat(console) with colours and appending/removing. If you will find some optimization issues in my code or some things which can be simplified I will be very thankful if you report them in this topic or via pm.

Thanks for attention Wink

Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #1 - Posted 2011-02-28 01:36:13 »

To append or remove strings from JTextPane, you use the StyledDocument by calling getStyledDocument() on the JTextPane object. StyledDocument has insertString() and remove()

Instead of using HTML, you create Styles by calling addStyle() in StyledDocument, which returns a Style object that you can customize using the StyleConstants class. Then whenever you need to insert a string, you give insertString() the string and the style you want to use.
Example:
1  
2  
3  
4  
5  
6  
StyledDocument styledDoc = textPane.getStyledDocument();
...
Style style = styledDoc.addStyle("MyStyleName",null);
StyleConstants.setForeground(style,Color.red);
...
styledDoc.insertString(styledDoc.getLength(),line,styledDoc.getStyle("MyStyleName"));

Offline williamwoles

Senior Newbie





« Reply #2 - Posted 2011-02-28 10:04:15 »

I have tried to work with StyledDocument.. I could get it showing correctly different colour line(different colors in the same line). That was the main reason why I started to work with HTML. Another thing, does Styled document will allow to be extended to show emotes and for example links to items?

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #3 - Posted 2011-02-28 21:31:34 »

Yes, images and JComponent's are supported, though you use the methods insertIcon() and insertComponent() in JTextPane.

I have looked everywhere how to add links and have still found nothing. The only way I can think of doing links is to add a JLabel to the text pane and have a mouseListener set on it that would process the click.

For the complete set of API, refer here:
http://ra4king.is-a-geek.net/javadocs/javax/swing/JTextPane.html
http://ra4king.is-a-geek.net/javadocs/javax/swing/text/StyledDocument.html

If you want example code from my chat box, ask and I will post a link to the zip file.

Hope that helps!

EDIT: I have just realized that HTMLDocument implements StyledDocument. This means you can just give it links using
1  
<a href="www.example.com">www.example.com</a>

Offline williamwoles

Senior Newbie





« Reply #4 - Posted 2011-03-01 00:28:05 »

You could post some code of you chat, so every could have benefit from using it.

Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #5 - Posted 2011-03-01 01:26:25 »

Sure! I have removed all the networkings and listeners to just show what I used to create the visual. I use 2 custom Styles: Names and Notifications. The Names is just to bold the name of the chatter. The Notifications is for system messages. This is an applet so that's why you see the init() and add() methods.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
private JButton connect;
private JScrollPane scrollPane;
private JTextPane chatArea;
private JTextField chatField;
private StyledDocument chat;
private Box names;

public void init() {
   createChatArea();
   createNamesArea();
   
   chat = chatArea.getStyledDocument();
   createStyles();
   
   setSize(500,500);
   
   users = new ArrayList<JLabel>();
   
   chatField.addActionListener(new ChatListener());
}

private void createChatArea() {
   JPanel panel = new JPanel(new BorderLayout());
   
   chatArea = new JTextPane();
   chatArea.setEditable(false);
   scrollPane = (JScrollPane)panel.add(new JScrollPane(chatArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
   chatField = new JTextField();
   panel.add(chatField,BorderLayout.SOUTH);
   
   add(panel);
}

private void createNamesArea() {
   Box box = Box.createVerticalBox();
   
   names = Box.createVerticalBox();
   
   JScrollPane pane = new JScrollPane(names);
   box.add(pane);
   
   pane.setPreferredSize(new Dimension(100,500));
   
   Box box2 = Box.createHorizontalBox();
   
   JButton button = (JButton)box2.add(new JButton("Send"));
   button.setMinimumSize(new Dimension(65,20));
   button.setPreferredSize(new Dimension(65,20));
   button.setMaximumSize(new Dimension(65,20));
   button.addActionListener(new ChatListener());
   
   connect = (JButton)box2.add(new JButton("Connect"));
   connect.setMinimumSize(new Dimension(85,20));
   connect.setPreferredSize(new Dimension(85,20));
   connect.setMaximumSize(new Dimension(85,20));
   connect.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
         if(!connected) {
            chatArea.setText("");
         }
      }
   });
   
   box.add(box2);
   
   add(box,BorderLayout.EAST);
}

private void createStyles() {
   Style s = chat.addStyle("Names",null);
   StyleConstants.setBold(s,true);
   
   s = chat.addStyle("Notifications",null);
   StyleConstants.setForeground(s,Color.white);
   StyleConstants.setBackground(s,Color.red);
}


When I receive a new messages from a chatter, this is the code to output:
1  
2  
chat.insertString(chat.getLength(),name + ": ",chat.getStyle("Names"));
chat.insertString(chat.getLength(),message + "\n",null);


And for a system notification:
1  
chat.insertString(chat.getLength(),notif + "\n",chat.getStyle("Notifications"));

Offline Matthias

Senior Duke


Medals: 3
Projects: 1


TWL - Themable Widget Library


« Reply #6 - Posted 2011-03-01 01:32:10 »

You could also take a look at the TWL Chat Demo and it's source code.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Longarmx (52 views)
2014-10-17 03:59:02

Norakomi (41 views)
2014-10-16 15:22:06

Norakomi (32 views)
2014-10-16 15:20:20

lcass (37 views)
2014-10-15 16:18:58

TehJavaDev (68 views)
2014-10-14 00:39:48

TehJavaDev (66 views)
2014-10-14 00:35:47

TehJavaDev (58 views)
2014-10-14 00:32:37

BurntPizza (72 views)
2014-10-11 23:24:42

BurntPizza (45 views)
2014-10-11 23:10:45

BurntPizza (85 views)
2014-10-11 22:30:10
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!