gpt4 book ai didi

java - 如何让这个类调用另一个类

转载 作者:行者123 更新时间:2023-11-29 07:04:38 24 4
gpt4 key购买 nike

好的,我有 2 节课这是我的主类,它打开一个 JFrame 并向 JFrame 绘制一些东西:

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

public class MainWindow extends Canvas{

public static int HEIGHT = 600;
public static int WIDTH = 600;

public static void main(String[] args){
MainWindow Window = new MainWindow();
JFrame Frame = new JFrame();
Frame.add(Window);
Frame.pack();
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setVisible(true);
Frame.setSize(WIDTH, HEIGHT);
Frame.setLocationRelativeTo(null);
Frame.setResizable(false);
Frame.setTitle("Untitled Build 0.01");
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.GRAY);
g.drawString("Sellect A Difficulty", 100, 25);
g.drawString("Please input a number from 1 - 3", 100, 40);
g.drawString("1. Easy", 100, 55);
g.drawString("2. Medium", 100, 70);
g.drawString("3. Hard", 100, 85);
g.setColor(Color.BLACK);
}
}

这是我的第二堂课,它用于设置游戏的难度,但我需要主课来调用它,但我不确定如何让它做到这一点。

  public class Difficulty {
public static final int input = 0;
static int NoInput = 1;
public static int Difficulty = 0;

@SuppressWarnings("unused")
public static void main(String[] args){
if(NoInput == 1){
//draw text to screen here
//TODO Write text to screen here about selecting difficulty
Difficulty = Keyboard.readInt();
if(input == 1){
Difficulty = 1;
}else if(input == 2){
Difficulty = 2;
}else if(input == 3){
Difficulty = 3;
}else if(input < 0 | input > 3){
//TODO draw "please input a number between 1 and 3 try again...." to screen
}
}
}
}

最佳答案

你的第二个类只不过是一个只有一个静态 main 方法的程序,这是行不通的。建议:

  • 删除第二个类并将其重新编写为真正的 OOP 兼容类,其中包含非静态字段、方法、构造函数、setter 等。
  • 然后第一个类可以有第二个对象并根据需要调用它的方法。
  • 第二个类也需要是一个非控制台 GUI 类,很可能是一个生成 JOptionPane 的类。
  • 您的 GUI 类不应混合使用 AWT 和 Swing 组件,而应该只包含 Swing 组件。
  • 阅读“使用 Swing 绘画”教程,了解如何改进您的绘画。

关于java - 如何让这个类调用另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21244967/

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