HeadFirstJava 12 图形用户接口

来源:互联网 发布:node.js高级编程 微盘 编辑:程序博客网 时间:2024/06/04 23:36

12.1创建

package Learn;import javax.swing.*;//别忘了这个包public class SimpleGuil {    public static void main(String[] args) {        // TODO Auto-generated method stub        JFrame frame = new JFrame();        JButton button = new JButton("Click me");        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//这一行会在Windows关闭时把程序结束掉        frame.getContentPane().add(button);        //frame.getContentPane().add(BorderLayout.SOUTH,button);两个参数可以指定按钮的位置        frame.setSize(300, 300);        frame.setVisible(true);//把frame显示出来    }}

12.2监听的事件源如何沟通

package Learn;import javax.swing.*;import java.awt.event.*;//import进Actioner和ActionEvent所在的包public class SimpleGuiB implements ActionListener{//实现此接口,这表示SimpleGUIB是个ActionListener    JButton button;    public static void main(String[] args) {        // TODO Auto-generated method stub        SimpleGuiB gui = new SimpleGuiB();        gui.go();    }    private void go() {        // TODO Auto-generated method stub        JFrame frame = new JFrame();        button = new JButton("Click me");        button.addActionListener(this);//向按钮注册        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.getContentPane().add(button);        frame.setSize(300, 300);        frame.setVisible(true);    }    @Override    public void actionPerformed(ActionEvent e) {//实现interface的方法,这是真正的处理时间的方法        // TODO Auto-generated method stub        button.setText("I've been click");    }}

12.3在GUI上面加东西的3种方法

  • 在frame上放置widget
    加上按钮,窗体,radio button等
    frame.getContentPane().add(myButton);
    javax.swing这个包上面有超过一打的widget类型
  • 在widget上绘制2D图形
    使用graphics.fillOval(70,70,100,100);
  • 在widget上绘制JPEG图
    把图形画在widget上。
    graphics.drawImage(myPic,10,10,this);

12.4内部类

  • 内部类可以使用外部类的所有方法和变量。
  • 使用外部类以外的程序代码来初始内部实例。
class foo{    public static void main(String[] args){        MyOuter outerObj = new My Outer();        MyOuter.MyInner innerObj = outerObj.new MyInner();        }}

12.5利用内部类实现两个按钮的程序

12.6以内部类执行动画效果

  • 在特定坐标点绘制对象
g.fillOval(20,50,100,100);
  • 在不同的坐标点重新绘制对象
  • 在对象尚未到达终点前重复上列的步骤
原创粉丝点击