点击面板上的按钮,改变相应的颜色

本文介绍了一个使用Java Swing实现的简单示例程序,通过点击不同颜色的按钮来改变面板背景色。程序中利用了按钮事件监听器来响应用户交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

package swing;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

/**
 * 点击面板上的按钮,改变相应的颜色
 *
 * 1.都是用字符串构造button
 * 2.都是将该button添加到panel
 * 3.都是用对应的颜色构造一个监听器
 * 4.都会添加监听器动作
 */
public class ButtonTest {
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   @Override
   public void run() {
    ButtonFrame frame = new ButtonFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
   }
  });
 }
}

class ButtonFrame extends JFrame {
 public ButtonFrame() {
  this.setTitle("Button Test");
  this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  
  buttonPanel = new JPanel();
  
  this.makeButton("Yellow", Color.YELLOW);
  this.makeButton("Blue", Color.BLUE);
  this.makeButton("Red", Color.RED);
  
  //将panel添加至frame
  this.add(buttonPanel);
 }
 
 private void makeButton(String name, final Color backgroundColor) {
  JButton button = new JButton(name);
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent event) {
    buttonPanel.setBackground(backgroundColor);
   }
  });
 }
 
 public static final int DEFAULT_WIDTH = 300;
 public static final int DEFAULT_HEIGHT = 200;
 
 private JPanel buttonPanel;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值