黑马程序员_Java基础_GUI图形界面入门

  一, GUI Graphical User Interface )图形用户接口

Java中为GUI提供的对象都存储在java.Awtjavax.Swing两个包中。

java.AwtAbstract Window ToolKit(抽象窗口工具包),需要调用本地系统方法实现功能,属于重量级控件。

 

javax.Swing:在AWT的基础上,建立的一套图形界面系统,其中提供了更多的组件,而且完全由java实现。增强了移植性,属于轻量级控件。

 

Awt继承关系图:


二,常见组件的布局管理器

布局:容器中组件的排列方式,就是布局。

常见的布局管理器:

1FlowLayout(流式布局管理器)

从左到右的顺序排列,Panel的默认布局管理器。

(2)BorderLayout(边界布局管理器)

东,南,西,北,中,Frame默认的布局管理器。

(3)GridLayout(卡片布局管理器)

规则的矩形。

(4)CardLayout(卡片布局管理器)

选项卡。

(5)GridBagLayout(网格包布局管理器)

非规则的矩形。

 

三,图形用户界面的创建步骤

1,创建Frame窗体;

2,对窗体进行基本设置

比如:大小,位置,布局

3,定义组件,

4,通过add方法将组建添加到窗体

5,让窗体显示,setVisible(true)

 

四,事件监听机制

流程图:


事件监听机制的特点:

    1,事件源

    2,事件

    3,事件监听器

    4,事件处理

 

事件源:Awt或者Swing当中的图形用户界面;

事件:每一个事件源都有自己特有的对应事件或共性事件;

事件监听器:将可以出发某一个事件(不止一个事件)的动作都封装在了监听器中

 

以上三者在Java中都已经定义好了,直接获取对象就可以了,我们要做到的就是要对产生的动作进行处理。

 

需求一:创建一个窗体,向窗体中添加一个按钮,点击关闭时,能够关闭窗体。


import java.awt.*;
import java.awt.event.*;
public class AwtDemo
{
    public static void main(String[] args) {
        Frame myF = new Frame("窗体");//定义窗体Frame,构造函数的标题是窗体名称
        myF.setSize(500,400);//设置窗体大小
        myF.setLocation(400,300);//设置窗体的位置
        Button b = new Button("按钮");//创建按钮
        myF.add(b);//将按钮添加到窗体中
        myF.setLayout(new FlowLayout());//设置按钮布局,流式布局
        //myF.addWindowListener(new myLis());//想窗体中添加关闭窗体事件
        //也可以创建一个匿名内部类;
        myF.addWindowListener(new WindowAdapter() {
            //最常用的就是关闭窗体;
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭窗口" + e.toString());//事件对象所处的事件状态信息;
                System.exit(0);
            }
            public void windowActivated(WindowEvent e) {//窗体前置
                System.out.println("激活。。。");
            }
            public void windowOpened(WindowEvent e) { //窗体创建成功显示出来时执行
                System.out.println("窗口开启。。。。");
            }
        });
        myF.setVisible(true);//让窗体显示出来;
        System.out.println("hello world");
    }
}
//Frame的父类Window类中addWindowListener(WindowListener l)向窗体中添加对窗体操作的七个事件,因为其
//是一个接口,这里面有七个抽象方法,我们必须都实现才行,但是都实现的话,有些功能不是我们想要的,所以
//它的子类就提供了我们想要的方法,该类是windowAdapter,他是一个抽象类,但是类中的七个方法来自父类window
//接口中的方法,但是都有方法体,方法体是空的,为什么有方法体还定义成抽象方法呢,原因是为了避免用户定义该类
//的对象。
class myLis extends WindowAdapter
{
    public void windowClosing(WindowEvent e) {
        System.out.println("closeing ...");
        System.exit(0);
    }
}

需求二:在需求一的基础上,实现点击按钮也能关闭窗体。(添加鼠标事件)


import java.awt.*;
import java.awt.event.*;
public class FrameDemo
{
    private Frame f;
    private Button but;
    public FrameDemo() {
        init();
    }
    public void init() {
        f = new Frame("我的窗体");
        //设置组件大小;
        f.setBounds(400,200,300,200);
        f.setLayout(new FlowLayout());//设置窗体位置和大小
        but = new Button("我的按钮");
        f.add(but);
        
        //加载窗体上的事件
        event();
        
        f.setVisible(true);
    }
    
