java--------学习之《GUI 图形化界面》

       ------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------



GUI(图形化界面)

 

GUI继承关系图:

 

 



GUI(Frame):带有标题和边框的顶层窗口

 

创建图形化界面的几个基本操作:

1创建Frame窗体

2对窗体进行基本设计(比如,大小,位置,布局)

3定义组件

4将组件通过窗体的add方法添加到窗体中

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

 

代码演示:

import java.awt.*;
class Yanshi
{
    public static void main(String[] args)
    {
        //构造一个最初不可见的窗体新实例对象//他创建时有一个默认的布局方式:边界布局
        Framef = newFrame("my awt");
        //setSize方法定义窗体的横坐标和纵坐标的长度
        f.setSize(500,400);
        //setLocation方法定义窗体在屏幕上出现的位置
        f.setLocation(300,200);
        //窗体对象调用setLayout方法定义流式布局“在参数列表里传入需要定义的布局匿名对象"
        f.setLayout(new FlowLayout());
        //创建一个按钮对象
        Buttonb = newButton("我是一个按钮");
        //窗体对象调用add方法将按钮对象添加进来
        f.add(b);
       
        //实例对象调用setVisible方法(根据参数列表里真或假来决定隐藏或显示窗体)
        f.setVisible(true);
    }
}


 

 

GUI(事件监听机制)

特点:

    1事件源

    2事件

3监听器

4事件处理

事件源:   就是awt包或者swing包中的那些图形界面组件。

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

监听器:   将可以触发某一个事件的动作(不止一个动作)都已经封装到了监听器中。

以上三者,在java中都已经定义好了。直接获取其对象来用就可以了。

 

我们要做的事情:对产生的动作进行处理

 

代码演示:

import java.awt.*;
import java.awt.event.*;
class Yanshi
{
    public static void main(String[] args)
    {
        //构造一个最初不可见的窗体新实例对象//他创建时有一个默认的布局方式:边界布局
        Framef = newFrame("my awt");
        //setSize方法定义窗体的横坐标和纵坐标的长度
        f.setSize(500,400);
        //setLocation方法定义窗体在屏幕上出现的位置
        f.setLocation(300,200);
        //窗体对象调用setLayout方法定义流式布局“在参数列表里传入需要定义的布局匿名对象"
        f.setLayout(new FlowLayout());
        //创建一个按钮对象
        Buttonb = newButton("我是一个按钮");
        //窗体对象调用add方法将按钮对象添加进来
        f.add(b);
        //添加指定的窗口状态监听器,以从此窗口接收窗口事件
        f.addWindowListener(new WindowAdapter()
        {
            public voidwindowClosing(WindowEvent e)
            {
                System.out.println("我关");
                System.exit(0);
            }
            public voidwindowActivated(WindowEvent e)
            {
                System.out.println("我活了,哈哈哈哈");
            }
            public voidwindowOpened(WindowEvent e)
            {
                System.out.println("我被打开了,哈哈哈");
            }          
        });
        //实例对象调用setVisible方法(根据参数列表里真或假来决定隐藏或显示窗体)
        f.setVisible(true);
       
        //System.out.println("hello world");
    }
}
 
 
//因为WindowListener的子类WindowAdapter已经实现了WindowListener接口。
//并覆盖了其中的所有方法,那么我只要继承自WindowAdapter覆盖我需要的方法即可
//在方法里面定义要运行的内容
 
//也可以直接写匿名内部类
class MyWin extends WindowAdapter
{
    public voidwindowClosing(WindowEvent e)
    {
        System.exit(0);
        //System.out.println("windowclosing---"+e.toString());
    }
}


 

 

GUI(Action事件)

代码演示:

import java.awt.*;
import java.awt.event.*;
class Yanshi
{
    public static void main(String[] args)
    {
        new FrameDemo();
    }
}
 
class FrameDemo
{
    //定义该图形中所需的组件的引用
    private Frame f;
    private Button but;
   
