[Java] [クラスとオブジェクト]内部クラスの簡単なアプリケーション

グラフィカルユーザーインターフェイスで、3つのボタンを設定して、背景色をそれぞれ赤、緑、青に設定します。

ここに画像の説明を挿入

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

}

メイン:

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

    }
}

ここに画像の説明を挿入
ここに画像の説明を挿入
ここに画像の説明を挿入
内部クラスの利点は、外部クラスによって定義されたプロパティとメソッドを、プライベートであっても、C ++フレンドクラスのように直接使用できることです。

おすすめ

転載: blog.csdn.net/weixin_48180029/article/details/112062704