java如何在另一个类中使用方法
我对Java和编码都是新手,但我学得很快。我一直在努力学习JFrame按钮,但除了打印行之外,我无法让我的按钮做任何事情。有人能解释一下如何让按钮运行方法“Lmao()”:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
public class GameCenter2
{
public static void Lmao() {
Scanner scan = new Scanner(System.in);
boolean run = true;
while (run) {
int random = (int) (Math.random() * 100);
System.out.println("Pick a number 1 - 100");
int response = scan.nextInt();
int difference = java.lang.Math.abs(response - random);
if (random == response) {
System.out.println("Congradulations, you win! The number was " + random);
} else {
System.out.println("WRONG! You were " + difference + " numbers off. The number was " + random + ".");
}
System.out.println("Would you like to play again? Yes or No.");
String response1;
response1 = scan.next();
if (response1.equals("Yes")) {
run = true;
} else {
run = false;
}
}
}
public static void main(String[] args) {
Login();
Button frm = new Button("GameCenter");
frm.setSize(200, 100);
frm.setVisible(true);
}
}
class Button extends JFrame implements ActionListener {
boolean guess;
JButton bChange; // reference to the button object
// constructor for ButtonFrame2
Button(String title) {
super(title); // invoke the JFrame constructor
setLayout(new FlowLayout()); // set the layout manager
// construct a Button
bChange = new JButton("Guessing Game");
// register the ButtonFrame2 object as the listener for the JButton.
bChange.addActionListener(this);
add(bChange); // add the button to the JFrame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent evt) {
Lmao();
}
}
这样做的目的是希望我能够为我所有的不同项目提供一个很好的中心,这就是为什么我希望能够使用一系列的方法,除非有更好的方法
# 1 楼答案
您正试图从另一个类访问
static
方法静态方法应该被称为
所以,在你的情况下
应该有用
如果是非静态方法,则应该创建一个对象并使用like Object。方法()
例如
对代码的一点小小改进