用Java制作一个简单的QQ聊天界面
第一次写博客
这是一开始学习Java时候用Java制作一个简单的QQ聊天界面
成品图
Java用来设计GUI图形界面设计是非常方便的,
下面是代码
package demo;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class P extends JFrame {
JButton sendBt;
JTextField inputField;
JTextArea chatContent;
public P(){
this.setLayout(new BorderLayout());
chatContent =new JTextArea(12,34);
JScrollPane showPanel = new JScrollPane(chatContent);
chatContent.setEditable(false);
JPanel inputPanel = new JPanel();
inputField = new JTextField(20);
sendBt = new JButton("发送");
JMenuBar menuBar= new JMenuBar();
this.setJMenuBar(menuBar);
JMenu menu =new JMenu("管理");
menuBar.add(menu);
JMenuItem item1 = new JMenuItem("弹出窗口");
JMenuItem item2 = new JMenuItem("关闭");
sendBt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String content = inputField.getText();
if(content != null && !content.trim().equals("")){
chatContent.append("我:"+content+"\n");
}else{
chatContent.append("聊天内容不能为空"+"\n");
}
inputField.setText("");
}
});
item1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
final JDialog dialog = new JDialog(P.this,true);
dialog.setTitle("弹出窗口");
dialog.setSize(200,200);
dialog.setLocation(50,50);
dialog.setLayout(new FlowLayout());
JButton btn1 = new JButton("确定");
dialog.add(btn1);
final JLabel label = new JLabel();
dialog.add(label);
label.setText("点击确定,关闭该对话框");
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dialog.dispose();
}
});
dialog.setVisible(true);
}
});
item2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
Label label =new Label("输入");
inputPanel.add(label);
inputPanel.add(inputField);
inputPanel.add(sendBt);
this.add(showPanel,BorderLayout.CENTER);
this.add(inputPanel,BorderLayout.SOUTH);
this.setTitle("JAVA窗口");
menu.add(item1);
menu.addSeparator();
menu.add(item2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500,300);
this.setVisible(true);
}
public static void main(String[] args) {
new P();
}
}