setText为什么不更新JLabel? [英] Why isn't setText updating the JLabel?

查看:97
本文介绍了setText为什么不更新JLabel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里检查了其他线程,但没有找到解决方案.

I've checked on the other threads here and haven't found a solution.

1)JFrame是setVisible(true).

1) The JFrame is setVisible(true).

2)这是什么意思:我想知道您的问题是否是并发问题,您正在Swing事件线程上运行一个长时间运行的过程,并且这正在阻止您的标签更新其文本."我在其他地方读过.

2) What does this mean: "I wonder if your problem is a concurrency issue, that you are doing a long-running process on the Swing event thread and that this is preventing your label from updating its text." I read that somewhere else.

3)我没有多次初始化包含标签的JPanel.

3) I haven't initialized multiple times the JPanel that contains the label.

4)从包含TrackingPanel(即gamePanel)的JPanel调用updateTurn.我将方法称为changeTurns();,这是该代码:

4) updateTurn is called from the JPanel that contains TrackingPanel (i.e. gamePanel). I call the method changeTurns(); and here's the code for that:

public void changeTurns() {
    if(turnPlayer == playerX)
        turnPlayer = playerO;
    else
        turnPlayer = playerX;

    trackingPanel.updateTurn();
}   

以下是完整的相关代码:

Here's the relevant code in full:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TrackingPanel extends JPanel{

    /*TURN STUFF*/
    private JPanel turnPanel; //turns panel to keep track of whose turn it is
    private JLabel turnLabel;
    private String turn;

    /*OTHER*/
    private GamePanel gamePanel;


    public TrackingPanel( GamePanel gamePan ) {

        setLayout( new GridLayout(1,4) );
        setBorder(BorderFactory.createMatteBorder(2,2,4,2,Color.BLACK));

        gamePanel = gamePan;

        /*THIS PANEL DISPLAYS THE TEXT*/
        turnPanel = new JPanel( new GridLayout(2,1) );
        turn = gamePanel.getPlayerTurn().getLetter();
        turnLabel = new JLabel("      Player " + turn + "'s turn");
        add( turnPanel);

    }//end constructor

    /*THIS IS WHERE THINGS GO WRONG*/
    public void updateTurn() {

        turn = gamePanel.getPlayerTurn().getLetter();
        turnLabel.setText( "      Player" + turn + "'s turn" );
        System.out.println(turn);
    }
}

在调用updateTurn()之前,turnLabel说"PlayerX轮到".之后,应该说"PlayerO轮到我了".通过打印出turn(我得到的是字符串'O'而不是'X'),我知道所显示的内容("PlayerX的转身")不是应该显示的内容("PlayerO的转身").

Before updateTurn() is called, turnLabel says "PlayerX's turn". After, it should say "PlayerO's turn". By printing out turn (I get the string 'O', instead of 'X'), I know that whats being displayed ("PlayerX's turn") is not what should be displayed ("PlayerO's turn").

预先感谢您的光临!

编辑.尝试提供SSCCE,但不知道如何包含图像文件.抱歉!

EDIT. Tried giving SSCCE but don't know how to include image files. Sorry!

推荐答案

尝试使用此功能:

 private void setText(final JLabel label, final String text){
    label.setText(text);
    label.paintImmediately(label.getVisibleRect());
 }

这篇关于setText为什么不更新JLabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