美文网首页
图形用户接口(GUI)

图形用户接口(GUI)

作者: sortinnauto | 来源:发表于2018-03-06 23:46 被阅读0次

创建GUI很简单,大体分为4步:

  1. 创建frame
  JFrame frame = new JFrame();
  1. 创建widget
  //widget已button为例
  JButton button = new JButton("click me");
  1. 将widget加到frame上
  //组件其实不会直接加到frame上,如果将frame想象成window的框,
  //那么其实组件是加到了window的pane上的。
  frame.getContentPane().add(button);
  1. 将整个页面显示出来
  frame.setSize(500, 500);
  frame.setVisible(true);

Swing有很多组件可以使用,它们都在javax.swing这个包中。最常使用的组件有:JButtonJRadioButtonJCheckBoxJLabelJListJScollPaneJSliderJTextAreaJTextFieldJTable等。

第一个GUI

package com.gui;

import javax.swing.*;

public class firstGui{
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JButton button = new JButton("点击我");

        //下面这一行程序会在窗口关闭时终止程序
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setContentPane(button);

        frame.setSize(600, 300);

        frame.setVisible(true);

    }
}

这样获取的按钮没有功能,是个名副其实的样子货。但是我们平常使用的软件几乎每个按钮都有相对应的功能,都可以响应我们的点击。我当然不想让我的按钮成为摆设,那我应该怎么做呢?
也就是说:如何让按钮在用户按下时执行特定的工作呢?

  • 我需要知道按钮被按下时要执行的方法;
  • 我需要检测什么时候按钮被按下了,也就是说,我需要一个检测按钮被按下的方法。

如果想要知道按钮的事件,就要监听事件的接口。
监听接口是介于监听与事件源之间的桥梁。
每个事件类型都有相对应的监听者接口。比如想要接受MouseEvent的话就实现MouseEvent这个接口。想要接受ActionEvent,就实现ActionEvent这个接口。
这里要强调接口的规则:实现接口就得先声明这件事,也就是说必须把接口中提供的所有方法都实现出来。

取得按钮的ActionEvent

  • 实现ActionListener这个接口
  • 向按钮注册(button.addActionListener())
  • 实现事件处理的方法
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Button2 implements ActionListener {
    JButton button = new JButton("click me");

    public static void main(String[] args) {
        Button2 button2 = new Button2();
        button2.go();
    }

    private void go() {
        JFrame frame = new JFrame();
        frame.getContentPane().add(button);
        button.addActionListener(this);  //向按钮注册
        frame.setSize(600, 600);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        button.setText("you've clicked me");
    }
}

相关文章

网友评论

      本文标题:图形用户接口(GUI)

      本文链接:https://www.haomeiwen.com/subject/utsdfftx.html