好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java实现聊天室界面

本文实例为大家分享了Java实现聊天室界面的具体代码,供大家参考,具体内容如下

服务器端:

?

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

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

package Server;

 

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.ArrayList;

import java.util.List;

 

import javax.swing.BorderFactory;

import javax.swing.JFrame;

import javax.swing.JButton;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JList;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

 

public class ServerFrame extends JFrame implements ActionListener {

 

    private JButton jbt_start;

    private JButton jbt_stop;

    private JButton jbt_exit;

    private JTextArea jta_disMess;

    private JList jlt_disUsers;

 

    private Server server;

 

    public List<String> online_usernames;

    public List<Integer> online_usernameids;

 

    public ServerFrame(Server server) {

        this .server = server;

        online_usernames = new ArrayList<String>();

        online_usernameids = new ArrayList<Integer>();

        try {

            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        } catch (InstantiationException e) {

            e.printStackTrace();

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        } catch (UnsupportedLookAndFeelException e) {

            e.printStackTrace();

        }

        setTitle( "\u670D\u52A1\u5668" );

        setIconImage(Toolkit.getDefaultToolkit().getImage( "Images/socket.jpg" ));

        setSize( 449 , 301 );

        setResizable( false );

        WinCenter.center( this );

        addWindowListener( new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent arg0) {

                jbt_exit.doClick();

            }

        });

        getContentPane().setLayout( null );

 

        jbt_start = new JButton( "\u542F\u52A8\u670D\u52A1\u5668" );

        jbt_start.setBounds( 32 , 23 , 103 , 34 );

        jbt_start.addActionListener( this );

        getContentPane().add(jbt_start);

 

        jbt_stop = new JButton( "\u505C\u6B62\u670D\u52A1\u5668" );

        jbt_stop.setBounds( 145 , 23 , 103 , 34 );

        jbt_stop.setEnabled( false );

        jbt_stop.addActionListener( this );

        getContentPane().add(jbt_stop);

 

        jbt_exit = new JButton( "\u9000\u51FA\u670D\u52A1\u5668" );

        jbt_exit.setBounds( 258 , 23 , 103 , 34 );

        jbt_exit.addActionListener( this );

        getContentPane().add(jbt_exit);

 

        JScrollPane scrollPane = new JScrollPane();

        scrollPane.setBounds( 10 , 64 , 221 , 192 );

        scrollPane.setWheelScrollingEnabled( true );

        scrollPane.setBorder(BorderFactory.createTitledBorder( "聊天消息" ));

        getContentPane().add(scrollPane);

 

        jta_disMess = new JTextArea();

        scrollPane.setViewportView(jta_disMess);

 

        JScrollPane scrollPane_1 = new JScrollPane();

        scrollPane_1.setBounds( 258 , 65 , 157 , 191 );

        scrollPane_1.setBorder(BorderFactory.createTitledBorder( "在线用户" ));

        getContentPane().add(scrollPane_1);

 

        jlt_disUsers = new JList();

        jlt_disUsers.setVisibleRowCount( 4 );

        scrollPane_1.setViewportView(jlt_disUsers);

    }

 

    /**

      *

      */

    private static final long serialVersionUID = 1L;

 

    @Override

    public void actionPerformed(ActionEvent arg0) {

        if (arg0.getSource() == jbt_start) {

            jbt_start.setEnabled( false );

            jbt_stop.setEnabled( true );

            server.startServer();

        }

        if (arg0.getSource() == jbt_stop) {

            int flag = JOptionPane.showConfirmDialog( this , "是否要停止服务器?" , "" ,

                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (flag == JOptionPane.OK_OPTION) {

                server.stopServer();

                jbt_start.setEnabled( true );

                jbt_stop.setEnabled( false );

            }

        }

        if (arg0.getSource() == jbt_exit) {

            if (jbt_stop.isEnabled()) {

                jbt_stop.doClick();

            }

            server.close();

        }

    }

 

    public void setDisUsers(String userNames) {

        if (userNames.equals( "@userlist" )) {

            jlt_disUsers.removeAll();

            String[] user_null = new String[]{};

            jlt_disUsers.setListData(user_null);

        } else {

            if (userNames.contains( "@userlist" )) {

                String[] dis = userNames.split( "@userlist" );

                String[] disUsernames = new String[dis.length / 2 ];

                int j = 0 ;

                for ( int i = 0 ; i < dis.length; i++) {

                    disUsernames[j++] = dis[i++];

                }

                jlt_disUsers.removeAll();

                jlt_disUsers.setListData(disUsernames);

            }

            if (userNames.contains( "@exit" )) {

                String[] dis = {};

                jlt_disUsers.setListData(dis);

            }

        }

    }

 

    public void setDisMess(String message) {

        if (message.contains( "@chat" )) {

            int local = message.indexOf( "@chat" );

            jta_disMess.append(message.substring( 0 , local) + "\n" );

            jta_disMess.setCaretPosition(jta_disMess.getText().length());

        }

        if (message.contains( "@exit" )) {

            jta_disMess.setText( "" );

        }

    }

 

    public void setStartAndStopUnable() {

        JOptionPane.showMessageDialog( this , "不能同时开启两个服务器" );

        jbt_start.setEnabled( false );

        jbt_stop.setEnabled( false );

    }

}

