从方法调用JLabel

时间:2015-12-13 22:25:03

标签: java arrays swing methods

我目前正在关注如何制作猜谜游戏应用的教程。我不明白以下说明。 通过调用重载的构造函数并将文本设置为“”(空字符串)并将其对齐到中心来创建lblBoard的每个JLabel

任何帮助将不胜感激

到目前为止,这是我的代码:

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) 
    {

    }

}

1 个答案:

答案 0 :(得分:0)

构造函数是在创建类的新Object时调用的函数。 (在我们的例子中,JLabel就是这个类),试试这个:

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.
}