-1

I have write a test with two class. The first JPanel, Gestion: JFrame with jlist + button (the button open the Jlist 2, PanelTest) The second JPanel, PanelTest: JFrame and I want to recover in String, the select value item in the JFrame Gestion (JList)

How to do that ?

Gestion.java:

package IHM;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.List;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JList;
import javax.swing.JButton;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;

public class Gestion extends JFrame {
    private DocumentListener myListener;
    public String test;
    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Gestion frame = new Gestion();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public String getTest() {
        return test;
    }


    /**
     * Create the frame.
     * @throws Exception 
     */
    public Gestion() throws Exception {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        final PanelTest panel2 = new PanelTest();

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);

        String choix[] = {" Pierre", " Paul", " Jacques", " Lou", " Marie"};
        final JList list = new JList(choix);
        panel.add(list);

        list.addListSelectionListener(new ListSelectionListener() {
               public void valueChanged(ListSelectionEvent arg0) {
                    test = (String) list.getSelectedValue();
                    System.out.println(test);
                   // PanelTest.setValue(test);
                }
             });



        JPanel panel_1 = new JPanel();
        contentPane.add(panel_1, BorderLayout.SOUTH);

        JButton btnNewButton = new JButton("New button");
        btnNewButton.addActionListener(new ActionListener()  {
            @Override
            public void actionPerformed(ActionEvent e) {
                new PanelTest().setVisible(true);   
                fermerFenetre();

            }

        });


        panel_1.add(btnNewButton);



    }

    public void fermerFenetre(){
           this.setVisible(false);
          }


}

PanelTest.java

package IHM;

import java.awt.BorderLayout;

public class PanelTest extends JFrame {
    public String tyty;
    private JPanel contentPane;
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    PanelTest frame = new PanelTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public PanelTest() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        textField = new JTextField();
        contentPane.add(textField, BorderLayout.WEST);
        textField.setColumns(10);



    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

1

Suggestions:

  • Make your list variable a field, not a local variable, or else make it a final local variable so that it is accessible inside of the anonymous ActionListener.
  • Obtain the selected list item in your ActionListener where you launch the 2nd window.
  • Pass that String into your PanelTest object via a String parameter.
  • The second window should be a dialog such as a JDialog, not a JFrame.
  • As an aside, you'll rarely want to have your GUI classes extend top level windows such as JFrames or JDialogs as that greatly limits the flexibility of your GUI code.

For example,

import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class Gestion2 extends JPanel {
   private static final String CHOIX[] = { " Pierre", " Paul", " Jacques",
         " Lou", " Marie" };
   private JList<String> choixList = new JList<>(CHOIX);

   public Gestion2() {
      JPanel listPanel = new JPanel();
      listPanel.add(new JScrollPane(choixList));

      JPanel btnPanel = new JPanel();
      btnPanel.add(new JButton(new ListSelectAction("Select Item and Press")));

      setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
      add(listPanel);
      add(btnPanel);
   }

   private class ListSelectAction extends AbstractAction {
      public ListSelectAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         String selectedItem = choixList.getSelectedValue();
         if (selectedItem != null) {
            PanelTest2 panelTest2 = new PanelTest2(selectedItem);

            Component component = (Component) e.getSource();
            Window win = SwingUtilities.getWindowAncestor(component);

            // JOptionPane example
            JOptionPane.showMessageDialog(win, panelTest2,
                  "JOptionPane Example", JOptionPane.PLAIN_MESSAGE);

            // or JDialog example
            JDialog dialog = new JDialog(win, "JDialog Example",
                  ModalityType.APPLICATION_MODAL);
            dialog.add(panelTest2);
            dialog.pack();
            dialog.setLocationRelativeTo(win);
            dialog.setVisible(true);
         }
      }
   }

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

      JFrame frame = new JFrame("Gestion2");
      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();
         }
      });
   }
}

@SuppressWarnings("serial")
class PanelTest2 extends JPanel {

   private String selectedItem;
   private JTextField textField = new JTextField(10);

   public PanelTest2(String selectedItem) {
      this.selectedItem = selectedItem;
      textField.setText(selectedItem);
      add(new JLabel("Selected Item:"));
      add(textField);
   }

   public String getSelectedItem() {
      return selectedItem;
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks for you help Hovercraft Full Of Eels, but i would like to use 2 JFrame. Is it possible to do that ? Nikolas – Nicolas LEFEBVRE Jan 14 '15 at 14:20
  • @NicolasLEFEBVRE: yes, just shove the JPanel into a JFrame, but why would you want to do that? It makes little sense to have more than one main application window. – Hovercraft Full Of Eels Jan 14 '15 at 14:42
  • @NicolasLEFEBVRE: please check out [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice) for more details on this issue. – Hovercraft Full Of Eels Jan 14 '15 at 14:57
  • 1
    I would like advice from you: I use eclipse luna with database HSQLDB. I'm beginner in java. I use design pattern MVC. I have 4 table in HSQLDB with foreign key and primary key. When I select an item in Jlist(or more item) department, I update Jlist Course...When I select an item in Courses, I update Jlist Student...: department -> Courses -> Student -> Grade sheet of courses..In each JFrame with JList, I have two button, Add and delete. In the last JFrame Grade sheet of courses, I can calculate the average of the student and I have a button to offset the overall average. how would you do you – Nicolas LEFEBVRE Jan 14 '15 at 15:45
  • @NicolasLEFEBVRE: your comment above looks like a new question, and so perhaps should be asked as a [new StackOverflow question](http://stackoverflow.com/questions/ask). – Hovercraft Full Of Eels Jan 14 '15 at 17:14
  • Is it possible to have the code with two JFrame with my code example ? – Nicolas LEFEBVRE Jan 15 '15 at 07:36
  • @NicolasLEFEBVRE: yes it's possible, and I'm going to ask that you be the one to try to do this, at least first. Please understand that you've now had several Swing coding experts explain to you that it's a bad idea to use two JFrames. There may be exceptions to this, but you've yet to explain to us why you want to go this route. Why? Why not tell us why your code structure demands this bad design? Secondly, I've given you quite a bit of example code at considerable effort. If you wish to try to modify it, by all means, please go ahead, but please don't beg for more code. .... continued – Hovercraft Full Of Eels Jan 15 '15 at 11:35
  • @NicolasLEFEBVRE: .... this is your project and the onus of effort expended for this project should be yours. So if you wish to experiment with the ideas of others, by all means, go ahead, and if your code does not succeed, then definitely ask a new question on this site about the problems that you're having with your code, but **please** don't ask others to do your coding for you. – Hovercraft Full Of Eels Jan 15 '15 at 11:37
  • 1/ I am not a beggar 2/ I do not want others to program my place because I like programming but I ask for help 3/ I asked a specific question, I expect an accurate answer 4/ If you do not want to answer my question, does not respond 5/ It's just a little question in Java 6/ Please go ahead, If you are not a teaching skills, does not respond to user questions: Have a nice day. – Nicolas LEFEBVRE Jan 16 '15 at 11:06
  • @NicolasLEFEBVRE: what is a teacher supposed to do with a student who refuses to listen? Explain that to me please? We are telling you -- don't use two JFrames and have given you good rationale why this is so. You've offered no *programming-related reasons* for why you insist on doing things wrong, so as a teacher, I'm going to stick to my guns and again state, please try to believe what we teach, but if you wish to be stubborn and not listen, then perhaps you should consider another career. – Hovercraft Full Of Eels Jan 16 '15 at 18:59