【问题标题】:How do I change the background color when the button is pressed? [closed]按下按钮时如何更改背景颜色? [关闭]
【发布时间】:2023-01-15 09:38:00
【问题描述】:

我正在制作一个制作窗口的程序,在窗口中打印一个十六进制代码,然后制作一个按钮。我想做的是将背景设置为十六进制代码颜色,并使按钮在按下时更改背景。这是我的代码:

import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
 
class Main{
    /**
     * @param args
     */
    public static void main(String[] args){
        Random obj = new Random();
        int rand_num = obj.nextInt(0xffffff + 1);
        String colorCode = String.format("#%06x", rand_num);
 
        JFrame frame = new JFrame();
        JLabel textLabel = new JLabel();
        JButton button1 = new JButton("New Color");
       
        frame.setTitle("Color Generator");
        frame.setSize(500, 500);
        //add a method to have colorCode become the background color
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
 
        textLabel.setText(colorCode);
        textLabel.setFont(new Font("Veranda", Font.PLAIN, 40));
        frame.add(textLabel);
 
        frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
        frame.getRootPane().setDefaultButton(button1);
        frame.add(button1);
    }
}

【问题讨论】:

  • java中有很多gui框架。我建议在您的问题中添加 swing 标签
  • 欢迎来到堆栈溢出。请使用 tour 了解 Stack Overflow 的工作原理,并阅读 How to Ask 了解如何提高问题的质量。请显示您尝试过的尝试以及您从尝试中得到的问题/错误消息。
  • 单击按钮时,您希望代码的哪一部分更新背景颜色?

标签: java


【解决方案1】:

你可以做这样的事情。像您所做的那样将您的代码堆积到main 中并不是一个好主意。我会留给你来改变它。

import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;

public class Main {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Random obj = new Random();
        int rand_num = obj.nextInt(0xffffff + 1);
        String colorCode = String.format("#%06x", rand_num);

        JFrame frame = new JFrame();
        JLabel textLabel = new JLabel();
        JButton button1 = new JButton("New Color");

        frame.setTitle("Color Generator");
        frame.setSize(500, 500);
        // add a method to have colorCode become the background color
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        textLabel.setText(colorCode);
        textLabel.setFont(new Font("Veranda", Font.PLAIN, 40));

        frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
        frame.getRootPane().setDefaultButton(button1);
        frame.add(textLabel);
        frame.add(button1);
        button1.addActionListener(e -> { 
            frame.getContentPane().setBackground(Color.decode(textLabel.getText()));
        });
        frame.setVisible(true);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2023-04-01
    • 1970-01-01
    • 2021-02-23
    • 2019-04-14
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多