java背景颜色_java 背景颜色更改

这篇博客介绍了如何在Java Swing中实现按钮事件处理,通过点击不同按钮改变 JPanel 背景颜色。作者创建了三个颜色按钮(黄色、蓝色、红色),每个按钮关联了一个颜色动作,当按钮被点击时,背景色相应改变。

简介

java 事件处理机制

code

/*

* @Author: your name

* @Date: 2020-10-28 22:38:26

* @LastEditTime: 2020-10-29 10:01:15

* @LastEditors: Please set LastEditors

* @Description: In User Settings Edit

* @FilePath: /java/ImageTest.java

*/

import java.awt.*;

import javax.swing.*;

public class ImageTest {

public static void main(String[] args) {

EventQueue.invokeLater(() -> {

JFrame frame = new ButtonFrame();

frame.setTitle("ImageTest");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

});

;

}

}

/*

* @Author: your name

* @Date: 2020-10-29 09:41:06

* @LastEditTime: 2020-10-29 10:01:27

* @LastEditors: Please set LastEditors

* @Description: In User Settings Edit

* @FilePath: /java/ButtonFrame.java

*/

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class ButtonFrame extends JFrame {

private JPanel buttonPanel;

private static final int DEFAULT_WIDTH = 300;

private static final int DEFAULT_HEIGHT = 200;

public ButtonFrame() {

setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// create button

JButton yellowButton = new JButton("Yellow");

JButton blueButton = new JButton("Blue");

JButton redButton = new JButton("Red");

buttonPanel = new JPanel();

// add buttons to panel

buttonPanel.add(yellowButton);

buttonPanel.add(blueButton);

buttonPanel.add(redButton);

add(buttonPanel);

// create button actions

ColorAction yellowAction = new ColorAction(Color.YELLOW);

ColorAction blueAction = new ColorAction(Color.BLUE);

ColorAction redAction = new ColorAction(Color.RED);

// associate actions with buttons

yellowButton.addActionListener(yellowAction);

blueButton.addActionListener(blueAction);

redButton.addActionListener(redAction);

}

private class ColorAction implements ActionListener {

private Color backgroundColor;

public ColorAction(Color c) {

backgroundColor = c;

}

public void actionPerformed(ActionEvent event) {

buttonPanel.setBackground(backgroundColor);

}

}

}

image

7c28aaf9e8235f7b0a6238a2033ddb52.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值