GUI界面的学习

GUI

        Java GUI(图形用户界面)是使用Java编程语言创建的用户界面。Java提供了许多库和工具,可以轻松地创建各种GUI应用程序。

package com.ffyc.javagui.listener;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Demo3Frame extends JFrame {


    public Demo3Frame() throws HeadlessException {
             this.setTitle("欢迎登录");
             this.setSize(300,300);//设置宽高
             this.setLocationRelativeTo(null); //水平垂直居中
             this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时退出程序
             this.setResizable(false);//设置禁止窗口拖拽调整大小

              //创建一个面板
              JPanel jPanel = new JPanel();

              JTextField jTextField = new JTextField(15);

              JButton jButton = new JButton("登录");

               jPanel.add(jTextField);
               jPanel.add(jButton);

              //把面板添加到窗口上
              this.add(jPanel);
              this.setVisible(true);//让窗口显示  放在设置的最后一行

        //为组件添加事件处理程序
        //jButton.addActionListener(new B());
        //new 接口  创建一个匿名内部类的对象,  是为了简化语法
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获得文本框输入的内容
                 String account = jTextField.getText();
                 if(account.length()==0){
                     //消息提示框
                     //JOptionPane.showMessageDialog(null,"请输入账号!");
                     //JOptionPane.showMessageDialog(null,"请输入账号!","操作提示",JOptionPane.WARNING_MESSAGE);

                    int res =   JOptionPane.showConfirmDialog(null, "您确定要退出吗?","操作提示",JOptionPane.OK_CANCEL_OPTION);
                     System.out.println(res);// 点击确定返回0 , 点击取消返回2
                     if(res==0){
                         //执行退出操作
                     }
                     return;
                 }
                if(account.length()<6 ||account.length()>10){
                    JOptionPane.showMessageDialog(null,"请输入一个6-10位之间的账号!");
                    return;
                }

            }
        });


    }




    public static void main(String[] args) {
           new Demo3Frame();//创建一个窗口对象
    }
}

这是一个简单的聊天窗口案例,其实GUI界面是非常简单的一个内容,下面是一个聊天室实现:

import java.util.Date;

public class Chat extends JFrame {
    JTextArea jTextArea;
    public Chat(String account, Socket socket) throws IOException {
        DataOutputStream dataOutputStream=new DataOutputStream(socket.getOutputStream());

        this.setTitle("欢迎"+account+"使用");
        this.setSize(400,400);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        /*
            DO_NOTHING_ON_CLOSE
            是在点击关闭之后什么都不做
            但是如果用EXIT,则会退出程序
         */
        this.setResizable(false);

        JPanel jPanel=new JPanel(new BorderLayout());
        //历史记录文本
        jTextArea=new JTextArea();
        jTextArea.setEditable(false);
        JScrollPane jScrollPane=new JScrollPane(jTextArea);
        jPanel.add(jScrollPane);
        //发送窗口
        JPanel sendPanel=new JPanel();
        JTextArea jTextArea1=new JTextArea(3,20);
        jTextArea1.setLineWrap(true);
        JScrollPane jScrollPane1=new JScrollPane(jTextArea1);
        JButton sendButton=new JButton("发送");
        sendPanel.add(jScrollPane1);
        sendPanel.add(sendButton);
        jPanel.add(sendPanel,BorderLayout.SOUTH);
        this.add(jPanel);


        new ClientThread(socket).start();

        //为窗口添加事件监听
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                int res=JOptionPane.showConfirmDialog(null,"确定要退出聊天吗?","操作提示",JOptionPane.OK_CANCEL_OPTION);
                if(res==0){
                    //点击确定
                    new Login();
                    dispose();
                }
            }
        });

        //点击发送按钮把内容发送出去
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获得消息内容
                String msg=account+"说:"+"\t"+DateUtil.DateToString(new Date(),"yyyy-MM-dd")+"\n";
                if(jTextArea1.getText().length()==0){
                    //为空
                    JOptionPane.showConfirmDialog(null,"输入内容不能为空!请重新输入!");
                    return;
                }
                //不为空
