gpt4 book ai didi

java - 与actionListener静态类冲突

转载 作者:行者123 更新时间:2023-12-02 00:48:34 25 4
gpt4 key购买 nike

我正在寻找一些方向。我想要一个按钮来为图形内容中绘制的内容提供动力。我之前曾将按钮与 jframe 和监听器一起使用。但不知怎的,听众并没有被接受。我确信这与声明的两个类有关。有人能告诉我问题是什么或冲突吗?

我不能使用//f.addWindowListener(this); //b.addActionListener(this);它标志着错误,这就是为什么它们被写成注释...=S

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

/* implements ActionListener*/
class JFramePaint1 extends JFrame implements ActionListener {

public static int activa = 0;
public static JButton b = new JButton("b");

public static void main(String[] a) {

JFrame f = new JFrame();
f.setTitle("Drawing Graphics in Frames");
f.setSize(800, 650);
f.setLocation(200, 50);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setContentPane(new ContentComponent());
f.getContentPane().add(b);

//f.addWindowListener(this);
//b.addActionListener(this);

f.setVisible(true);
}

static class ContentComponent extends JPanel {

public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillRect(0, 40, 800, 650);
if (activa == 1) {

g.setColor(Color.BLACK);
g.drawRect(40, 40, 150, 80);
int x = 40;
int y = 40;
for (int i = 0; i < 4; i++) {

g.drawRect(x + 10, y + 10, 150, 80);
x = x + 10;
y = y + 10;
}
}
}//del paint
}

public void actionPerformed(ActionEvent e) {
if (e.getSource() == b) {
System.out.println("entro");
}
}

public void windowClosing(WindowEvent e) {
System.exit(0);
}

public void windowOpened(WindowEvent e) {}

public void windowClosed(WindowEvent e) {}

public void windowActivated(WindowEvent e) {}

public void windowDeactivated(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}
}

最佳答案

你不能使用

  //f.addWindowListener(this);
//b.addActionListener(this);

因为你使用的是静态方法。您期望 this 指向什么?

关于java - 与actionListener静态类冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4170244/

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