gpt4 book ai didi

java - 我应该创建一个新类来制作代码的 gui 吗?

转载 作者:行者123 更新时间:2023-11-29 05:57:50 25 4
gpt4 key购买 nike

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class Test {
private static ArrayList<Countries> arr = new ArrayList<Countries>();
private static ArrayList<Countries> d = new ArrayList<Countries>();
static String country;
static String capital;
static String cities;
static String cevap;
static int score =0;


public static void main(String args[]) throws IOException{
Scanner keybord = new Scanner(System.in);
arr = new ArrayList<Countries>();
d = read("data.txt");

for(int i = 0; i < d.size(); i++){
System.out.print( d.get(i).toString());
cevap = keybord.nextLine();
if(cevap.equalsIgnoreCase(d.get(i).getCapital())){
System.out.println ("The answer is true!\nYou win 10 points");
score += 10;
}
else{
System.out.println("The answer is not true" + " The answer is " + d.get(i).getCapital() + "\nYou loose 10 points");
score -= 10;
}
System.out.println("You're score is: " + score);
System.out.println();
}
}



public static ArrayList<Countries> read(String filename) throws IOException{
Scanner scan = new Scanner(new File(filename));
while(scan.hasNext()){
country = scan.nextLine(); //System.out.println(country);
String cities1 = scan.nextLine(); //System.out.println(cities1);
String cities2 = scan.nextLine(); //System.out.println(cities2);
String cities3 = scan.nextLine(); //System.out.println(cities3);
String cities4 = scan.nextLine(); //System.out.println(cities4);
String capital = scan.nextLine(); //System.out.println(capital);
Countries c = new Countries(country, cities1, cities2, cities3, cities4, capital);
arr.add(c);
scan.nextLine();
}
return arr;
}



}

要制作这个程序的 Gui,我应该更改主要部分,如下所示。因为我觉得我从读取的数据中读取和初始化变量会更方便。或者我应该为 Gui 创建另一个类吗?

public static void main(String args[]) throws IOException{
Scanner keybord = new Scanner(System.in);
arr = new ArrayList<Countries>();
d = read("data.txt");

for(int i = 0; i < d.size(); i++){
lcountry = new JLabel(d.get(i).getCity1());
label1 = new JLabel(d.get(i).getCity1());
label2 = new JLabel(d.get(i).getCity2());
label3 = new JLabel(d.get(i).getCity3());
label4 = new JLabel(d.get(i).getCity4());

最佳答案

不,我建议将所有 UI 内容封装在一个单独的类中。如果将它放在 main 方法中,它的用处就会小得多。

事实上,这适用于您的所有类(class)。一个 main 方法应该非常小,并且除了创建执行实际工作的类的实例之外,别无其他。如果 main 很大,那是你做错了。

无论您使用文本还是图形 UI,您的问题都应该可用。当您可以将文本 UI 换成图形 UI 并且一切仍然有效时,您可以说您已经很好地封装了东西。这称为封装和分层。如果您不能轻松更换 UI,那您就错了。

关于java - 我应该创建一个新类来制作代码的 gui 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378794/

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