gpt4 book ai didi

java - 使用 ActionListener 查找事件时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 12:42:00 24 4
gpt4 key购买 nike

我刚刚开始使用 JSwing 并尝试学习如何处理按钮等,因此所有批评都将受到赞赏,并且我会为任何基本错误提前道歉。我只是想创建一个基本的 JFrame,其中有两个具有不同结果的按钮。由于某种原因,即使我使用 Action 监听器,actionPerformed 方法也找不到按钮“pressme”。谁能帮我找到这个问题的解决方案?先感谢您!-尼克

    import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JPanel extends JFrame implements ActionListener
{
public JPanel createContentPane(){
JPanel pane = new JPanel();
Container con = this.getContentPane();
JPanel titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(10, 0);
titlePanel.setSize(250, 30);
pane.add(titlePanel);
JLabel answer = new JLabel("");
pane.add(answer);
JLabel label1 = new JLabel("Is Ms. Stilman a savage?", JLabel.CENTER);
label1.setSize(150, 15);
label1.setLocation(250, 10);
titlePanel.add(label1);
JButton pressme = new JButton("Nah, what are you talking about?");
pane.add(pressme);
pressme.setMnemonic('P');
pressme.addActionListener(this);
pressme.setLocation(250, 10);
pressme.requestFocus();
JButton secondpress = new JButton("Yea she's a hardcore savage.");
pane.add(secondpress);
secondpress.addActionListener(this);
secondpress.setLocation(250, 10);
secondpress.requestFocus();
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == pressme) {
answer.setText("Button pressed!");
JOptionPane.showMessageDialog(null, "You're wrong and probably a scrub.", "Message Dialog",
JOptionPane.PLAIN_MESSAGE); setVisible(true);
}
else if (source == secondpress) {
answer.setText("Button pressed!");
JOptionPane.showMessageDialog(null, "Oh ya for sure.", "Message Dialog",
JOptionPane.PLAIN_MESSAGE); setVisible(true);
}
}
public static void createAndShowGui(){
JFrame Frame1 = new JFrame("Button Press Test");
setContentPane(demo.createContentPane());
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}

最佳答案

您的按钮是在方法中声明和实例化的局部变量,将它们更改为实例变量例如:

private final JButton pressme;
private final JButton secondpress;

createContentPane(){
pressme = new JButton("Nah, what are you talking about?");
secondpress =new JButton("Yea she's a hardcore savage.");
}

关于java - 使用 ActionListener 查找事件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36749402/

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