    FrameDemo()
    {
        init();
    }
    public void init()
    {
        f = new Frame("myframe");
        //对frame基本设置
        //setbounds方法可以一次性设置窗口大小和出现位置
        f.setBounds(300,100,600,500);
        //定窗体的布局模式
        f.setLayout(new FlowLayout());
       
        but = new Button("我是按摩扭");
        //将组建添加到fame中
        f.add(but);
        //加载一下窗体上的事件
        myEvent();
        //让窗体显示
        f.setVisible(true);
    }
    private void myEvent()
    {
        //给窗体加入事件,并传入具体监听对象
        f.addWindowListener(new WindowAdapter()
        {
            public voidwindowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
        //定义一个按钮它能具备退出程序的功能
        /*
        按钮就是事件源。
        那么选择哪一个监听器呢?
        通过关闭窗体事件了解到想要知道哪个组件具备什么样的特有监听器
        需要查看该组件对象的功能。
        */
        but.addActionListener(new ActionListener()
        {
            public voidactionPerformed(ActionEvent e)
            {
                System.out.println("退出,按钮搞定");
                System.exit(0);
            }
        });
    }
}


 

鼠标 事件

代码演示:

import java.awt.*;
import java.awt.event.*;
 
class Yanshi
{
    public static void main(String[] args)
    {
        new Yanshi();
    }
    private Frame f;
    private Button but;
   
    Yanshi()
    {
        init();
    }
   
    public void init()
    {
        f = new Frame("my fame");
        f.setBounds(300,10,600,500);
        f.setLayout(new FlowLayout());
       
        but = new Button("my button");
       
        f.add(but);
       
        myEvent();
        f.setVisible(true);
    }
    private void myEvent()
    {
        f.addWindowListener(new WindowAdapter()
        {
            public voidwindowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
       
        but.addActionListener(new ActionListener()
        {
            public voidactionPerformed(ActionEvent e)
            {
                System.out.println("action ok");
            }
        });
        //给but添加一个鼠标监听
        but.addMouseListener(new MouseAdapter()
        {
            private int count = 1;
            private int clickCount = 1;
            public void mouseEntered(MouseEvente)
            {
                System.out.println("鼠标进入该组件"+count++);
            }
            public void mouseClicked(MouseEvente)
            {
                if(e.getClickCount()==2)
                        System.out.println("双击动作"+clickCount++);
            }
        });
    }
}


 

 

键盘 事件

代码演示:

import java.awt.*;
import java.awt.event.*;
 
class Yanshi
{
    public static void main(String[] args)
    {
        new Yanshi();
    }
    private Frame f;
    private Button but;
    private TextField tf;
   
    Yanshi()
    {
        init();
    }
   
    public void init()
    {
        f = new Frame("my fame");
        f.setBounds(300,10,600,500);
        f.setLayout(new FlowLayout());
        //这是创建一个文本框对象,可以直接在里边设置列数
        tf = new TextField(20);
       
       
        but = new Button("my button");
       
        //将文本框对象添加到窗体里边
        f.add(tf);
        f.add(but);
       
        myEvent();
        f.setVisible(true);
    }
    private void myEvent()
    {
        f.addWindowListener(new WindowAdapter()
        {
            public voidwindowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
       
        //给but添加一个键盘监听
        but.addKeyListener(new KeyAdapter()
        {
            public void keyPressed(KeyEvent e)
            {
                //组合键的演示
                if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER)
                System.out.println("run ctrl + enter");
                    //System.exit(0);
                //System.out.println("ctrl+enter isrun");
                //System.out.println(KeyEvent.getKeyText(e.getKeyCode())+".."+e.getKeyCode());
            }
        });
           
        //限定文本框里边能输入的内容,文本框成了事件源,给文本框对象添加监听器(键盘监听)
        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();
                }
            }
           
        });
       
    }
}


   

 

演示打开文件,保存文件

代码演示:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Yanshi
{
    private Frame f;
    private MenuBar bar;
    private TextArea ta;
    private Menu fileMenu;
    private MenuItem closeItem,saveItem,openItem;
   
    private FileDialog openDia,saveDia;
   
    private File file;
    Yanshi()
    {
        init();
    }
    public void init()
    {
        f = new Frame("my window");
        f.setBounds(300,100,650,600);
 
        bar = new MenuBar();
       
        ta = new TextArea();
       
        fileMenu = new Menu("文件");
       
        openItem = new MenuItem("打开");
        saveItem = new MenuItem("保存");
        closeItem = new MenuItem("退出");
       
 
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(closeItem);
        bar.add(fileMenu);;
               
        f.setMenuBar(bar);
       
        openDia = new FileDialog(f,"我要打开",FileDialog.LOAD);
        saveDia = new FileDialog(f,"我要保存",FileDialog.SAVE);
       
        f.add(ta);
        f.setVisible(true);
       
        myEvent();
    }
   
    private void myEvent()
    {
        saveItem.addActionListener(new ActionListener()
        {
            public voidactionPerformed(ActionEvent e)
            {
                if(file==null)
                {
                    saveDia.setVisible(true);
                    StringdirPath = saveDia.getDirectory();
                    StringfileName = saveDia.getFile();
                    if(dirPath==null || fileName==null)
                        return;
                   
                    file = new File(dirPath,fileName);
                }
                try
                {
                    BufferedWriterbufw = newBufferedWriter(newFileWriter(file));
                   
                    Stringtext = ta.getText();
                    bufw.write(text);
                    bufw.close();
                }
                catch(IOException ex)
                {
                    throw new RuntimeException();
                }
            }
        });
        openItem.addActionListener(new ActionListener()
        {
            public voidactionPerformed(ActionEvent e)
            {
                openDia.setVisible(true);
                StringdirPath = openDia.getDirectory();
                StringfileName = openDia.getFile();
                //System.out.println(dirPath+"..."+fileName);
                if(dirPath==null || fileName==null)
                    return;
               
                ta.setText("");
                file = new File(dirPath,fileName);
               
                try
                {
                    BufferedReaderbufr =
                            new BufferedReader(new FileReader(file));
                    Stringline = null;
                    while((line=bufr.readLine())!=null)
                    {
                        ta.append(line+"\r\n");
                    }
                    bufr.close();
                }
                catch(IOException ex)
                {
                    throw new RuntimeException("读取失败");
                }
            }
        });
       
       
       
        closeItem.addActionListener(new ActionListener()
        {
            public voidactionPerformed(ActionEvent e)
            {
                System.exit(0);
            }
        });
       
        f.addWindowListener(new WindowAdapter()
        {
            public voidwindowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
   
    }
   
   
    public static void main(String[] args)
    {
        new Yanshi();
    }
}
以上代码已经实现了一个类似于简易的文字编辑器。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
javaGUI图形界面 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、付费专栏及课程。

余额充值