简体   繁体   中英

Repainting a JPanel

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;}


                  }
                 }          
                }
            });
        }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM