【问题标题】:Trying to create a simple applet but it won't run through the whole program试图创建一个简单的小程序,但它不会运行整个程序
【发布时间】:2013-05-01 20:53:31
【问题描述】:

我正在创建一个小程序,然后它会打开显示“有多少种类型?”然后出现一个文本字段。我输入一个数字并按回车,但什么也没发生! (我没有收到任何错误,但没有任何反应)

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class appletPracticw extends Applet implements ActionListener { 
TextField numG;
TextField g ;
TextField numS; 
TextField sog; 
private int number;
private int numberOfSongs;
String gener;
String songName;
public void go(){
    numG= new TextField(5);
    numS= new TextField(5);
    g= new TextField(5);
    sog= new TextField(5);
    numG.addActionListener(this);
    g.addActionListener(this);
    sog.addActionListener(this);
    numS.addActionListener(this);
    Tracker t=new Tracker();
    add(new Label("How many genres are there? "));  add(numG);
    for(int i=0;i<number;i++){
        catogories c=new catogories();
        add(new Label("Name of genere: "));  add(g);
        t.addCatogory(c,gener);
    }
    for(int x=0;x<number;x++){
        add(new Label("How many songs are there in "+t.getCatogories().get(x).getGenere()));  add(numS);
        for(int i=0;i<numberOfSongs;i++){
            Songs s=new Songs();
            add(new Label("The name of song "+(i+1)+" is"));  add(sog);
            t.getCatogories().get(x).addSong(s, songName);
        }
    }
}
public void actionPerformed(ActionEvent e) {
    if(e.getSource()==numG){
        String num=numG.getText();
        number=Integer.parseInt(num);
    }
    if(e.getSource()==numS){
        String num=numS.getText();
        numberOfSongs=Integer.parseInt(num);
    }
    if(e.getSource()==g){
        gener=g.getText();
    }
    if(e.getSource()==sog){
        songName=sog.getText();
    }
}
public void init() {
    go();

} 公共小程序Practicw() {

} }

【问题讨论】:

  • “试图创建一个简单的小程序..” “简单的小程序”是一个重言式。有关详细信息,请参阅Why should CS teachers stop teaching applets?。如果您想要“简单”,请编写基于 Swing 的框架。

标签: java applet textfield


【解决方案1】:

number 字段被初始化为 0

您构建小程序,添加标签和文本字段。看起来您假设程序在此行等待用户输入:

add(new Label("How many genres are there? "));  add(numG);

实际上它只是创建用户界面而不等待输入。

因此执行了两个for 循环,但由于number 仍然是0,因此永远不会进入循环。

您应该做的是在 actionPerformed 方法中执行实际操作(在您的情况下,这是通过添加新标签和字段来更改 GUI),以便在 之后创建类别标签和输入字段 用户输入了流派的数量。第二个循环也必须这样做。

【讨论】:

  • 等等,我不能扩展 2 个类。
  • @LouisB 不客气,我希望你明白了。之所以使用ActionListener,是因为用户输入可以随时进行,您的程序需要对它做出某种反应。
  • 等等,但我仍然不明白如何初始化一个基本结构,然后在发生某些事情后继续?像我应该把我的 for 循环放在 actionlistner 中吗?
  • 这有点难说,因为我不知道你的整个应用程序或网站的确切目的是什么。抱歉,“扩展 ActionListener”具有误导性 - 我的意思是您应该在 actionPerformed 方法中执行实际操作(例如,显示新标签和 InputFields)。你应该写下一个计划来定义你希望你的屏幕在哪些输入之后改变。我不知道您还想在您的小程序中做什么,但我现在看到的内容可以使用 HTML 和一些 JavaScript 更轻松地完成。
猜你喜欢
  • 2014-11-18
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多