简体   繁体   中英

Displaying text with JFrame

I'm trying to make a simple counter but the window that appears doesn't show anything at all. Not sure what I'm doing wrong but I feel like it has something to do with the output String not properly updating. Any insights would be greatly appreciated. Can only be wrong after all.

import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class main {

public static int counter = 0;
public static int end = 100;
public static String output;

public static void main (String[] args){
    window();
}
public static void window(){
    JLabel label = new JLabel(output, JLabel.CENTER);
    label.setAlignmentX(0);
    label.setAlignmentY(0);

    JFrame window = new JFrame("");
    window.setVisible(true);
    window.setSize(500,500);
    window.add(label);
}

public static void counter(String counter1) throws InterruptedException{

    Random rand = new Random();

    int start = 0;

    for(int i =0; i < end; i++){
        int random = rand.nextInt(60) + 1;
        start ++;

        if (start != 0){

            for(int z =0; z <= random; z++){
                counter ++;
                System.out.print(counter);
                Thread.sleep(1000);
            }
        }
        counter = 0;
        start = 0;
    }
}

The String output equals null.

You did never say to Java, this String, equals "bread", for example. But Java needs this information, otherwise it is nothing.

If you are typing before the creation of the JLabel,

output = "Bread";

It should display Bread on the screen.

You need to do following things in order to make this work:

  • Create the JLabel with some specific text like "It works" and get it to display properly. This may require calling pack() and setVisible(true) after adding JLabel to the JFrame.
  • Then you need to start the counting process. Currently it does not look like that method is getting called.
  • Finally you need to update the JLabel with new text label.setText(String.valueOf(count).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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