设置窗口居中代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

package Server;

 

import java.awt.Dimension;

import java.awt.Toolkit;

import java.awt.Window;

 

public class WinCenter {

    public static void center(Window win) {

        Toolkit tkit = Toolkit.getDefaultToolkit();

        Dimension sSize = tkit.getScreenSize();

        Dimension wSize = win.getSize();

        if (wSize.height > sSize.height) {

            wSize.height = sSize.height;

        }

        if (wSize.width > sSize.width) {

            wSize.width = sSize.width;

        }

        win.setLocation((sSize.width - wSize.width) / 2 , (sSize.height - wSize.height) / 2 );

    }

}

客户端:

登录界面

?

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

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

package Client;

 

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

 

import java.awt.Font;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.net.Inet4Address;

import java.net.UnknownHostException;

 

import javax.swing.JTextField;

import javax.swing.JButton;

 

public class Client_enterFrame extends JFrame implements ActionListener, KeyListener {

    public Client_enterFrame(Client client) {

        this .client = client;

        try {

            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        } catch (ClassNotFoundException e1) {

            e1.printStackTrace();

        } catch (InstantiationException e1) {

            e1.printStackTrace();

        } catch (IllegalAccessException e1) {

            e1.printStackTrace();

        } catch (UnsupportedLookAndFeelException e1) {

            e1.printStackTrace();

        }

        setIconImage(Toolkit.getDefaultToolkit().getImage( "Images/socket.jpg" ));

        setTitle( "\u804A\u5929\u5BA4" );

        getContentPane().setLayout( null );

        setSize( 296 , 249 );

        WinCenter.center( this );

        setResizable( false );

        addWindowListener( new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent e) {

                jbt_exit.doClick();

            }

        });

 

        JLabel lblNewLabel = new JLabel( "\u7528\u6237\u540D" );

        lblNewLabel.setFont( new Font( "宋体" , Font.PLAIN, 14 ));

        lblNewLabel.setBounds( 23 , 30 , 81 , 34 );

        getContentPane().add(lblNewLabel);

 

        jtf_username = new JTextField();

        jtf_username.addKeyListener( this );

        jtf_username.setBounds( 114 , 30 , 143 , 34 );

        getContentPane().add(jtf_username);

        jtf_username.setColumns( 10 );

 

        JLabel lblNewLabel_1 = new JLabel( "\u670D\u52A1\u5668\u5730\u5740" );

        lblNewLabel_1.setFont( new Font( "宋体" , Font.PLAIN, 14 ));

        lblNewLabel_1.setBounds( 23 , 74 , 81 , 34 );

        getContentPane().add(lblNewLabel_1);

 

        jtf_hostIp = new JTextField();

        jtf_hostIp.setBounds( 114 , 74 , 143 , 34 );

        jtf_hostIp.addKeyListener( this );

        getContentPane().add(jtf_hostIp);

        try {

            String ip = (String) Inet4Address.getLocalHost().getHostAddress();

            jtf_hostIp.setText(ip);

        } catch (UnknownHostException e) {

            e.printStackTrace();

        }

        jtf_hostIp.setColumns( 10 );

 

        JLabel lblNewLabel_2 = new JLabel( "\u7AEF\u53E3\u53F7" );

        lblNewLabel_2.setFont( new Font( "宋体" , Font.PLAIN, 14 ));

        lblNewLabel_2.setBounds( 23 , 118 , 81 , 34 );

        getContentPane().add(lblNewLabel_2);

 

        jtf_hostPort = new JTextField();

        jtf_hostPort.addKeyListener( this );

        jtf_hostPort.setBounds( 114 , 118 , 143 , 34 );

        getContentPane().add(jtf_hostPort);

        jtf_hostPort.setText( "5000" );

        jtf_hostPort.setColumns( 10 );

 

        jbt_enter = new JButton( "\u8FDB\u5165\u804A\u5929\u5BA4" );

        jbt_enter.addActionListener( this );

        jbt_enter.addKeyListener( this );

        jbt_enter.setFont( new Font( "宋体" , Font.PLAIN, 14 ));

        jbt_enter.setBounds( 23 , 162 , 108 , 39 );

        getContentPane().add(jbt_enter);

 

        jbt_exit = new JButton( "\u9000\u51FA\u804A\u5929\u5BA4" );

        jbt_exit.setFont( new Font( "宋体" , Font.PLAIN, 14 ));

        jbt_exit.setBounds( 144 , 162 , 113 , 39 );

        jbt_exit.addActionListener( this );

        getContentPane().add(jbt_exit);

    }

 

    /**

      *

      */

    private static final long serialVersionUID = 1L;

    private JTextField jtf_username;

    private JTextField jtf_hostIp;

    private JTextField jtf_hostPort;

    private JButton jbt_enter;

    private JButton jbt_exit;

    private Client client;

 

 

    @Override

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == jbt_exit) {

            setVisible( false );

            client.exitLogin();

        }

        if (e.getSource() == jbt_enter) {

            String username = jtf_username.getText();

            username.trim();

            String hostIp = jtf_hostIp.getText();

            hostIp.trim();

            String hostPort = jtf_hostPort.getText();

            hostPort.trim();

            if (!username.equals( "" )) {

                if (!hostIp.equals( "" )) {

                    if (!hostPort.equals( "" )) {

                        String login_mess = client.login(username, hostIp, hostPort);

                        if (login_mess.equals( "true" )) {

                            this .setVisible( false );

                            client.showChatFrame(username);

                        } else {

                            JOptionPane.showMessageDialog( this , login_mess);

                        }

                    } else {

                        JOptionPane.showMessageDialog( this , "服务器连接端口号不能为空!" );

                    }

                } else {

                    JOptionPane.showMessageDialog( this , "服务器地址不能为空!" );

                }

            } else {

                JOptionPane.showMessageDialog( this , "用户名不能为空!" );

            }

        }

    }

 

    @Override

    public void keyPressed(KeyEvent arg0) {

        if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {

            jbt_enter.doClick();

        }

    }

 

    @Override

    public void keyReleased(KeyEvent arg0) {

    }

 

    @Override

    public void keyTyped(KeyEvent arg0) {

    }

}

