1:变换背景(案例)

需求:根据按钮点击变换下边区域的颜色背景

在这里插入图片描述

知识点:继承、接口、布局

package demo1;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class EventFrame extends JFrame implements ActionListener {
    private JButton btnRed = new JButton("红色");
    private JButton btnGreen = new JButton("绿色");
    private JButton btnBlue = new JButton("蓝色");
    private JTextField jTextField = new JTextField();
    private JPanel p = new JPanel();

    public EventFrame() {
        btnRed.setFont(new Font("", Font.BOLD, 24));
        btnGreen.setFont(new Font("", Font.BOLD, 24));
        btnBlue.setFont(new Font("", Font.BOLD, 24));
        p.setLayout(new FlowLayout());
        p.add(btnRed);
        p.add(btnGreen);
        p.add(btnBlue);
        btnRed.addActionListener(this);   //使用this来传递当前对象引用
        btnGreen.addActionListener(this);
        btnBlue.addActionListener(this);
        jTextField.setSize(300, 300);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(jTextField, BorderLayout.CENTER);
        getContentPane().add(p, BorderLayout.NORTH);
        setSize(400, 300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton obj = (JButton) e.getSource();   //使用getSource获取当前事件源,然后强转为按钮对象
        if (obj == btnRed) {
            jTextField.setBackground(Color.red);
        } else if (obj == btnGreen) {
            jTextField.setBackground(Color.green);
        } else {
            jTextField.setBackground(Color.blue);
        }
    }
}

程序入口

package demo1;

/**
 * Date: 2019/1/18 0018
 **/
public class Main {
    public static void main(String[] args) {
        new EventFrame();

    }
}



方法参考
1:接口ActionListener的源码
public interface ActionListener extends EventListener {

    /**
     * Invoked when an action occurs.
     */
    public void actionPerformed(ActionEvent e);

}
2:Swing布局(参考下一节)

3:getContentPane()方法
getContentPane
public Container getContentPane()返回此框架的 contentPane对象。 
Specified by: 
getContentPane在接口 RootPaneContainer 
结果 
contentPane财产 
另请参见: 
setContentPane(java.awt.Container) , RootPaneContainer.getContentPane() 

发布了67 篇原创文章 · 获赞 9 · 访问量 5187

猜你喜欢

转载自blog.csdn.net/Octopus21/article/details/86549078
今日推荐