【问题标题】:JTextField set text output wrongJTextField 设置文本输出错误
【发布时间】:2016-10-15 15:03:17
【问题描述】:

我正在尝试为我构建的随机名称生成器构建一个 GUI,目前我正在尝试让它在我按下按钮时打印出名称。

但是,我得到的不是名称列表,而是“[]”。我不太了解 GUI 编程,所以我不确定这里出了什么问题。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.nio.file.*;
import java.util.*;


public class Applet1 extends javax.swing.JApplet {

public static List<String> list = new ArrayList<String>();

public static void init(String args[])throws IOException{

      List<String> prefix = Files.readAllLines(Paths.get("prefix.txt"));
      List<String> suffix = Files.readAllLines(Paths.get("suffix.txt"));
      Random randomizer = new Random();


      String prefix2 = prefix.get(randomizer.nextInt(prefix.size()));
      String suffix2 = suffix.get(randomizer.nextInt(suffix.size()));                         
      Random ran = new Random();
      int C = ran.nextInt(5);

        for(int A=0;A <= 5;A++){
            if( C == 0 )
                list.add(prefix2 + " ");                
            else if( C>0 && C<3 )
                list.add(prefix2 + suffix2+ " ");                   
            else if( C>2 && C<6 )
                list.add(prefix2 + " " + prefix2 + suffix2+ " ");}}


public void init() {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting     code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the     default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Applet1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Applet1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Applet1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Applet1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the applet */
    try {
        java.awt.EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                initComponents();
            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

/**
 * This method is called from within the init() method to initialize the
 * form. WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jComboBox1 = new javax.swing.JComboBox<>();
    jButton1 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();

    setMinimumSize(new java.awt.Dimension(498, 517));

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "5", "10", "15" }));

    jButton1.setText("Press");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel1.setText("Select number of names and press button to Generate");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addGap(18, 18, 18)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(121, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton1)
                .addComponent(jComboBox1,     javax.swing.GroupLayout.PREFERRED_SIZE, 21,     javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(33, Short.MAX_VALUE))
    );
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jTextField1.setText(list.toString());
}                                        


// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration



}

据我所知,要么我在某处破坏了代码,要么 TextField 无法处理字符串数组。

【问题讨论】:

  • System out println this list.toString()) 先看看会发生什么。然后您可以确定您的 GUI 是问题还是其他地方的逻辑问题

标签: java arrays swing jtextfield


【解决方案1】:

这个方法永远不会被调用:

public static void init(String args[])throws IOException{ 

因此,list 仍然为空。

其他提示/注意事项/问题:

  1. 小程序的大小在 HTML 中设置,因此任何大小(最小值、大小或最大值)的设置都不应在代码中调用。

    setMinimumSize(new java.awt.Dimension(498, 517));
    
  2. 为什么要编写小程序?如果是老师指定的,请参考Why CS teachers should stop teaching Java applets

  3. Java Plugin support deprecatedMoving to a Plugin-Free Web
  4. 从 GUI 的文本字段大小来看,它似乎实际上需要是一个多行文本区域 (JTextArea)。

【讨论】:

  • OP 的代码有很多错误,很难知道从哪里开始。
  • 1.每当我通过 Eclipse 启动它时,applet 页面都太小了,所以我一直试图让它更大。似乎从来没有工作过。
  • 另外,我刚刚查找了如何制作 Java GUI,并且有很多页面说小程序是要走的路。此外,如果我必须将其转换为可能会破坏我现有代码的 TextArea。 GUI设计应该这么难吗?
  • "..有很多页面说小程序是要走的路。" 互联网上有很多垃圾。除此之外,小程序在去年变得不那么有用了。您可以信任您看到的那些页面,也可以信任为AppletJApplet 提供最高评价的答案提供者,写了信息。两者的页面,您似乎忽略的博客文章,并且不断建议不要使用它们,包括现在(即我)。你的选择,真的。
  • @AndrewThompson 好的,所以我接受了您的建议,并在带有 TextArea 的 Jframe 中对其进行了重新设计,并对现在实际工作的代码进行了一些重新排序:imgur.com/a/lCTKG
【解决方案2】:

您的问题与 GUI 或 Swing 代码无关,而与错误的 for 循环有关。它永远不会循环,因为您的条件是向后的:

for(int A=0;A >= 5;A++){

由于 A 变量开始为 0,它永远不会满足 A &gt;= 5 的 for 循环布尔标准,因此循环永远不会“循环”,并且列表保持为空 - 这就是您所看到的.

一种解决方案是更改该循环以使其正常工作,也许您希望:

for(int A = 0; A <= 5; A++) {  // this loops 6 times (not 5)

请查看:How to Debug Small Programs

此外,您的类是一个小程序,但您已经给它一个主方法——一个从不在小程序中运行的方法。该代码不应该在init() 方法中吗?

【讨论】:

  • 感谢您注意到这一点,我已对其进行了更改,但无论哪种方式它仍然只产生“[]”
  • @Exostrike:你的类也是一个小程序,但你给了它一个主方法——一个从不在小程序中运行的方法。该代码不应该在init() 方法中吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
相关资源
最近更新 更多