图形用户接口(GUI)

2018-03-06  本文已影响0人  sortinnauto

创建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

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");
    }
}

上一篇 下一篇

猜你喜欢

热点阅读