[Java] [Class and Object] Simple application of internal classes

In the graphical user interface, set three buttons to set the background color to red, green, and blue respectively.

Insert picture description here

Myframe:

package com.itheima;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame extends JFrame{
    
    
    JButton RedButton,GreenButton,BlueButton;
    ColorAction colorAction;
    public MyFrame() {
    
    
        init();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    void init(){
    
    
        setLayout(new FlowLayout());
        RedButton = new JButton("红色");
        GreenButton = new JButton("绿色");
        BlueButton = new JButton("蓝色");
        add(RedButton);
        add(GreenButton);
        add(BlueButton);
        colorAction = new ColorAction();
        RedButton.addActionListener(colorAction);
        GreenButton.addActionListener(colorAction);
        BlueButton.addActionListener(colorAction);



    }
    private class ColorAction implements ActionListener{
    
    
        @Override
        public void actionPerformed(ActionEvent e) {
    
    
            Container contentPane = getContentPane();
            if(e.getSource() == RedButton){
    
    
                contentPane.setBackground(Color.RED);
            }
            if(e.getSource() == GreenButton){
    
    
                contentPane.setBackground(Color.GREEN);
            }
            if(e.getSource() == BlueButton){
    
    
                contentPane.setBackground(Color.BLUE);
            }
        }
    }

}

Main:

package com.itheima;
public class Main {
    
    
    public static void main(String[] args) {
    
    
        MyFrame myFrame = new MyFrame();
        myFrame.setBounds(100,100,280,150);
        myFrame.setTitle("内部类的简单应用");

    }
}

Insert picture description here
Insert picture description here
Insert picture description here
The advantage of the inner class is that you can directly use the attributes and methods defined by the outer class, even if they are private, a bit like a C++ friend class.

Guess you like

Origin blog.csdn.net/weixin_48180029/article/details/112062704