聊天主界面

?

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

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

package Client;

 

import java.awt.Font;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.ArrayList;

import java.util.List;

 

import javax.swing.BorderFactory;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JList;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

import javax.swing.ListModel;

import javax.swing.ListSelectionModel;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

import javax.swing.event.ListSelectionEvent;

import javax.swing.event.ListSelectionListener;

 

public class Client_chatFrame extends JFrame implements ActionListener,

        KeyListener, ListSelectionListener {

    public Client_chatFrame(Client client, String title) {

        this .client = client;

        try {

            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        } catch (InstantiationException e) {

            e.printStackTrace();

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        } catch (UnsupportedLookAndFeelException e) {

            e.printStackTrace();

        }

        setIconImage(Toolkit.getDefaultToolkit().getImage( "Images/socket.jpg" ));

        setTitle( "\u804A\u5929\u5BA4" + "  " + title);

        setSize( 450 , 325 );

        WinCenter.center( this );

        setResizable( false );

        addWindowListener( new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent arg0) {

                jbt_exit.doClick();

            }

        });

        getContentPane().setLayout( null );

 

        JScrollPane scrollPane = new JScrollPane();

        scrollPane.setBorder(BorderFactory.createTitledBorder( "聊天消息" ));

        scrollPane.setBounds( 10 , 10 , 283 , 167 );

        scrollPane.setWheelScrollingEnabled( true );

        getContentPane().add(scrollPane);

 

        jta_disMess = new JTextArea();

        jta_disMess.setEditable( false );

        scrollPane.setViewportView(jta_disMess);

 

        jtf_inputMess = new JTextField();

        jtf_inputMess.addKeyListener( this );

        jtf_inputMess.setBounds( 10 , 242 , 192 , 32 );

        getContentPane().add(jtf_inputMess);

        jtf_inputMess.setColumns( 10 );

 

        jbt_trans = new JButton( "\u53D1  \u9001" );

        jbt_trans.setFont( new Font( "宋体" , Font.PLAIN, 14 ));

        jbt_trans.setBounds( 212 , 241 , 93 , 32 );

        jbt_trans.addActionListener( this );

        getContentPane().add(jbt_trans);

 

        jbt_clear = new JButton( "\u6E05\u9664\u804A\u5929\u8BB0\u5F55" );

        jbt_clear.setFont( new Font( "宋体" , Font.PLAIN, 14 ));

        jbt_clear.setBounds( 158 , 187 , 135 , 37 );

        jbt_clear.addActionListener( this );

        getContentPane().add(jbt_clear);

 

        jbt_exit = new JButton( "\u9000\u51FA\u804A\u5929\u5BA4" );

        jbt_exit.setFont( new Font( "宋体" , Font.PLAIN, 14 ));

        jbt_exit.setBounds( 20 , 189 , 128 , 37 );

        jbt_exit.addActionListener( this );

        getContentPane().add(jbt_exit);

 

        scrollPane_1 = new JScrollPane();

        scrollPane_1.setBorder(BorderFactory.createTitledBorder( "在线用户" ));

        scrollPane_1.setBounds( 303 , 10 , 128 , 214 );

        getContentPane().add(scrollPane_1);

 

        jlt_disUsers = new JList();

        jlt_disUsers.setVisibleRowCount( 4 );

        jlt_disUsers.setSelectedIndex( 0 );

        jlt_disUsers

                .setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        jlt_disUsers.addListSelectionListener( this );

        scrollPane_1.setViewportView(jlt_disUsers);

 

        jbt_singlChat = new JButton( "\u5355\u4EBA\u804A\u5929" );

        jbt_singlChat.setBounds( 315 , 241 , 116 , 32 );

        jbt_singlChat.addActionListener( this );

        getContentPane().add(jbt_singlChat);

    }

 

    /**

      *

      */

    private static final long serialVersionUID = 1L;

    private JTextField jtf_inputMess;

    private JTextArea jta_disMess;

    private JButton jbt_trans;

    private JButton jbt_clear;

    private JButton jbt_exit;

    private JList jlt_disUsers;

    private JButton jbt_singlChat;

    private JScrollPane scrollPane_1;

    private Client client;

 

    @Override

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == jbt_clear) {

            jta_disMess.setText( "" );

        }

        if (e.getSource() == jbt_trans) {

            String mess = jtf_inputMess.getText();

            mess.trim();

            jtf_inputMess.setText( "" );

            if (mess.equals( "" )) {

                JOptionPane.showMessageDialog( this , "不能发送空消息" );

                jtf_inputMess.setText( "" );

            } else {

                client.transMess(mess);

            }

        }

        if (e.getSource() == jbt_exit) {

            if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( this ,

                    "是否确定要退出聊天室?" , "提示" , JOptionPane.OK_CANCEL_OPTION)) {

                this .setVisible( false );

                client.exitChat();

                System.exit( 0 );

            }

        }

        if (e.getSource() == jbt_singlChat) {

            String user_names = (String) jlt_disUsers.getSelectedValue();

            if (user_names == null ) {

                JOptionPane.showMessageDialog( this , "您未选择聊天对象\n请选择要单独聊天的对象" );

            } else {

                if (!client.c_singleFrames.containsKey(user_names)) {

                    createSingleChatFrame(user_names);

                } else {

                    client.c_singleFrames.get(user_names)

                            .setFocusableWindowState( true );

                }

            }

        }

    }

 

    @Override

    public void keyPressed(KeyEvent arg0) {

        if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {

            if (arg0.getSource() == jtf_inputMess) {

                jbt_trans.doClick();

            }

        }

    }

 

    @Override

    public void keyReleased(KeyEvent arg0) {

    }

 

    @Override

    public void keyTyped(KeyEvent arg0) {

    }

 

    public void setDisMess(String substring) {

        int local = substring.indexOf( "@chat" );

        jta_disMess.append(substring.substring( 0 , local) + "\n" );

        jta_disMess.setCaretPosition(jta_disMess.getText().length());

    }

 

    public void setDisUsers(String chat_re) {

        String[] infos = chat_re.split( "@userlist" );

        String[] info = new String[infos.length / 2 ];

        for ( int i = 1 ; i < infos.length; i++) {

            int id_user = 0 ;

            try {

                id_user = Integer.parseInt(infos[i]);

                if (client.getThreadID() == id_user) {

                    if (!client.username.equals(infos[i - 1 ])) {

                        JOptionPane.showMessageDialog( this ,

                                "由于有同名的用户登录,所以您的用户名后面加上了编号" );

                        client.username = infos[i - 1 ];

                        this .setTitle( "聊天室    " + client.username);

                        break ;

                    } else {

                        break ;

                    }

                } else {

                    i++;

                }

            } catch (Exception e) {

            }

        }

        if (infos.length == 2 ) {

            String[] s = new String[]{};

            if (!client.c_singleFrames.isEmpty()) {

                ListModel list = jlt_disUsers.getModel();

                for ( int i = 0 ; i < list.getSize(); i++) {

                    if (client.c_singleFrames.get(list.getElementAt(i)) != null ) {

                        client.c_singleFrames.get(list.getElementAt(i))

                                .setExitNotify();

                    }

                }

            }

            jlt_disUsers.removeAll();

            jlt_disUsers.setListData(s);

        } else {

            if ((infos.length / 2 - 1 ) < client.username_online.size()) {

                // 有人下线

                List<String> rec = new ArrayList<String>();

                int i = 0 ;

                for (; i < infos.length; i++) {

                    rec.add( 0 , infos[i++]);

                }

                for (i = 0 ; i < client.username_online.size(); i++) {

                    if (!rec.contains(client.username_online.get(i))) {

                        break ;

                    }

                }

                String name = client.username_online.get(i);

                client.username_online.remove(i);

                try {

                    client.clientuserid.remove(i);

                } catch (Exception e) {

                    e.printStackTrace();

                }

 

                if (client.c_singleFrames.containsKey(name)) {

                    client.c_singleFrames.get(name).closeSingleFrame();

                    client.c_singleFrames.remove(name);

                }

            } else {

                List<Integer> online = new ArrayList<Integer>();

                for ( int i = 0 ; i < client.username_online.size(); i++) {

                    online.add( 0 , client.clientuserid.get(i));

                }

                if (online.isEmpty()) {

                    for ( int i = 1 ; i < infos.length; i++) {

                        if (( int ) Integer.parseInt(infos[i]) != client

                                .getThreadID()) {

                            client.username_online.add( 0 , infos[i - 1 ]);

                            client.clientuserid.add( 0 ,

                                    Integer.parseInt(infos[i]));

                        }

                        i++;

                    }

                } else {

                    for ( int i = 1 ; i < infos.length; i++) {

                        if (Integer.parseInt(infos[i]) != client.getThreadID()) {

                            if (!online.contains(Integer.parseInt(infos[i]))) {

                                client.username_online.add( 0 , infos[i - 1 ]);

                                client.clientuserid.add( 0 ,

                                        Integer.parseInt(infos[i]));

                            } else {

                                String name = client.username_online

                                        .get(client.clientuserid

                                                .indexOf(Integer

                                                        .parseInt(infos[i])));

                                if (!name.equals(infos[i - 1 ])) {

                                    if (client.c_singleFrames.containsKey(name)) {

                                        Client_singleFrame cf = client.c_singleFrames

                                                .get(name);

                                        cf.setTitle(name);

                                        client.c_singleFrames.remove(name);

                                        client.c_singleFrames.put(name, cf);

                                        cf.setVisible( false );

 

                                    }

                                    client.username_online.remove(name);

                                    client.clientuserid.remove( new Integer(

                                            Integer.parseInt(infos[i])));

                                    client.username_online.add( 0 , infos[i - 1 ]);

                                    client.clientuserid.add( 0 ,

                                            Integer.parseInt(infos[i]));

                                }

                            }

                        }

                        i++;

                    }

                }

 

            }

            try {

                for ( int i = 0 ; i < client.username_online.size(); i++) {

                    info[i] = client.username_online.get(i);

                }

 

            } catch (Exception e) {

            }

            jlt_disUsers.removeAll();

            jlt_disUsers.setListData(info);

        }

    }

 

    public void closeClient() {

        JOptionPane.showMessageDialog( this , "服务器已关闭" , "提示" ,

                JOptionPane.OK_OPTION);

        client.exitClient();

        setVisible( false );

    }

 

    @Override

    public void valueChanged(ListSelectionEvent e) {

        if (e.getSource() == jlt_disUsers) {

        }

    }

 

    public void createSingleChatFrame(String name) {

        Client_singleFrame c_singlFrame = new Client_singleFrame(client, name);

        client.c_singleFrames.put(name, c_singlFrame);

        try {

            c_singlFrame.userThreadID = client.clientuserid

                    .get(client.username_online.indexOf(name));

        } catch (Exception e) {

        }

 

        c_singlFrame.setVisible( true );

    }

 

    public void setSingleFrame(String chat_re) {

        String[] infos = chat_re.split( "@single" );

        try {

            if (client.c_singleFrames.containsKey(infos[ 0 ])) {

                client.c_singleFrames.get(infos[ 0 ]).setDisMess(infos[ 3 ]);

            } else {

                createSingleChatFrame(infos[ 0 ]);

                client.c_singleFrames.get(infos[ 0 ]).setDisMess(infos[ 3 ]);

            }

        } catch (Exception e) {

        }

    }

}

