JTextField不会完全消失

时间:2014-12-03 04:18:26

标签: java jtextfield dialog

我创建了一个对话框,让用户在内存中输入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

2 个答案:

答案 0 :(得分:1)

使用txtName.setVisible(false);代替homeScreen.remove(txtName);

基本上,如果您想致电remove,则需要revalidaterepaint容器......

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

答案 1 :(得分:1)

更改代码

homeScreen.remove(txtName);

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

remove()不暗示revalidate() + repaint()的原因是remove()不是原子的。呼叫者可能希望执行多个更新,即多个add()remove()呼叫的序列。 revalidate()基本上“完成”您的“用户更新交易”,repaint()“将其推送到屏幕”。

作为旁注,如果对变量名执行一些微小的改进,您的代码将更容易理解和维护。什么是homeScreen?为什么称它为labelName - 什么名字?什么是txtName - 什么文字的名称? count什么,冰淇淋?

我建议进行以下改进:

  • incorrect - &gt; isIncorrect(也将if (incorrect == true)更改为if (isIncorrect)
  • homeScreen - &gt; mainFrame或仅frame(因为您只有一个框架)
  • labelName - &gt; infoLabel或仅label(因为您只有一个标签 - 并删除JLabel correct,它未被使用)
  • txtName - &gt; answerTextField
  • count - &gt; answerCount

删除变量listen1,但未使用它。

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