所以我在这里撕掉我的头发,我似乎无法弄清楚为什么这些JLabel没有画到窗户上。我一直在关注我过去做过的另一个项目,它在JPanel中也使用了JLabel,一切似乎都是正确的。有谁看到我搞砸了这个?
package lab19_20;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class Lab19_20 extends JFrame implements ActionListener, MouseListener
{
JLabel[] lblBoard = new JLabel[16];
int[] nums = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8};
int firstChoice = -1;
int tries = 0;
JLabel lblFirst;
JButton btnGame = new JButton("New Game");
JLabel lblTries = new JLabel("0");
JPanel pnlControls = new JPanel();
JPanel pnlBoard = new JPanel();
Font lblBoardFont = new Font("Helvetica", Font.BOLD, 30);
Container content = this.getContentPane();
public Lab19_20()
{
setTitle("The Concentration Game");
setVisible(true);
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createLabels();
content.add(pnlBoard, BorderLayout.NORTH);
pnlControls.add(btnGame);
pnlControls.add(lblTries);
content.add(pnlControls, BorderLayout.SOUTH);
btnGame.addActionListener(this);
}
void createLabels()
{
pnlBoard.setLayout(new GridLayout(4, 4, 5, 5));
for(int i = 0; i < lblBoard.length; i++)
{
lblBoard[i] = new JLabel("", JLabel.CENTER);
lblBoard[i].setVisible(true);
lblBoard[i].setOpaque(true);
lblBoard[i].setBackground(Color.BLUE);
lblBoard[i].setForeground(Color.BLACK);
lblBoard[i].setFont(lblBoardFont);
lblBoard[i].addMouseListener(this);
lblBoard[i].setName("" + i);
pnlBoard.add(lblBoard[i]);
}
}
void shuffle()
{
int num1, num2, tmp = 0;
Random r = new Random();
for (int i = 0; i < 500; i++)
{
num1 = r.nextInt(nums.length);
num2 = r.nextInt(nums.length);
tmp = nums[num1];
nums[num1] = nums[num2];
nums[num2] = tmp;
}
}
@Override
public void actionPerformed(ActionEvent ae)
{
shuffle();
firstChoice = -1;
for (int i = 0; i < lblBoard.length; i++)
lblBoard[i].setText("");
tries = 0;
lblTries.setText("" + tries);
}
@Override
public void mouseClicked(MouseEvent me)
{
JLabel l = (JLabel) me.getSource();
int theNumber = Integer.parseInt(l.getName());
if (firstChoice == -1)
{
l.setText("" + nums[theNumber]);
lblFirst = l;
firstChoice = theNumber;
}
else if (nums[theNumber] != nums[firstChoice])
{
l.setText("" + nums[theNumber]);
pnlBoard.paintImmediately(0,0, pnlBoard.getWidth(), pnlBoard.getHeight());
try
{
Thread.sleep(250);
}
catch(InterruptedException blah){}
lblFirst.setText("");
l.setText("");
lblFirst = null;
firstChoice = -1;
tries++;
}
else
{
l.setText("" + nums[theNumber]);
firstChoice = -1;
tries++;
}
lblTries.setText("" + tries);
}
public static void main(String[] args)
{
Lab19_20 console = new Lab19_20();
}
@Override public void mousePressed(MouseEvent me) {}
@Override public void mouseReleased(MouseEvent me) {}
@Override public void mouseEntered(MouseEvent me) {}
@Override public void mouseExited(MouseEvent me) {}
}
答案 0 :(得分:1)
两件快事......
setVisible(true);
。lblBoard[i].setText("" + i);
代替(或以及lblBoard[i].setName("" + i);