    //将事件和窗体分开;
    public void event() {
        f.addWindowListener (new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭窗口。。。");
                System.exit(0);
            }
        });
        /*给这个窗体添加一个按钮,让按钮具备退出程序的功能;
        按钮就是事件源,将事件注册到按钮上,选择哪一个监听器呢?
        通过关闭窗体示例了解到,想要知道哪个组件具有什么样的事件监听器,需要查看组件对象的功能。
            查阅Button类发现他有一个事件监听器:addActionListener(ActionListener l) 
        */
        but.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("按钮关闭窗口。。。");
                System.exit(0);
            }
        });
        //在按钮上添加鼠标事件;
        but.addMouseListener(new MouseAdapter() {
            int count = 1;
            public void mouseReleased(MouseEvent e) {
                System.out.println("鼠标进入" + count++);
            }
        });
    }
    public static void main(String[] args) {
        FrameDemo f = new FrameDemo();
    }
}

需求三:键盘事件监听器的使用;向按钮上添加键盘监听器。


import java.awt.*;
import java.awt.event.*;
public class FrameKeyDemo
{
    private Frame f;
    private Button b;
    private TextField tf;
    FrameKeyDemo() {
        zuiF();
    }
    public void zuiF() {
        f = new Frame("我的窗体");
        f.setBounds(300,200,400,300);
        f.setLayout(new FlowLayout());
        tf = new TextField(20);//创建文本框,传入要设置的大小
        
        b = new Button("我的按钮");
        f.add(tf);
        f.add(b);
        myEvent();
        f.setVisible(true);
    }
    public void myEvent() {
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        b.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                //if(e.getKeyCode() == KeyEvent.VK_ENTER )
                    //System.exit(0);
                    //int code = e.getKeyCode();
                    if(e.getKeyCode()==KeyEvent.VK_ENTER && e.isControlDown())
                        System.out.println("Ctrl and Enter is run...");
            }
        });
        tf.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e)
            {
                int code = e.getKeyCode();
                if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9))
                {
                    System.out.println(code+".....是非法的");
                    e.consume();//让非法的字符不在文本框中显示;
                }
            }
        });
    }
    public static void main(String[] args) {
        FrameKeyDemo f = new FrameKeyDemo();
    }
}

需求四:在按钮上添加鼠标双击事件,每次鼠标双击都产生事件,并记录次数。


import java.awt.*;
import java.awt.event.*;
public class FrameDemo2
{
    private Frame f;
    private Button but;
    public FrameDemo2() {
        init();
    }
    public void init() {
        f = new Frame("我的窗体");
        //设置组件大小;
        f.setBounds(400,200,300,200);
        f.setLayout(new FlowLayout());//设置窗体位置和大小
        but = new Button("我的按钮");
        f.add(but);
        
        //加载窗体上的事件
        event();
        
        f.setVisible(true);
    }
    
    //将事件和窗体分开;
    public void event() {
        f.addWindowListener (new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭窗口。。。");
                System.exit(0);
            }
        });
        //添加按钮组件动作事件,只要在按钮上发生操作就会触发事件,包括键盘或鼠标
        but.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent em) {
                System.out.println("action....");
            }
        });
        //在按钮上添加鼠标事件;
        but.addMouseListener(new MouseAdapter() {
            int count = 1;
            int countC = 1;
            //添加鼠标进入事件
            public void mouseEntered(MouseEvent e) {
                System.out.println("鼠标进入" + count++);
            }
            //添加鼠标单击事件
            public void mouseClicked(MouseEvent e) {
                //让鼠标双击时才触发事件
                if(e.getClickCount() == 2) {
                    System.out.println("鼠标双击" + countC++);
                }
                //System.out.println("鼠标单击" + countC++);
            }
        });
    }
    public static void main(String[] args) {
        FrameDemo2 f = new FrameDemo2();
    }
}

需求五:菜单条的创建,实现一个简易的记事本程序。


import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MenuDemo
{
    private Frame frame;
    private Menu fileMenu,helpMenu;
    private MenuBar menuBar;
    private MenuItem closeItem,openItem,saveItem;
    private TextArea textArea;
    private FileDialog openDia,saveDia;
    private File fl;
    public MenuDemo() {
        Init3();
    }
    public void Init3() {
        frame = new Frame("菜单选项");
        frame.setBounds(200,120,700,520);
        //frame.setLayout(new FlowLayout());不设置布局,则默认布局是边界布局
        menuBar = new MenuBar();//添加菜单条,菜单条中可以添加菜单
        fileMenu = new Menu("文件");
        helpMenu = new Menu("帮助");
        //subMenu = new Menu("子菜单");//在菜单中添加菜单,将会是一个有箭头的选项
        closeItem = new MenuItem("退出");//将退出项添加到文件菜单中
        openItem = new MenuItem("打开");
        saveItem = new MenuItem("保存");
        textArea = new TextArea();
        frame.add(textArea);
        openDia = new FileDialog(frame,"打开",FileDialog.LOAD);
        saveDia = new FileDialog(frame,"保存",FileDialog.SAVE);
        //将菜单添加到菜单条上
        menuBar.add(fileMenu);
        menuBar.add(helpMenu);
        //将子菜单,子条目,退出添加到菜单上
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(closeItem);
        //将子菜单条目添加到子菜单上
        //subMenu.add(tiaoMu);
        
        
        frame.setMenuBar(menuBar);
        event();
        frame.setVisible(true);
    }
    public void event() {
        saveItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(fl == null) {
                    saveDia.setVisible(true);
                    String dirPath = saveDia.getDirectory();
                    String fileName = saveDia.getFile();
                    if(dirPath == null || fileName == null)//如果路径或文件名为空,返回
                        return ;
                    fl = new File(dirPath,fileName);
                }
                
                try
                {
                    BufferedWriter fw = new BufferedWriter(new FileWriter(fl));
                    String str = textArea.getText();
                    fw.write(str);
                    fw.flush();
                    fw.close();
                }
                catch (IOException ex)
                {
                    throw new RuntimeException("存取失败");
                }
            }
        });
        
        //菜单打开按钮事件
        openItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                openDia.setVisible(true);//显示系统文件加载窗体
                String dirPath = openDia.getDirectory();
                String fileName = openDia.getFile();
                //System.out.println(dirPath + "---" + fileName);
                if(dirPath == null || fileName == null)//如果路径或文件名为空,返回
                    return;
                textArea.setText("");
                fl = new File(dirPath,fileName);
                try
                {
                    BufferedReader bufR = new BufferedReader(new FileReader(fl));
                    String line = null;
                    while ((line=bufR.readLine())!=null)
                    {
                        textArea.append(line + "\r\n");
                        //System.out.println(line);
                    }
                    bufR.close();
                }
                catch (IOException ex)
                {
                    throw new RuntimeException("打开失败");
                }
            }
        });
        
        //点击菜单栏的退出时,退出窗体
        closeItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        
        //关闭窗口事件
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    public static void main(String[] args) {
        new MenuDemo();
    }
}

需求六:定义一个文本框和一个文本域和按钮,文本框获取磁盘路径,在文本域中显示磁盘下的目录。


import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class WindowTest
{
    private Frame f;
    private Button b;
    private TextField tf;
    private TextArea ta;
    private Dialog d;
    private Label l;
    private Button okB;
    WindowTest() {
        init();
    }
    public void init() {
        f = new Frame("My Frame");
        f.setBounds(300,100,600,500);
        f.setLayout(new FlowLayout());
        tf = new TextField(60);
        b = new Button("转到");
        ta = new TextArea(20,70);
        d = new Dialog(f,"错误提示信息",true);
        d.setBounds(450,240,240,120);
        d.setLayout(new FlowLayout());
        l = new Label();
        okB = new Button("确定");
        d.add(l);
        d.add(okB);
        //流式布局要注意顺序;
        f.add(tf);
        f.add(b);
        f.add(ta);
        myEve();
        f.setVisible(true);
    }
    private void myEve() {
        //当按回车键时,和按转到按钮效果一样
        tf.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_ENTER)
                {
                    showEvent();
                }
            }
        });
        //关闭错误提示窗体
        d.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                d.setVisible(false);
            }
        });
        //确定按钮,鼠标点击关闭错误提示框(原理是隐藏该窗体)
        okB.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                d.setVisible(false);
            }
        });
        //键盘按Enter键关闭错误提示窗
        okB.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_ENTER)
                {
                    d.setVisible(false);
                }
            }
        });
        //关闭整个容器并退出
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        
        tf.addKeyListener(new KeyAdapter() {
            public void addKeyPressed(KeyEvent e) {
            }
        });
        //转到按钮显示目录内容
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                showEvent();
            }
        });
    }
    private void showEvent() {
        String tdir = tf.getText();
            //System.out.println(text);
            //ta.setText(text);
            //将文本转到文本域之后,让文本框中的文本消失
            //tf.setText("");
        File f = new File(tdir);
        if (f.exists() && f.isDirectory())
            {
                ta.setText("");
                String[] s = f.list();
                for(String name: s) {
                    ta.append(name + "\r\n");
                }
            }
            else {
                l.setText("输入的路径:" + tdir + "不存在,请重试");
                d.setVisible(true);
            }
    }
    public static void main(String[] args) {
        new WindowTest();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值