//                System.out.println());
                msg+=jTextArea1.getText();
                try {
                    dataOutputStream.writeUTF(msg);
                    jTextArea1.setText("");
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                    JOptionPane.showMessageDialog(null,"信息发送失败,请尝试重新连接网络");
                }
            }
        });
    }

    boolean temp=true;

    class ClientThread extends Thread{
        DataInputStream dataInputStream;
        public ClientThread(Socket socket) throws IOException {
            dataInputStream=new DataInputStream(socket.getInputStream());
        }

        @Override
        public void run() {
            while(temp){
                try {
                    String msg=dataInputStream.readUTF();
                    System.out.println(msg);
                    jTextArea.append(msg+"\n");
                } catch (IOException e) {
                    e.printStackTrace();
                    temp=false;
                }
            }
        }
    }
}

import java.util.Date;

public class DateUtil {
    //让Date类型转换为日期
    public static String DateToString(Date date){
        //创立一个SDF类型的对象,通过对象调用函数转化
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String str_date=sdf.format(date);
        return str_date;
    }
    //方法重载,用户指定格式
    public static String DateToString(Date date,String p){
        SimpleDateFormat sdf=new SimpleDateFormat(p);
        String str_date=sdf.format(date);
        return str_date;
    }
    //方法重载:将当前时间格式转换为指定格式的字符串
    public static String DateToString(String p){
        SimpleDateFormat sdf=new SimpleDateFormat(p);
        String str_date=sdf.format(new Date());//直接创建一个对象
        return str_date;
    }
    //将日期转化为Date类型
    public static Date StringToDate(String str) throws Exception{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date_str=sdf.parse(str);
        return date_str;
    }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;

public class Login extends JFrame {

    public Login(){
        this.setTitle("欢迎使用");
        this.setSize(300,300);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);

        JPanel jPanel=new JPanel(new GridLayout(4,1));

        JPanel welconPanel=new JPanel();
        JLabel welcomelabel=new JLabel("登陆");
        welconPanel.add(welcomelabel);

        JPanel account=new JPanel();
        JLabel accountLabel=new JLabel("账号");
        JTextField accountField=new JTextField(15);
        account.add(accountLabel);
        account.add(accountField);

        JPanel password=new JPanel();
        JLabel passwordLabel=new JLabel("密码");
        JPasswordField passwordField=new JPasswordField(15);
        password.add(passwordLabel);
        password.add(passwordField);

        JPanel button=new JPanel();
        JButton loginButton=new JButton("登录");
        JButton regButton=new JButton("注册");
        button.add(loginButton);
        button.add(regButton);

        jPanel.add(welconPanel);
        jPanel.add(account);
        jPanel.add(password);
        jPanel.add(button);

        this.add(jPanel);
        this.setVisible(true);

        //监听事件
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String account=accountField.getText();
                String password=new String(passwordField.getPassword());
                if(account.length()==0){
                    JOptionPane.showMessageDialog(null,"账号不能为空");
                }
                if(password.length()==0){
                    JOptionPane.showMessageDialog(null,"密码不能为空");
                }

                try {
                    Socket socket=new Socket("127.0.0.1",9999);
                    new Chat(account,socket).setVisible(true);
                    dispose();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    JOptionPane.showMessageDialog(null,"当前服务器忙,请稍后再试!");
                }

            }
        });

    }

}

public class Start {
    public static void main(String[] args) {
        new Login();
        // Chat();
    }
}

import java.util.ArrayList;

public class Server extends JFrame {
    //存放所有连接到服务器的Socket集合
    ArrayList<Socket> sockets=new ArrayList<>();
    JTextArea jTextArea;

    public Server(){
        this.setTitle("监控");
        this.setSize(300,300);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);

        JPanel jPanel=new JPanel(new BorderLayout());
        //历史记录文本
        jTextArea=new JTextArea();
        jTextArea.setEditable(false);
        JScrollPane jScrollPane=new JScrollPane(jTextArea);
        jPanel.add(jScrollPane);
        //发送窗口
        JPanel sendPanel=new JPanel();
        JTextArea jTextArea1=new JTextArea(3,20);
        jTextArea1.setLineWrap(true);
        JScrollPane jScrollPane1=new JScrollPane(jTextArea1);
        JButton sendButton=new JButton("发送");
        sendPanel.add(jScrollPane1);
        sendPanel.add(sendButton);
        jPanel.add(sendPanel,BorderLayout.SOUTH);
        this.add(jPanel);
    }

    public void serverStart(){
        try {
            //启动服务
            ServerSocket serverSocket=new ServerSocket(9999);
            //监听多个客户端的的连接
            while(true){
                Socket socket=serverSocket.accept();
                sockets.add(socket);
                System.out.println("有服务器连接成功!当前数量为:"+sockets.size());

                new socketThread(socket).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务器启动失败");
        }
    }

    //写一个内部类,用来监听各自客户端有没有发送消息
    class socketThread extends Thread{
        DataInputStream dataInputStream;
        Socket socket;
        public socketThread(Socket socket) throws IOException {
            this.socket=socket;
            this.dataInputStream=new DataInputStream(socket.getInputStream());
        }

        @Override
        public void run() {
            //接受客户端的消息
            try {
               while (true){
                   String msg=dataInputStream.readUTF();
                   System.out.println(msg);
                   //传回信息
                   for(Socket sock:sockets){
                       DataOutputStream dataOutputStream=new DataOutputStream(sock.getOutputStream());
                       dataOutputStream.writeUTF(msg);
                   }
               }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("客户端异常!请检查客户端连接!");
                sockets.remove(socket);
            }
        }
    }
}

