user6145254
user6145254

Reputation:

Make JFrame not recreating again every time i press button

I created button with it's listener and then i press button it opens my specified JFrame. The problem is that then i close that JFrame and click button second time to reopen JFrame again it's creating my JFrame all over again. Can someone explain how to avoid this kind of situation?

(What i want is that every time i reopen my JFrame on button click it just continuous from there i left my JFrame, not just recreating it over and over again )

P.S. My code if someone is interested in.It's very simple. Here as you can see is my button listener and then i press it it create JFrame as i told before. I just added this code for someone who is interested in Java and want more explanation. But my main problem is stated above :)

         b2.addActionListener(new ActionListener() {             
        JTextField molecname = new JTextField("Molecule name", 20);
        Connection conn = null;
        ResultSet resultSet;            
        SwingJList<String> myJList2;
        Statement stat;
        JButton searchButton = new JButton("Search");
        JScrollPane listScrollPane;
        JSplitPane splitPane;
        JPanel searchPane;
        GridLayout searchPane2;
        JList list;
        JLabel molLabel; 
        @Override
        public void actionPerformed(ActionEvent event) {
            molLabel = new JLabel("Molecule name:");
            molecname.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    molecname.setText("");
                }
            });
            try {
                conn = DriverManager.getConnection(db.getMolecule().getDBLink(), props);
                if (conn != null) {
                    DatabaseMetaData metadata = conn.getMetaData();
                    List<String[]> sqltable = new ArrayList<>();
                    try {
                        String[] types = {"TABLE"};
                        resultSet = metadata.getTables(null, null, "%", types);
                        while (resultSet.next()) {
                            //tableName = resultSet.getString(3);
                            tableName = (tableName == null) ? resultSet.getString(3) : tableName + "." + resultSet.getString(3);
                            //sqltable.add(new String[]{tableName});                                 
                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(JFDatabase.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    for (String[] tablename : sqltable) {
                        System.out.println(Arrays.toString(tablename));
                        System.out.println(Arrays.asList(tablename));
                    }
                    String[] LIST_DATA4 = tableName.split(Pattern.quote("."));

                    myJList2 = new SwingJList<>(Arrays.asList(LIST_DATA4));
                    myJList2.addListSelectionListener((ListSelectionEvent e2) -> {

                        if (!e2.getValueIsAdjusting()) {
                            String selectedName = myJList2.getSelectedValue();
                            molecname.setText(selectedName);
                        }
                    });

                    stat = conn.createStatement();
                    searchButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent event) {
                            molecname.getText();
                            String molname1 = molecname.getText();
                            props.put("molname", molname1);
                            try {
                                String[] types = {"TABLE"};
                                ResultSet resultSet = metadata.getTables(null, null, molname1, types);
                                if (resultSet.next()) {
                                    System.out.println("Egzistuoja");
                                    ResultSet resset = stat.executeQuery("SELECT * FROM " + molname1 + "");
                                    ResultSetMetaData metadata = resset.getMetaData();
                                    int columnCount = metadata.getColumnCount();
                                    System.out.println("Table columns :  ");
                                    for (int i = 1; i <= columnCount; i++) {
                                        String columnName = metadata.getColumnName(i);
                                        System.out.println(columnName);
                                    }
                                }

                            } catch (SQLException ex) {
                                Logger.getLogger(JFDatabase.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            frame2.dispose();
                        }

                    });

                    list = new JList(sqltable.toArray());
                    list.setCellRenderer(f);

                    listScrollPane = new JScrollPane(myJList2);
                    listScrollPane.setPreferredSize(new Dimension(250, 200));
                    listScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "List", TitledBorder.CENTER, TitledBorder.TOP));
                    searchPane = new JPanel();
                    searchPane2 = new GridLayout(15, 3);
                    searchPane.setLayout(searchPane2);
                    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane, searchPane);

                    searchPane.add(molLabel);
                    searchPane.add(molecname);
                    searchPane.add(searchButton);

                    frame2.add(splitPane);
                    frame2.pack();
                    frame2.setLocationRelativeTo(null);
                    frame2.setVisible(true);

                    JOptionPane.showMessageDialog(null,
                            "Database connected",
                            "Warning", JOptionPane.INFORMATION_MESSAGE);
                    System.out.println("You made it, take control your database now!");
                } else {
                    JOptionPane.showMessageDialog(null,
                            "Database connection not avaible",
                            "Warning", JOptionPane.WARNING_MESSAGE);
                    System.out.println("Failed to make connection!");
                }
            } catch (SQLException e3) {
                JOptionPane.showMessageDialog(null,
                        "Database connection not avaible",
                        "Warning", JOptionPane.WARNING_MESSAGE);
                System.err.print(e3);
            }


        }
    });

Upvotes: 1

Views: 95

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

Observations:

  • Your main question is wrong -- your problem is not that you're creating a new JFrame with each run through this listener because you are most definitely NOT creating a new JFrame each time this listener is called.
  • Instead you're creating a new JSplitPane, shoving it with components, and adding this to an already existing JFrame,and then displaying this same old JFrame, but one that is displaying new components.
  • So what you'll need to do is not to do this.
  • I suggest that you extract this second window's code out of this class and create a new class for it, if only to re-factor your code and make it much easier to debug and enhance.
  • In this new class, build the GUI's components, add them to the main JPanel, and do this once and once only.

You state in comment:

But my varibale i am dealing on that button click will be not passed to JFrame

but this doesn't make sense. Please explain.


Regarding any data that needs to be sent to this window (or any other window)

  • Give this class methods that accept data not GUI components.
  • And make these methods smart so that they know how to add the data so that it is displayed with any existing dtat that you want to persist. This is the key critical part, where the details will be important, but which details on how you want to do this can only be known by you since you are the one who knows exactly what you are trying to display. Your current code is too long and confusing for me at least to be able to give more specific recommendations than this.
  • Then in your b2 button's listener code above you extract the data needed, pass it to the field of the class above, and then display your data-display window.

Other issues

  • First and foremost and I'm not trying to nag, but you really must re-factor this code as it is an ungodly mess, one that must be difficult for you to debug and enhance, because it sure is difficult for us to do so.
  • This includes creating a bunch of new classes to encapsulate much of this data and behavior.
  • And code that will allow you to separate all database functionality out of the GUI code.
  • Next you should take care to call database and all other long-running code off of the Swing event thread.
  • Note that sub-windows, in other words windows that are not the main GUI window but that show side information, should not be composed of JFrames but rather JDialogs, modal dialogs if you want to halt program flow in the main window when the sub-window is displayed, or non-modal if this is not true.

Upvotes: 1

Related Questions