include java text field (textfield)

Asked

Viewed 591 times

0

I want to add this text field at my game. I’ve changed the code in my game but this one text field is being opened in a new window, but I want that text field is included in the game window itself.

Just below the "settings button".

This is my game:

import java.awt.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeListener;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
import java.util.List;
import java.applet.Applet;
import java.net.*;
import java.applet.*;
import java.io.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

public class MemoryGame extends JFrame implements ActionListener
{
    ClassLoader cl = null;
    Font f; 
    TextField msg1, msg2, password,t;
    String s;
    Label mostra;           
    public int delay = 1000; //1000 milliseconds

    public void Contador()
    {
    ActionListener counter = new ActionListener() 
    {
            public void actionPerformed(ActionEvent e) 
            {
        tempo++;
        TempoScore.setText("Tempo: " + tempo);
            }
    };
    new Timer(delay, counter).start();
    }

    public void updateHitMiss() 
    {
        HitScore.setText("Acertou: " + Hit);
        MissScore.setText("Falhou: " + Miss);
    PontosScore.setText("Pontos: " + Pontos);
    }

    private JFrame window = new JFrame("Jogo da Memoria");
    private static final int WINDOW_WIDTH = 500; // pixels
    private static final int WINDOW_HEIGHT = 500; // pixels
    private JButton exitBtn, baralharBtn, solveBtn, restartBtn, maximoBtn, definicoesBtn;
    ImageIcon ButtonIcon = createImageIcon("card1.png"); //.jpg 
    private JButton[] gameBtn = new JButton[16];
    private ArrayList<Integer> gameList = new ArrayList<Integer>();
    //List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
    private int Hit, Miss, Pontos, Maximo;
    public int tempo = 0;   
    private int counter = 0;
    private int[] btnID = new int[2];
    private int[] btnValue = new int[2];
    private JLabel HitScore, MissScore, TempoScore, PontosScore, MaximoScore;
    private JPanel gamePnl = new JPanel();
    private JPanel buttonPnl = new JPanel();
    private JPanel scorePnl = new JPanel();
    private JTextArea _resultArea = new JTextArea(6, 20);

    protected static ImageIcon createImageIcon(String path) 
    {
        java.net.URL imgURL = MemoryGame.class.getResource(path);
        if (imgURL != null) 
    {
            return new ImageIcon(imgURL);
        } 
    else  return null;
    }

    public MemoryGame()
    {
        createGUI();
        createJPanels();
        setArrayListText();
        window.setTitle("Jogo da Memoria");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        window.setVisible(true);
        Contador();

        //... Set textarea's initial text, scrolling, and border.
        _resultArea.setText("\n");
        JScrollPane scrollingArea = new JScrollPane(_resultArea);

        //... Get the content pane, set layout, add to center
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(scrollingArea, BorderLayout.SOUTH);

        //... Set window characteristics.
        this.setContentPane(content);
        //this.setTitle("TextAreaDemo B");
        //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
    }

    public void createGUI()
    {
        for (int i = 0; i < gameBtn.length; i++)
        {
            gameBtn[i] = new JButton(ButtonIcon);
            gameBtn[i].addActionListener(this);
        }
        HitScore = new JLabel("Acertou: " + Hit);
        MissScore = new JLabel("Falhou: " + Miss);
    TempoScore = new JLabel("Tempo: " + tempo);
    PontosScore = new JLabel("Pontos: " + Pontos);  
        exitBtn = new JButton("Sair");
        exitBtn.addActionListener(this);
        baralharBtn = new JButton("Baralhar");
        baralharBtn.addActionListener(this);
        solveBtn = new JButton("Resolver");
        solveBtn.addActionListener(this);
    restartBtn = new JButton("Recomecar");
        restartBtn.addActionListener(this);
    maximoBtn = new JButton("Pontuacoes");
        maximoBtn.addActionListener(this);
    definicoesBtn = new JButton("Definicoes");
        definicoesBtn.addActionListener(this);

        //... Set textarea's initial text, scrolling, and border.
        _resultArea.setText("\n");
        JScrollPane scrollingArea = new JScrollPane(_resultArea);

        //... Get the content pane, set layout, add to center
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(scrollingArea, BorderLayout.SOUTH);

        //... Set window characteristics.
        this.setContentPane(content);
        //this.setTitle("TextAreaDemo B");
        //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
    }

