zoukankan      html  css  js  c++  java
  • 在一个frame设置四个组件

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    
    class TouChaCol{
        JFrame frame;
        JLabel label;
        
        public static void main(String [] args){
            TouChaCol ch = new TouChaCol();
            ch.go();
        }
        
        class LabelActionListener implements ActionListener{
            public void actionPerformed(ActionEvent e){
                label.setText("fuck you click me");
            }
        }
        
        class ColorActionListener implements ActionListener{
            public void actionPerformed(ActionEvent e){
                frame.repaint();
            }
        }
        
        public void go(){
            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            Panel panel = new Panel();
            
            label = new JLabel("yoooyo helllo who are you");
            JButton button1 = new JButton("change the color");
            button1.addActionListener(new ColorActionListener());
            
            JButton button2 = new JButton("change the label");
            button2.addActionListener(new LabelActionListener());
            
            frame.getContentPane().add(BorderLayout.SOUTH,button1);
            frame.getContentPane().add(BorderLayout.EAST,button2);
            frame.getContentPane().add(BorderLayout.WEST,label);
            frame.getContentPane().add(BorderLayout.CENTER,panel);
            
            frame.setSize(700, 700);
            frame.setVisible(true);
        }
    }
    View TouChaCol
    import javax.swing.*;
    import java.awt.*;
    public class Panel 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 myColor = new Color(red,green,blue);
            g.setColor(myColor);
            g.fillOval(70,70, 100, 100);
        }
    }
    View class Panel

    在Panel(继承自JPanel)类中方法paintComponent()

    fillRect(0,0,this.width,this.height)表示在该panel的(x,y)坐标为起始,this.width和this.height也表示该面板的宽高

    需要作出改变的组件,放做全局

    在go中有代码:

    button1.addActionListener(new ColorActionListener());

    button2.addActionListener(new LabelActionListener());

    在外部类对象中新建的内部类对象会与该外部类对象产生联结,内部类对象可直接调用外部类对象的实例变量,也因此,需要改变的组件做实例变量也是为了给内部对象使用

     BoarderLayout.CENTER 这个中间是相对于其他组件而言的,当其左边的组件变小时,他可能会变大

  • 相关阅读:
    Debian常用操作
    debian-11.0.0-amd64
    CentOS-8.4.2105-x86_64
    第20章: 二进制方式部署K8S1.20高可用集群
    天狮集团云函数实践:自定义业务逻辑实现跨境电商全球直播
    峰值利用率80%+,视频云离线转码自研上云TKE实践
    腾讯首个CNCF沙箱开源项目
    斗鱼直播云原生实践之注册中心篇
    Superedge的新特性和未来之路
    腾讯云与 Grafana Labs 达成深度合作, 推出全新 Grafana 托管服务
  • 原文地址:https://www.cnblogs.com/gabygoole/p/4913844.html
Copyright © 2011-2022 走看看