gpt4 book ai didi

java - 下面的代码是每次单击按钮时显示随机颜色。但尽管已完全编译,但它不起作用。谢谢

转载 作者:行者123 更新时间:2023-12-02 11:05:33 26 4
gpt4 key购买 nike

package gui;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class gui7 implements ActionListener {

JFrame frame=new JFrame();

JButton button=new JButton("Click me");

public static void main(String args[]) {

gui7 a=new gui7();

a.go();

}
public void actionPerformed(ActionEvent event) {

frame.repaint(); //to call paintcomponent

}
public void go() {

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

button.addActionListener(new gui7());

gui8 f=new gui8();

frame.getContentPane().add(BorderLayout.SOUTH,button);

frame.getContentPane().add(BorderLayout.CENTER,f);

frame.setSize(300,300);

frame.setVisible(true);
}


}


package gui;

import java.awt.*;

import javax.swing.*;

public class gui8 extends JPanel {

public void paintComponent(Graphics g) {

g.fillRect(0, 0, this.getWidth(),this.getHeight());

//创建随机颜色的代码

    int red=(int)(Math.random()*255);

int blue=(int)(Math.random()*255);

int green=(int)(Math.random()*255);

Color rand=new Color(red,blue,green);

g.setColor(rand);

g.fillOval(70, 70, 100, 100);

}

}

最佳答案

我认为你应该改变线路

button.addActionListener(new gui7());

 button.addActionListener(this);

关于java - 下面的代码是每次单击按钮时显示随机颜色。但尽管已完全编译,但它不起作用。谢谢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51000136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com