    public void createJPanels()
    {
        gamePnl.setLayout(new GridLayout(4, 4));
        for (int i = 0; i < gameBtn.length; i++)
        {
            gamePnl.add(gameBtn[i]);
        }
        buttonPnl.add(baralharBtn);
        buttonPnl.add(exitBtn);
        buttonPnl.add(solveBtn);
    buttonPnl.add(restartBtn);
    buttonPnl.add(maximoBtn);
    buttonPnl.add(definicoesBtn);
        buttonPnl.setLayout(new GridLayout(2, 1));
        scorePnl.add(HitScore);
        scorePnl.add(MissScore);
    scorePnl.add(TempoScore);
    scorePnl.add(PontosScore);
        scorePnl.setLayout(new GridLayout(1, 0));
        window.add(scorePnl, BorderLayout.NORTH);
        window.add(gamePnl, BorderLayout.CENTER);
        window.add(buttonPnl, BorderLayout.SOUTH);

    }

    public void setArrayListText() // gera numeros aleatorios
    { 
    List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
    Collections.shuffle(lista);
    gameList.addAll(lista);
    }

    public boolean sameValues()
    {
        if (btnValue[0] == btnValue[1])
        {
            return true;
        }
        return false;
    }

    public void pass() 
    {
        s = "123";
        msg1 = new TextField("Digite a password:"); msg1.setEditable(false);
        password = new TextField(12); password.setEchoCharacter('*');
        msg2 = new TextField(30); msg2.setEditable(false);
        add(msg1); add(password); add(msg2);
    }
    /*
    public boolean action(Event e, Object o) 
    {
            if (e.target instanceof TextField)
            if (e.target ==password)
            if (e.arg.equals(s)) msg2.setText("Acesso permitido");
            else msg2.setText("Password invalida.");
            return true;
    } */
    /*
    class EscutaJanela extends WindowAdapter
    {
            public void windowClosing(WindowEvent e) 
            setVisible(true);
            dispose();
    }
    */

