简体   繁体   English

在窗口上打印数字数组

[英]Printing an array of numbers on a window

Hello I am new to java graphics and just experimenting with things but I am puzzled with how I can display the numbers in an array on my created window? 您好,我是Java图形的新手,只是尝试一些东西,但是我对如何在创建的窗口中的数组中显示数字感到困惑? I am not sure if it works the same as text or not? 我不确定它是否与文本相同?

import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class area extends JFrame{


    int[] myArray;
    myArray = new int[3];
    myArray[0] = 1;
    myArray[1] = 2;
    myArray[2] = 3;

JTextArea area = new JTextArea();
for (int i=0; i<myArray.length; i++)
{
    area.append(myArray[i]+"\n");
}
add(area);  


public static void main(String args[]) {

area gui = new area(); 
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(400,200);
gui.setVisible(true);
}
}

Use a JTextArea and you can save your array as a string 使用JTextArea,您可以将数组另存为字符串

String text;
for(int w : array) {
   w=Integer.toString(w);
   text+=w;
}

You can use a JTextArea. 您可以使用JTextArea。

JTextArea ta = new JTextArea();
for (int i=0; i<array.length; i++)
{
    ta.append(array[i]+"\n");
}
add(ta);

Are you using an IDE like eclipse? 您是否正在使用像eclipse这样的IDE? If not might help. 如果没有,可能会有所帮助。 Looks like part of your code is in the wrong place. 看起来您的代码部分放在错误的位置。 Instead of constructor or init method its just below the var declerations. 而不是构造函数或init方法位于var declerations之下。 IDE will help you with that. IDE将为您提供帮助。 Also go thru (patiently) some more basic tutorials and look at small existing code. 还可以(耐心地)阅读一些更基本的教程,并查看现有的小代码。

Following code worked for me small edit to yours near //constructor 以下代码对我有用,对您的// constructor附近进行小的编辑

    import java.util.Scanner;
    import javax.swing.JFrame;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

    //put in a file called area.java
    public class area extends JFrame{


            int[] myArray;
            JTextArea area = new JTextArea();
     //constructor 
     area(){
            myArray = new int[3];
            myArray[0] = 1;
            myArray[1] = 2;
            myArray[2] = 3;




    for (int i=0; i<myArray.length; i++)
    {
            area.append(i + " " + myArray[i]+"\n");
    }
    add(area);

       }
    public static void main(String args[]) {

         area gui = new area();
         gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         gui.setSize(400,200);
         gui.setVisible(true);
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM