【问题标题】:JTextField won't disappear completelyJTextField 不会完全消失
【发布时间】:2014-12-03 04:18:25
【问题描述】:

我创建了一个对话框,让用户从内存中输入 5 种颜色。这一切都完全有效,只是有一个轻微的审美问题。在正确输入所有 5 种颜色或输入错误的一种时,假设擦除对话框中的内容并打印消息“对不起!颜色不正确”或“恭喜”。它打印消息,但仍然可以在消息后面看到 JTextField(剩余部分/剪辑)。

我尝试过使用 hide() 和 remove() 方法,但它们似乎不起作用(或者我使用不正确),我尝试重新制作一个对话框,但我做不到似乎仍然可以解决问题。我在做什么错/如何使 JTextField 在完成后消失?提前感谢您的帮助!

如果用户输入的颜色不正确或全部正确(txtName 是 JTextField),以下是部分:

        if(count == 6)//User either finished or entered a color incorrectly
        {                
            //Entered color incorrectly
            if(incorrect == true)
            {                    
                txtName.setEnabled(false); //Doesn't work
                homeScreen.remove(txtName); //Doesn't work
                labelName.setText("Incorrect! Sorry - Wrong color.");
                //txtName.removeActionListener(new MyButtonListener());
            }
            else//Correctly finished the game.
            {
                labelName.setText("Congratulations - your memory skills are perfect!");
                //txtName.removeActionListener(new MyButtonListener());
                homeScreen.remove(txtName);//Doesn't work
            }
        }

这是我的整个程序(我无法在帖子中正确格式化):

package memorygame;

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

public class MemoryGame 
{
    private JFrame homeScreen;
    private JLabel labelName;
    private JTextField txtName;
    private JLabel correct;
    Vector<String> name = new Vector();
    private int count = 1;

    private MyButtonListener listen1 = new MyButtonListener();

    //Constructor - Method to be called when MemoryGame object called
    public void MemoryGame ()
    {
        homeScreen = new JFrame();    
        homeScreen.setSize(400,200);
        homeScreen.setTitle("Memory Game");  
        homeScreen.setDefaultCloseOperation(homeScreen.EXIT_ON_CLOSE);
        homeScreen.setLayout(new FlowLayout());  
        labelName = new JLabel();
        txtName = new JTextField(10);
        createContents();
        homeScreen.setVisible(true);
    }//End Constructor

    //Create components and add them to the window/dialog box
    private void createContents()
    {       
        labelName.setText("Enter the color " + count + ":");
        System.out.println("The current count is: " + count);
        homeScreen.add(labelName); 
        homeScreen.add(txtName);
        txtName.addActionListener(new MyButtonListener());//Allows you to press enter to invoke action
    }
    //Upon user hitting enter
    private class MyButtonListener implements ActionListener
    {
        public void actionPerformed (ActionEvent e)//When event occurs
        {
            Scanner in = new Scanner (System.in);//For program input
            String answer = "";
            //Make memColor an array for randomized colors
            /*

            Random r = new Random();
            String[] memColors = new String[5];             
            String[] colors = {"red", "green", "blue", "yellow", "brown", "purple"};

            for(int i =0; i < memColors.length; i++)
            {
                memColors[i] = colors[r.nextInt(6)];
            }
            */
            String memColor1 = "red";
            String memColor2 = "black";
            String memColor3 = "yellow";
            String memColor4 = "green";
            String memColor5 = "blue";
            boolean incorrect = false;

            //If answered incorrectly set count to 5(it'll be 6)
            //And have a boolean for if count== 6 for congrats and failure
            if(e.getSource() == txtName)
            {
                answer = txtName.getText();
                System.out.println(answer);
            }
            else
            {}     
            //Check if user entered Correct color, 1= Red, 2= Black, etc.
            if(count == 1)
            {
                if(answer.equalsIgnoreCase(memColor1))
                {
                    txtName.setText("");                
                }
                else
                {//Needs to be a custom message box
                    count = 5;
                    incorrect = true;
                }                
             }
            else if(count == 2)
            {
                if(answer.equalsIgnoreCase(memColor2))
                {
                    txtName.setText("");       
                }
                else
                {                  
                    count = 5;
                    incorrect = true;
                }                
            }            
            else if(count == 3)
            {
                if(answer.equalsIgnoreCase(memColor3))
                {
                    txtName.setText("");                
                }
                else
                { 
                    count = 5;
                    incorrect = true;
                } 
            }
            else if(count == 4)
            {
                if(answer.equalsIgnoreCase(memColor4))
                {
                    txtName.setText("");                
                }
                else
                {
                    count = 5;
                    incorrect = true;
                }
            }
            else if(count == 5)
            {
                if(answer.equalsIgnoreCase(memColor5))
                {
                    txtName.setText("");

                }
                else
                {
                    count = 5;
                    incorrect = true;
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Something went wrong!");
            }            

            count += 1;
            //User has completed the game or entered a color incorrectly
            if(count == 6)
            {

                if(incorrect == true) //Incorrect color
                {                    
                    txtName.setEnabled(false);
                    homeScreen.remove(txtName);
                    labelName.setText("Incorrect! Sorry - Wrong color.");
                    //txtName.removeActionListener(new MyButtonListener());
                }
                else //Completed the game correctly
                {
                    labelName.setText("Congratulations - your memory skills are perfect!");
                    //txtName.removeActionListener(new MyButtonListener());
                    homeScreen.remove(txtName);
                }
            }
            else
            {
                labelName.setText("Enter the color " + count + ":");
            }              
        }//End Listener        
    }//End Button class

        public static void main(String[] args) {       

        //Show message box
        //Randomize colors
        JOptionPane.showMessageDialog(null, "How good is your memory?\nTry to memorize this color sequence:\n\n red black yellow green blue");

        MemoryGame mem = new MemoryGame();        
        mem.MemoryGame();        
    }//End Main
}// End Class

【问题讨论】:

  • 尝试使用txtName.setVisible(false); 而不是homeScreen.remove(txtName);

标签: java jtextfield dialog


【解决方案1】:

使用txtName.setVisible(false); 而不是homeScreen.remove(txtName);

基本上,如果你想调用remove,你需要revalidaterepaint容器...

您还需要确保您的 UI 是在事件调度线程的上下文中创建的,有关更多详细信息,请参阅 Initial Threads

【讨论】:

  • 谢谢,成功了!我不明白 Event Dispatching Thread 的上下文是什么,但我会从该链接中进一步了解它。
【解决方案2】:

修改代码

homeScreen.remove(txtName);

homeScreen.remove(txtName);
homeScreen.revalidate();
homeScreen.repaint();

remove() 不暗示revalidate() + repaint() 的原因是remove() 不是原子的。调用者可能想要执行多个更新,即多个add()remove() 调用的序列。 revalidate() 基本上“完成”了你的“UI 更新事务”,repaint()“把它推到屏幕上”。

附带说明一下,如果您对变量名进行微小的改进,您的代码将更易于理解和维护。 homeScreen 是什么?为什么叫labelName - 什么名字?什么是txtName - 什么文字的名称? count 什么,冰淇淋?

我建议以下改进:

  • incorrect -> isIncorrect(也将 if (incorrect == true) 更改为 if (isIncorrect)
  • homeScreen -> mainFrame 或只是 frame(因为你只有一帧)
  • labelName -> infoLabel 或只是 label(因为你只有一个标签 - 并删除 JLabel correct,它是未使用的)
  • txtName -> answerTextField
  • count -> answerCount

移除变量listen1,它没有被使用。

另外,如果您查看执行if (count == 1) 和以下四个if 子句的代码,除了数字之外,它们都是相同的。阵列的完美情况。您可以将变量memColor* 转换为数组String[] memColor。或许这就是 Vector 的用途。你可能想改用ArrayList,现在在这种情况下没有人使用Vector

【讨论】:

  • 非常感谢您浏览我的整个代码并指出我可以改进的地方并解释重新验证和重新绘制方法!我目前正在使用这些更新修复我的代码。我曾计划将 memColor 设为一个数组,但我没想过将 if 语句作为一个数组。谢谢!
猜你喜欢
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
相关资源
最近更新 更多