    public void actionPerformed(ActionEvent e)
    {
        if (exitBtn == e.getSource())
        {
            System.exit(0);
        }

        if (baralharBtn == e.getSource())
        {
            List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
            Collections.shuffle(lista);
            gameList.addAll(lista);
        }

        if (solveBtn == e.getSource())
        {
            for (int i = 0; i < gameBtn.length; i++)
            {   // enable false, ao clicar, não modifica o aspecto(cor) da quadricula,
        gameBtn[i].setEnabled(false); // enabled false-> cor cinzenta(padrão de fundo), true azul                
        gameBtn[i].setVisible(true); // visible true-> fica nºs visiveis
                gameBtn[i].setText("" + gameList.get(i));       
            }
        }

        for (int i = 0; i < gameBtn.length; i++)
        {           
            if (gameBtn[i] == e.getSource())
            {
                gameBtn[i].setText("" + gameList.get(i));
                gameBtn[i].setEnabled(false);
                counter++;

        if(Hit==7)
        {
                    if (counter == 2)
                    {
            gameBtn[btnID[0]].setEnabled(false);
            gameBtn[btnID[1]].setEnabled(false);
            gameBtn[btnID[0]].setVisible(false);
            gameBtn[btnID[1]].setVisible(false);
            Hit = Hit +1;
            Pontos = Pontos + 25;
                    }                   
        }

        if(Hit==8)
        {  
                    int PontuacaoMax=0;
                    PontuacaoMax=Pontos;
                    window = new JFrame(" FIM DO JOGO ");           
                    JLabel label3 = new JLabel("\n PARABENS FINALIZOU O JOGO ! TOTAL DE PONTOS: "+PontuacaoMax);    
                    int[] anArray;
                    int w=0;
                    int h=1;
                    anArray = new int[20];
                    anArray[w] = PontuacaoMax;  
                    System.out.printf("Jogo %d,",h);
                    System.out.println(" Pontuacao final : "+PontuacaoMax);
                    w++;h++;
                    window.add("Center", label3);               
                    window.show();                      
                    ImageIcon img = new ImageIcon("C:\\Users\\bruno.azevedo8\\Documents\\NetBeansProjects\\Jogo_Memoria\\resources\\fogo.jpg");
                    JLabel label = new JLabel(img);
                    window.add(label, BorderLayout.NORTH);
                    window.pack();  
                    window.setVisible(true); 
                    gameBtn[btnID[0]].setEnabled(false);
                    gameBtn[btnID[1]].setEnabled(false);
                    gameBtn[btnID[0]].setVisible(true);
                    gameBtn[btnID[1]].setVisible(true);
                    cl = getClass().getClassLoader();
                    //AudioClip audio = Applet.newAudioClip(cl.getResource("C:\\Users\\bruno.azevedo8\\Documents\\NetBeansProjects\\Memoria\\Jogo_Memoria\\resources\\bottle-open.wav"));
                    //audio.play();                 
                }

                if (counter == 3)
                {               
                    if (sameValues())
                    {
                        gameBtn[btnID[0]].setEnabled(false);
                        gameBtn[btnID[1]].setEnabled(false);
                        gameBtn[btnID[0]].setVisible(true);
                        gameBtn[btnID[1]].setVisible(true);
                        Hit = Hit +1;
                        Pontos = Pontos + 25;
                    }
                    else
                    {
                        gameBtn[btnID[0]].setEnabled(true);
                        gameBtn[btnID[0]].setText("");
                        gameBtn[btnID[1]].setEnabled(true);
                        gameBtn[btnID[1]].setText("");
                        Miss = Miss +1;
                        Pontos = Pontos - 5;                       
                    }
                    counter = 1; 
                }
                /*if (Pontos <= 0)
                {
                        Pontos=0;
                } */
                if (counter == 1) // na grelha identifica o 1º clique do rato
                {
                    btnID[0] = i;
                    btnValue[0] = gameList.get(i);
                }
                if (counter == 2) // na grelha identifica o 2º clique do rato(diferente do 1º)
                {
                    btnID[1] = i;
                    btnValue[1] = gameList.get(i);
                }
            }
        }

    if (restartBtn == e.getSource()) // apaga a grelha
        { 
            Hit=0;
            Miss=0;
            tempo=-1;
            Pontos=0;
            for (int i = 0; i < gameBtn.length; i++)
            {
                gameBtn[i].setText("");
                gameBtn[i].setEnabled(true);
                gameBtn[i].setVisible(true);    
            }
        }  

    if (maximoBtn == e.getSource()) //mostra melhor pontucao
        {
            window = new JFrame(" Jogo da Memoria - Melhores Pontuacoes:"); 
            int Max=0,PontuacaoMax=0;           

            //private static int maxValue(char[] chars) 
            //{
                //int  = chars[0]; 
                /*
                int[] anArray;
                anArray = new int[20];
                for (int w = 0; w < anArray.length; w++) 
                {
                    if (anArray[w]>= Max) 
                    {
                        Max = anArray[w];
                        JLabel label2 = new JLabel(" Pontuacao Maxima: "+Max);
                        window.add("Center", label2);
                    }
                }

                System.out.println(PontuacaoMax);
                JLabel label5 = new JLabel(" Pontuacao: " +PontuacaoMax );
                window.add("Center", label5); */
                //return Pontos;
            //}
            /*
            anArray[w]=0;
            int w;
            for(w=0;w<20;w++)
            {
                if (anArray[w]>=PontuacaoMax)
                {
                    PontuacaoMax=anArray[w];
                    JLabel label2 = new JLabel(" Pontuacao Maxima: "+PontuacaoMax);
                    window.add("Center", label2);
                }
            } 
            */ 
            if (Pontos >= PontuacaoMax)
            {
                PontuacaoMax = Pontos;
                JLabel label2 = new JLabel(" Pontuacao Maxima: "+PontuacaoMax); 
                //Vector<Integer> v = new Vector<>();
                //v.add(PontuacaoMax);System.out.println(PontuacaoMax);
                window.add("Center", label2);
            }
            if (Pontos < PontuacaoMax)
            {
                PontuacaoMax = Pontos;
                JLabel label2 = new JLabel(" Pontuacao Maxima: 0");         
                window.add("Center", label2);
            }    

            window.show();                      
            ImageIcon img = new ImageIcon("C:\\Users\\bruno.azevedo8\\Documents\\NetBeansProjects\\Jogo_Memoria\\resources\\trofeu.jpg");         
            JLabel label = new JLabel(img); 
            window.add(label, BorderLayout.NORTH);
            window.pack();  
            window.setVisible(true); 
        }

    if (definicoesBtn == e.getSource()) //mostra as definicoes
        { /*
            window = new JFrame(" Jogo da Memoria - Password:");
            window.setLayout(new BorderLayout());   
            // pass(); 
            s = "123";
            msg1 = new TextField("Digite a password:"); 
            msg1.setEditable(false);
            password = new TextField(12); 
            password.setEchoCharacter('*');
            msg2 = new TextField(30); 
            msg2.setEditable(false);
            add(msg1); 
            add(password); 
            add(msg2); 

            window.resize(300,300);
            window.show();                      
            window.pack();  
            window.setVisible(true);    
            //action(e,o);  */      

            definicoesBtn.addActionListener(new ActionListener()
            {    
                public void actionPerformed(ActionEvent evento)
                {    
                    window = new JFrame(" Jogo da Memoria - Definicoes:");              
                    JLabel label3 = new JLabel("Escolha Nivel Dificuldade:");           
                    window.add("West", label3);                                     
                    ImageIcon img = new ImageIcon("C:\\Users\\bruno.azevedo8\\Documents\\NetBeansProjects\\Jogo_Memoria\\resources\\definicoes.jpg");
                    JLabel label = new JLabel(img); 
                    window.add(label, BorderLayout.NORTH);
                    JPanel panel = new JPanel(new GridLayout(0, 1));
                    ButtonGroup group = new ButtonGroup();
                    JRadioButton aRadioButton = new JRadioButton(" Facil ");
                    JRadioButton bRadioButton = new JRadioButton(" Medio ");
                    JRadioButton cRadioButton = new JRadioButton(" Dificil ");

                    ChangeListener changeListener = new ChangeListener() 
                    {
                        public void stateChanged(ChangeEvent changEvent) 
                        {
                            AbstractButton aButton = (AbstractButton)changEvent.getSource();
                            ButtonModel aModel = aButton.getModel();
                            boolean armed = aModel.isArmed();
                            boolean pressed = aModel.isPressed();
                            boolean selected = aModel.isSelected();

                            aRadioButton.addActionListener(new ActionListener()
                            {
                                public void actionPerformed(ActionEvent e) 
                                {                           
                                    gamePnl.setLayout(new GridLayout(4, 4));
                                    //System.out.println("4x4");
                                }
                            });
                            bRadioButton.addActionListener(new ActionListener()
                            {
                                public void actionPerformed(ActionEvent e) 
                                {                                       
                                    JButton[] gameBtn = new JButton[18];

                                     for (int i = 0; i < gameBtn.length; i++)
                                    {
                                        gameBtn[i] = new JButton(ButtonIcon);
                                        gameBtn[i].addActionListener(this);
                                    } 

                                    gamePnl.setLayout(new GridLayout(6, 6)); /*
                                    for (int i = 0; i < gameBtn.length; i++)
                                    {
                                            gamePnl.add(gameBtn[i]);
                                    }           */                                                  
                                }
                            });
                            cRadioButton.addActionListener(new ActionListener()
                            {
                                public void actionPerformed(ActionEvent e) 
                                {                                                                                   
                                    gamePnl.setLayout(new GridLayout(5, 5));                                                
                                }
                            });
                        }
                    };
                    panel.add(aRadioButton);
                    group.add(aRadioButton);
                    panel.add(bRadioButton);
                    group.add(bRadioButton);
                    panel.add(cRadioButton);
                    group.add(cRadioButton);
                    aRadioButton.addChangeListener(changeListener);
                    bRadioButton.addChangeListener(changeListener);
                    cRadioButton.addChangeListener(changeListener);
                    window.add(panel);                      
                    window.pack();  
                    window.setVisible(true); 
                }    
            });             
        }
        updateHitMiss();
    }