public class ServerStart {
    public static void main(String[] args) {
        new Server().serverStart();
    }
}

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java写GUI图形界面 public class login extends JFrame { private JComboBox nameJComboBox; private JPanel userJPanel; private JLabel pictureJLabel; private JButton okJButton,cancelJButton; private JLabel nameJLabel,passwordJLabel,note; private JPasswordField passwordJPasswordField; private String name1; private String password1; private String user; private ImageIcon myImageIcon; public login( ) { createUserInterface(); // 调用创建用户界面方法 } private void createUserInterface() { Container contentPane = getContentPane(); contentPane.setLayout( null ); userJPanel = new JPanel(); userJPanel.setBounds( 35, 120, 300, 96 ); userJPanel.setBorder(BorderFactory.createEtchedBorder() ); //显示一圈边儿 userJPanel.setLayout( null ); contentPane.add( userJPanel ); nameJComboBox = new JComboBox(); nameJComboBox.setBounds( 100, 12, 170, 25 ); nameJComboBox.addItem( "admin" ); nameJComboBox.addItem( "aloie" ); nameJComboBox.setSelectedIndex( 0 ); nameJComboBox.setEditable(true); userJPanel.add( nameJComboBox ); pictureJLabel=new JLabel(); pictureJLabel.setBounds(45,0,380,118); pictureJLabel.setIcon(new ImageIcon("pic.gif")); contentPane.add(pictureJLabel); nameJLabel=new JLabel("姓 名:"); nameJLabel.setBounds(20,12,80,25); userJPanel.add(nameJLabel); passwordJPasswordField=new JPasswordField(); passwordJPasswordField.setBounds(100,60,170,25); userJPanel.add(passwordJPasswordField); passwordJLabel=new JLabel("密 码:"); passwordJLabel.setBounds(20,60,80,25); userJPanel.add(passwordJLabel); note=new JLabel("密码与用户名相同"); note.setBounds(0,295,180,25); add(note); okJButton=new JButton("登 陆"); okJButton.setBounds(60,250,80,25); contentPane.add(okJButton); okJButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { okJButtonActionPerformed(event); } } ); cancelJButton=new JButton("取 消"); cancelJButton.setBounds(210,250,80,25); contentPane.add(cancelJButton); cancelJButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { System.exit(0); //退出登陆 } } ); setTitle( "登陆窗口" ); setSize( 380, 350 ); setResizable( false ); //将最大化按钮设置为不可用 } private void okJButtonActionPerformed( ActionEvent event ) { //okJButton响应事件,检查用户名和密码的匹配 name1= nameJComboBox.getSelectedItem().toString(); if (name1.equals("admin") ) { if (passwordJPasswordField.getText().equals("admin")) { showNewWindow(); setVisible( false); } else { JOptionPane.showMessageDialog( this,"密码错误,拒绝登陆", "密码错误 !", JOptionPane.ERROR_MESSAGE ); } } else if (name1.equals("aloie")) { if ( passwordJPasswordField.getText().equals("aloie") ) { showNewWindow(); setVisible(false); } else { JOptionPane.showMessageDialog( this,"密码错误,拒绝登陆", "密码错误 !", JOptionPane.ERROR_MESSAGE ); } } } public void showNewWindow() { JFrame jf=new JFrame("main Frame"); jf.setSize(500,400); jf.setVisible(true); jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } public static void main( String[] args ) { JFrame.setDefaultLookAndFeelDecorated(true); login mylogin = new login( ); mylogin.setVisible( true ); mylogin.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值