GUI——简单组件

示例

完成了 两个监听事件
(利用内部类创造了两个对象,同时可以访问内部的事情)

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GUI {
    JFrame frame;
    JLabel label;

    public static void main(String[] args){
        GUI gui=new GUI();
        gui.go();
    }
    public void go(){
        frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton labelbutton=new JButton("change label");
        labelbutton.addActionListener(new LabelListener());

        JButton colorbutton=new JButton("change circle");
        colorbutton.addActionListener(new ColorListener());

        label=new JLabel(" I'm a label");
        MyDrawPanel drawPanel=new MyDrawPanel();

        frame.getContentPane().add(BorderLayout.SOUTH,colorbutton);
        frame.getContentPane().add(BorderLayout.CENTER,drawPanel);
        frame.getContentPane().add(BorderLayout.EAST,labelbutton);
        frame.getContentPane().add(BorderLayout.WEST,label);

        frame.setSize(300,300);
        frame.setVisible(true);

    }


    class ColorListener implements ActionListener{
        //实现方法
        public void actionPerformed(ActionEvent event){
            frame.repaint();
        }
    }

    class LabelListener implements ActionListener{
        //实现方法
        public void actionPerformed(ActionEvent event){
            label.setText("Ouch!");
        }
    }
}

class MyDrawPanel extends JPanel{
    public void paintComponent(Graphics g){
        g.fillRect(0,0,this.getWidth(),this.getHeight());

        int red=(int)(Math.random()*255);
        int green=(int)(Math.random()*255);
        int blue=(int)(Math.random()*255);

        Color randomColor=new Color(red,green,blue);
        g.setColor(randomColor);
        g.fillOval(70,70,100,100);
    }
}


猜你喜欢

转载自blog.csdn.net/m0_46243503/article/details/107612912