    public static void main(String[] argv)
    {      
        JFrame win = new MemoryGame();
        win.setVisible(true);
        //new MemoryGame(); */
        try 
        {
            // criação do socket TCP de ligação ao servidor, o 1º argumento
            // é o nome da máquina, o 2º é o número do porto
            Socket sd = new Socket(InetAddress.getByName(argv[0]), (new Integer(argv[1])).intValue());
            // obtenção dos canais de leitura e escrita do socket
            InputStream in = sd.getInputStream();
            OutputStream out = sd.getOutputStream();
            // criação do buffer para envio e recepção de informação
            byte[] buffer = new byte[1024];
            for (;;) 
            {
                // pede a mensagem ao utilizador
                System.out.print("Introduza a mensagem: ");
                System.out.flush();
                int length = System.in.read(buffer);
                // envia ao servidor o buffer através do outputstream
                out.write(buffer, 0, length);
                out.flush();
                // se premiu return, fecho da ligação
                if (length == 1) break;
                // leitura da mensagem ecoada pelo servidor
                length = in.read(buffer);
                System.out.println(new String(buffer,0,0,length));
            }
        } 
        catch (IOException e) 
        {
                // Surgiu algum problema com a ligação ao socket
                System.out.println(e.toString());
        }
        System.out.println("ligação fechada");

    }
}

