简体   繁体   中英

Calling JLabel from method

I'm currently following a tutorial on how to make a guessing game gui app. I don't understand the following instruction though. Create each JLabel of lblBoard by calling the overloaded constructor and setting the text to "" (empty string) and it's alignment to center

any help would be greatly appreciated

here is my code so far:

package assignment.pkg19;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import java.util.Random;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import java.lang.Object;

public class Assignment19 extends JFrame implements ActionListener, KeyListener
{

Container content = this.getContentPane(); 

//arrays
    JLabel lblBoard [] = new JLabel[16]; 
     int nums [] = new int[16];

     //variables
     int firstChoice = -1;
     int tries = 0;

     //interface
     JButton btnGame = new JButton("New Game");
     JLabel lblTries = new JLabel("0"); 
     JPanel pnlControls = new JPanel();
     JPanel pnlBoard = new JPanel();
     String lblFirst;
     public void createLabels()
     {
         pnlBoard.setLayout(new GridLayout(4,4, 5, 5));
        for (int i = 0; i < 16; i++)  
        {
            //call jlabel
            lblBoard.setOpaque(true);



        }
     }

    public static void main(String[] args) 
    {

    }

    @Override
    public void actionPerformed(ActionEvent e) 
    {

    }

    @Override
    public void keyTyped(KeyEvent e) 
    {

    }

    @Override
    public void keyPressed(KeyEvent e) 
    {

    }

    @Override
    public void keyReleased(KeyEvent e) 
    {

    }

}

A constructor is the function that is called when you create a new Object of a Class. (In our case, JLabel is the class), try this:

for(int index=0;index<lblBoard.lenght;i++){
        lblBoard[index] = new JLabel(""); 
        //We create a new JLabel object without text in the array of JLabels lblBoard.
}

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