1

I have two frames with contents . The first one has a jlabel and jbutton which when it is clicked it will open a new frame. I need to repaint the first frame or the panel that has the label by adding another jlabel to it when the second frame is closed.

//Edited

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;


    public class FirstFrame extends JPanel implements KeyListener{

        private static String command[];
        private static JButton ok;
        private static int count = 1;
        private static JTextField text;
        private static JLabel labels[];
        private static JPanel p ;
        private static JFrame frame;

        public int getCount(){
            return count;
        }
        public static void createWindow(){
            JFrame createFrame = new JFrame();
            JPanel panel = new JPanel(new GridLayout(2,1));
            text = new JTextField (30);
            ok = new JButton ("Add");
            ok.requestFocusInWindow();
            ok.setFocusable(true);
            panel.add(text);
            panel.add(ok);
            text.setFocusable(true);
            text.addKeyListener(new FirstFrame());
            createFrame.add(panel);
            createFrame.setVisible(true);
            createFrame.setSize(600,300);
            createFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            createFrame.setLocationRelativeTo(null);

            createFrame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent windowEvent) {
                        System.out.println(command[count]);
                        if(command[count] != null){

                            p.add(new JLabel("NEW LABEL"));
                            p.revalidate();
                            p.repaint();
                            count++;
                            System.out.println(count);
                        }


                    }
                });
            if(count >= command.length)
                count = 1;


            ok.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    if(command[count] == null)
                        command[count] = text.getText();
                    else
                        command[count] = command[count]+", "+text.getText();


                    text.setText("");



                }
            });
        }
        public FirstFrame(){
            p = new JPanel();
            JButton create = new JButton ("CREATE");
            command = new String[2];    
            labels = new JLabel[2];
            addKeyListener(this);
            create.setPreferredSize(new Dimension(200,100));
            //setLayout(new BorderLayout());    
            p.add(new JLabel("dsafsaf"));
            p.add(create);
            add(p);
            //JPanel mainPanel = new JPanel();
            /*mainPanel.setFocusable(false);
            mainPanel.add(create);
            */

            create.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    createWindow();
                }
            });

            //add(mainPanel, BorderLayout.SOUTH);
        }
        public static void main(String[] args) {
            frame = new JFrame();
            frame.add(new FirstFrame());        
            frame.setVisible(true);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }
        @Override
        public void keyTyped(KeyEvent e) {


        }
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER)
                if(ok.isDisplayable()){
                    ok.doClick();
                    return;}


                  }
                 }          
                }
            });
        }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
aNNgeL0
  • 57
  • 1
  • 7
  • 1
    1) Your code won't compile or run for us. 2) Your code formatting is a bit crazy with indentations all over the place making it hard to read. 3) Your question is not clear to me. What is this code not doing that it's supposed to be doing? 4) Where do you even create your FirstFrame above? You're creating a regular JFrame in your main method, not a FirstFrame. 4) You don't want two JFrames but rather the second window should probably be a JDialog: [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice) – Hovercraft Full Of Eels May 24 '15 at 11:38
  • 5) You're using a `mainPanel` variable one that is neither declared nor initialized in the code above. – Hovercraft Full Of Eels May 24 '15 at 11:41
  • My code has over 1k lines. I posted just the part that is not working – aNNgeL0 May 24 '15 at 11:44
  • 1
    Please post code that is understandable and that demonstrates your problem. What you've posted is, to be blunt, nonsense. How can we guess what might not be working correctly if we can't understand the code? We can much better help if we can run the code and experience the problem for ourselves. – Hovercraft Full Of Eels May 24 '15 at 11:45
  • For instance, it looks like all you're trying to do is to change the text in a JLabel -- if so, you shouldn't be adding a new JLabel, nor should you be calling `repaint()`. Again please clarify the problem. – Hovercraft Full Of Eels May 24 '15 at 11:48
  • Consider using a modal dialog. See [How to Make Dialogs](http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html) – MadProgrammer May 24 '15 at 11:54
  • I edited my post. I want to add a new jlabel next to the button of the first frame – aNNgeL0 May 24 '15 at 12:11
  • 1
    Thanks. Don't add a KeyListener to your JTextField. Add an ActionListener to it since you're listening for the enter key press. – Hovercraft Full Of Eels May 24 '15 at 12:14
  • By mistake. How can i listen to enter key press with an ActionListener ? I Really dont understand why is not working ... i have done this in an other small class and it works perfectly – aNNgeL0 May 24 '15 at 12:20

1 Answers1

1

As per my first comment, you're better off using a dialog of some type, and likely something as simple as a JOptionPane. For instance in the code below, I create a new JLabel with the text in a JTextField that's held by a JOptionPane, and then add it to the original GUI:

import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class FirstPanel2 extends JPanel {
   private static final int PREF_W = 600;
   private static final int PREF_H = 300;
   private JTextField textField = new JTextField("Hovercraft rules!", 30);
   private int count = 0;

   public FirstPanel2() {
      AddAction addAction = new AddAction();
      textField.setAction(addAction);

      add(textField);
      add(new JButton(addAction));
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class AddAction extends AbstractAction {
      public AddAction() {
         super("Add");
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         String text = textField.getText();
         final JTextField someField = new JTextField(text, 10);
         JPanel panel = new JPanel();
         panel.add(someField);
         int result = JOptionPane.showConfirmDialog(FirstPanel2.this, panel, "Add Label",
               JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
         if (result == JOptionPane.OK_OPTION) {
            JLabel label = new JLabel(someField.getText());
            FirstPanel2.this.add(label);
            FirstPanel2.this.revalidate();
            FirstPanel2.this.repaint();
         }
      }
   }

   private static void createAndShowGui() {
      FirstPanel2 mainPanel = new FirstPanel2();

      JFrame frame = new JFrame("My Gui");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Also, don't add KeyListeners to text components as that is a dangerous and unnecessary thing to do. Here you're much better off adding an ActionListener, or as in my code above, an Action, so that it will perform an action when the enter key is pressed.


Edit
You ask:

Just realized it is because of the KeyListener. Can you explain please the addAction ?

This is functionally similar to adding an ActionListener to a JTextField, so that when you press enter the actionPerformed(...) method will be called, exactly the same as if you pressed a JButton and activated its ActionListener or Action. An Action is like an "ActionListener" on steroids. It not only behaves as an ActionListener, but it can also give the button its text, its icon and other properties.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373