0

Im currently working on an aplication on Eclipse and what I need is to press a button and then a JFrame to open, containing values from MySQL DB on a JTable. I had recently asked a question here about an error I had in trying to show columns using absolute layout(null layout) and I was told that it would be preferable to use layouts. The thing is that i have multiple buttons and stuff on my existing form and changing the layout would hide some of the features and I couldn't find a solution.So I thought of something. Since the JTable has issues with absolute layout and Layout Managers dont help me with my multiple buttons, I could delete the JTable from my existing form(null layout) and keep the buttons. As a result, when a user presses the "Sort by Name" or "Add Console" buttons I have for mySQL app on the existing form, then a new JFrame should pop up and show the correct JTable. Is there a possible way to do that?

JTable Creation Process :

 package newWindow;

  import java.awt.*;
  import java.sql.*;
  import javax.swing.*;
  import javax.swing.table.*;

 public class newWindow {

 public static void main(String[] args) {
    new newWindow();
   }

 public newWindow() {
   EventQueue.invokeLater(new Runnable() {
       @Override
         public void run() {
           try {
 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {}

  try
  {
  Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=mySQL&password=7777");
  Statement stmt = conn.createStatement();
  ResultSet rs = stmt.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
  ResultSetMetaData md = rs.getMetaData();
  int columnCount = md.getColumnCount();
  String[] cols = new String[columnCount];
  int i;
  for (i=1;i<= columnCount;i++)
   {
     cols[i-1] = md.getColumnName(i);
   }
   DefaultTableModel model = new DefaultTableModel(cols,0);
     while (rs.next())
       {
         Object[] row = new Object[columnCount];
             for (i = 1 ; i <= columnCount ; i++)
                 {
                   row[i-1] = rs.getObject(i);
                 }
      model.addRow(row);
        }
   JFrame frame = new JFrame("Promitheas");
   JTable table = new JTable(model);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().setLayout(new GridLayout());
   JScrollPane scrollPane = new JScrollPane(table);
   frame.getContentPane().add(scrollPane);
   frame.pack();
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
   conn.close();
   stmt.close();
   rs.close();
  } catch (SQLException case1) { case1.printStackTrace();
  } catch (Exception case2) { case2.printStackTrace();}               
    }
  });
 }
}

Sort by Name Button :

try{
   conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=mySQL&password=7777");
   String[] gender = { "ASC", "DESC"};
   int response = JOptionPane.showOptionDialog(null,"Ascending or Descending Order?","Make a choice...",0,JOptionPane.INFORMATION_MESSAGE,null,gender,gender[0]);
   stmtsortname = conn.createStatement();
   String sql = null;
   if (response == JOptionPane.YES_OPTION)
        sql = "ASC";
   if (response == JOptionPane.NO_OPTION)
        sql = "DESC";
  rssortname = stmtsortname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id ORDER BY consoles.name "+sql);
                              .
                              .
                              . 
             create an newJTable overwriting the old
                              .
                              .
 } catch ...  
vagg77
  • 97
  • 2
  • 15
  • Using nested layoutmanagers is always what you should do. You just have to play around with adding new panels (with other layouts) to each location in the top layout. Example: Borderlayout with a FlowLayout in the WEST location for buttons and using the CENTER position for the JTable. – Xabster Aug 06 '14 at 10:34
  • 1. probably in this case is better talking about side effect, than..., 2. questions about JTable are most frequently asked here, more that half for those questions are about JDBC & JTable 3. create JDialog, only one instance and change data in DefaultTableModel 4. rest is described in Oracle tutorial How to use Tables – mKorbel Aug 06 '14 at 10:34
  • The best solution is to fix the core problem, the layout manager, rather the trying to dance around the issue and introduce more hacks.. – MadProgrammer Aug 06 '14 at 10:40
  • never mind I figured it out....I posted id with a button "Start Table" – vagg77 Aug 06 '14 at 10:43
  • 1
    See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Aug 06 '14 at 11:25

2 Answers2

0

Make a class which takes the data you want transfered as a parameter. Do your magic setup the table and set visible true and replace blala with your logic

public class NewJFrame extends JFrame{

   public NewJFrame(Data data){
      blala
      this.setVisible(true);
   }
}

and then on the button you have the ActionListner or something simmilar in that

new NewJFrame(data);
Lars Nielsen
  • 2,005
  • 2
  • 25
  • 48
0

ANSWERED

JButton btnStartTable = new JButton("Start Table");
    btnStartTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0){
        try
    {

        conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=mySQL&password=7777");
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
        md = rs.getMetaData();
        columnCount = md.getColumnCount();
        String[] cols = new String[columnCount];
        for (i=1;i<= columnCount;i++)
         {
        cols[i-1] = md.getColumnName(i);
         }
    model = new DefaultTableModel(cols,0);
        while (rs.next())
        {
              Object[] row = new Object[columnCount];
                 for (i = 1 ; i <= columnCount ; i++)
                 {
                    row[i-1] = rs.getObject(i);
                 }
        model.addRow(row);
        }

    frame2 = new JFrame();
    frame2.setVisible(true);
    JTable table = new JTable(model);
    f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f2.getContentPane().setLayout(new GridLayout());
    JScrollPane scrollPane = new JScrollPane(table);
    f2.getContentPane().add(scrollPane);
    f2.pack();
    f2.setLocationRelativeTo(null);
    f2.setVisible(true);
    conn.close();
    stmt.close();
    rs.close();
    } catch (SQLException case1) { case1.printStackTrace();
    } catch (Exception case2) { case2.printStackTrace();}}
    });
    btnStartTable.setBounds(10, 11, 126, 23);
    frame.getContentPane().add(btnStartTable);
vagg77
  • 97
  • 2
  • 15
  • two questions why would do all that in a method, why a mouse listener? – Lars Nielsen Aug 06 '14 at 10:47
  • 1) to call the method in my program and make it 12% more readable/understandable 2)I said that I wanted to CLICK a button and open a new frame...you click the Start Button and the window pops up....as for the first im kind of starting now learning so I do a lot of things not the smart-efficient way – vagg77 Aug 06 '14 at 10:54
  • don't to create a new JFrame, create only one JDialog as local variable, add WindowListener to JDialog, override all closing events with setVisible(false), a new event from JButton to call JDBC, ResultSet fills TableModel, if success to call setVisible(true), wrapped into invokeLater ---> local variable for JDialog – mKorbel Aug 06 '14 at 11:04
  • close() resultset and connection in finally – mKorbel Aug 06 '14 at 11:04