单人聊天界面

?

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

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

package Client;

 

import java.awt.BorderLayout;

import java.awt.Component;

import java.awt.Container;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

import javax.swing.BorderFactory;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

 

public class Client_singleFrame extends JFrame implements ActionListener, KeyListener {

 

    /**

      *

      */

    private static final long serialVersionUID = 1L;

    private static JTextArea jta_disMess;

    private JTextField jtf_inputMess;

    private JButton jbt_trans;

 

    public int userThreadID = 0 ;

 

    private Client client;

 

    public Client_singleFrame(Client client, String title) {

        this .client = client;

        init(title);

    }

 

    private void init(String title) {

        try {

            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        } catch (ClassNotFoundException e1) {

            e1.printStackTrace();

        } catch (InstantiationException e1) {

            e1.printStackTrace();

        } catch (IllegalAccessException e1) {

            e1.printStackTrace();

        } catch (UnsupportedLookAndFeelException e1) {

            e1.printStackTrace();

        }

        setIconImage(Toolkit.getDefaultToolkit().getImage( "Images/socket.jpg" ));

        WinCenter.center( this );

        setTitle(title);

        setSize( 400 , 400 );

        setResizable( false );

        setContentPane(createContentPanel());

        addWindowListener( new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent e) {

                closeSingleFrame();

            }

        });

    }

 

    private Container createContentPanel() {

        JPanel jp = new JPanel();

        jp.setBorder(BorderFactory.createTitledBorder( "聊天消息" ));

        jp.setLayout( new BorderLayout());

        jta_disMess = new JTextArea();

        jta_disMess.setEditable( false );

        jp.add(BorderLayout.CENTER, new JScrollPane(jta_disMess));

        jp.add(BorderLayout.SOUTH, createInput());

        return jp;

    }

 

    private Component createInput() {

        JPanel jp = new JPanel();

        jp.setBorder(BorderFactory.createTitledBorder( "发送消息" ));

        jp.setLayout( new BorderLayout());

        jtf_inputMess = new JTextField();

        jtf_inputMess.addKeyListener( this );

        jbt_trans = new JButton( "发送" );

        jbt_trans.addActionListener( this );

        jp.add(jtf_inputMess, BorderLayout.CENTER);

        jp.add(jbt_trans, BorderLayout.EAST);

        return jp;

    }

 

    @Override

    public void keyPressed(KeyEvent arg0) {

        if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {

            if (arg0.getSource() == jtf_inputMess) {

                jbt_trans.doClick();

            }

        }

    }

 

    @Override

    public void keyReleased(KeyEvent arg0) {

    }

 

    @Override

    public void keyTyped(KeyEvent arg0) {

    }

 

    @Override

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == jbt_trans) {

            String str = jtf_inputMess.getText();

            str.trim();

            jtf_inputMess.setText( "" );

            if (str.equals( "" )) {

                JOptionPane.showMessageDialog( this , "信息不能为空" );

            } else {

                SimpleDateFormat form = new SimpleDateFormat( "yyyy-MM-dd  HH:mm" );

                String date = form.format( new Date());

                String mess = client.username + "  " + date + "\n" + str;

                jta_disMess.append(mess + "\n" );

                jta_disMess.setCaretPosition(jta_disMess.getText().length());

                int index = client.username_online.indexOf( this .getTitle());

                String info = client.username + "@single" + client.getThreadID() + "@single" +

                        ( int ) client.clientuserid.get(index) + "@single" +

                        mess + "@single" ;

                try {

                    client.dos.writeUTF(info);

                } catch (IOException e1) {

                    e1.printStackTrace();

                }

            }

        }

    }

 

    public void setDisMess(String chat_re) {

        jta_disMess.append(chat_re + "\n" );

        jta_disMess.setCaretPosition(jta_disMess.getText().length());

    }

 

    public void closeSingleFrame() {

        client.c_singleFrames.remove( this .getTitle());

        setVisible( false );

    }

 

    public void setExitNotify() {

        jta_disMess.append( this .getTitle() + "已下线....." );

        jbt_trans.setEnabled( false );

    }

}

设置窗体居中

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

package Client;

 

import java.awt.Dimension;

import java.awt.Toolkit;

import java.awt.Window;

 

public class WinCenter {

    public static void center(Window win) {

        Toolkit tkit = Toolkit.getDefaultToolkit();

        Dimension sSize = tkit.getScreenSize();

        Dimension wSize = win.getSize();

        if (wSize.height > sSize.height) {

            wSize.height = sSize.height;

        }

        if (wSize.width > sSize.width) {

            wSize.width = sSize.width;

        }

        win.setLocation((sSize.width - wSize.width) / 2 , (sSize.height - wSize.height) / 2 );

    }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/Zhengxinyu666/article/details/99693712

查看更多关于Java实现聊天室界面的详细内容...

  阅读:10次