I changed in my game the following lines: to include the textfield .

public MemoryGame()
    {
        createGUI();
        createJPanels();
        setArrayListText();
        window.setTitle("Jogo da Memoria");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        window.setVisible(true);
        Contador();
        //novo codigo textfield
        //... Set textarea's initial text, scrolling, and border.
        _resultArea.setText("\n");
        JScrollPane scrollingArea = new JScrollPane(_resultArea);

        //... Get the content pane, set layout, add to center
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(scrollingArea, BorderLayout.SOUTH);

        //... Set window characteristics.
        this.setContentPane(content);
        //this.setTitle("TextAreaDemo B");
        //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
//fim novo codigo text field
    } 

What’s on a gray background.

Before that includes this line :72: private Jtextarea _resultArea = new Jtextarea(6, 20);

Also includes two more lines to my game:

public static void main(String[] argv)
    {      
        JFrame win = new MemoryGame();  // nova linha
        win.setVisible(true);           // nova linha
        //new MemoryGame(); */
       //... resto do codigo
     }

Everything else is the same, so I don’t want to open the textfield in a new window. But open along with the memory game, the textfield should be below the settings button or at least appear in that window, after that I try to put in place.

I’ve already lost an entire afternoon with text field and I can’t in any way put text field in the main game window.

  • 3

    Wow, how much code...

  • 2
  • I’ve already edited the question, I think it’s simpler to understand the problem.

  • Try to be more specific, there’s a lot of code to analyze, few here will try to help you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.