I have been tryin to get this to work for the past week if not two >:( with no joy. Worst of all its such a trivial problem.

The program asks you to choose a town name from a combo box when you choose the location you shoud be brought to a brand new Jframe with a populated Jtable. Now everything does what its meant to do except the jframe window which opens as the border of the window and the minmise,maximise and close buttons. You can view the database by expanding the jframe window from the bottom right corner(Click and drag it open). But i cannot leave it at that extremely unprofessional.

This design issue has been the bane of my existence for the last 2 weeks.

So I ask you out of the kindness of your hearts to do one favour or another for me:

Favour 1:
Tranfer my code into a jframe I have tried this numerous times myself but it has not worked. (A bit cheeky).

Favour 2:
Give me a step by step on how to achieve favour 1?

Or if someone has a working sample of something like this could they share it with me??

Any help would be greatly appreciated

Heres my code(Java Class):

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

public class Display_All extends JFrame
{
   Object JFrame;
   Object JTable;
   Object JScrollpane;


    public Display_All(Object town)
    {
        Vector columnNames = new Vector();
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
//  Get column names


                columnNames.addElement( "Business Name" );
                columnNames.addElement( "Email" );
                columnNames.addElement( "Address 1" );
                columnNames.addElement( "Town" );
                columnNames.addElement( "Phone" );
                columnNames.addElement( "Mobile" );
                columnNames.addElement( "Web Address" );
                columnNames.addElement( "Owner" );

        try
        {
            //  Connect to an Access Database


            String driver = "com.mysql.jdbc.Driver";
            String url ="jdbc:mysql://localhost:3306/ireland";
            String userid = "root";
            String password = "pass";

            Class.forName( driver );
            Connection connection = DriverManager.getConnection( url, userid, password );

            //  Read data from a table

            String sql = "(SELECT Activities_Name, Activities_Email,Activities_Address_1, Town, Activities_Phone ,Activities_Mobile, Activities_Web_Address, Activities_Owner FROM activities WHERE Town ='"+town+"')"
                    + "UNION ALL ( SELECT Attraction_Name, Attraction_Email, Attraction_Address_1, Town, Attraction_Phone, Attraction_Mobile, Attraction_Web_Address, Attraction_Owner FROM attractions WHERE Town = '"+town+"')"
                    + "UNION ALL ( SELECT BB_Name, BB_Email, BB_Address_1 ,Town, BB_Phone, BB_Mobile, BB_Web_Address, BB_Owner FROM bb WHERE Town = '"+town+"')"
                    + "UNION ALL ( SELECT Hotel_Name ,Hotel_Email ,Hotel_Address_1, Town, Hotel_Phone, Hotel_Mobile, Hotel_Web_Address, Hotel_Owner FROM hotels WHERE Town = '"+town+"')"
                    + "UNION ALL ( SELECT Pub_Name, Pub_Email ,Pub_Address_1, Town, Pub_Phone ,Pub_Mobile, Pub_Web_Address, Pub_Owner FROM pubs WHERE Town = '"+town+"')"
                    + "UNION ALL ( SELECT Restaurant_Name, Restaurant_Email, Restaurant_Address_1, Town, Restaurant_Phone, Restaurant_Mobile, Restaurant_Web_Address, Restaurant_Owner FROM restaurant WHERE Town = '"+town+"')"
                    + "UNION ALL ( SELECT Self_Catering_Name, Self_Catering_Email, Self_Catering_Address_1, Town, Self_Catering_Phone, Self_Catering_Mobile, Self_Catering_Web_Address, Self_Catering_Owner FROM self_catering WHERE Town = '"+town+"')";


            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery( sql );
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();



            //  Get row data

            while (rs.next())
            {
                Vector row = new Vector(columns);

                for (int i = 1; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );
                }

                data.addElement( row );
            }

           rs.close();
           stmt.close();
           connection.close(); 
        }
        catch(Exception e)
        {
            System.out.println( e );

        }


        //  Create table with database data

        JTable table = new JTable(data, columnNames )
        {
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                    {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );

      JPanel buttonPanel = new JPanel();
        getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    }

  public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Display_All frame = new Display_All("town");
            frame.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
            frame.setVisible(true);
        }       
    });
}

}

Heres the search box (JFrame) code:

import com.sun.rowset.JdbcRowSetImpl;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Joe Lyons
 */
public class Search_All extends javax.swing.JFrame {

    /**
     * Creates new form Search_All
     */
    public Search_All() {

    initComponents();
     try {
             JdbcRowSetImpl rowSet = new JdbcRowSetImpl();

                rowSet.setUrl("jdbc:mysql://localhost:3306/ireland");
                rowSet.setUsername("root");
                rowSet.setPassword("MySQL5");

    rowSet.setCommand("SELECT DISTINCT Town FROM bb order by Town");
                rowSet.execute();

                while (rowSet.next()) {
                    String SA = rowSet.getString("Town");
                    townComboBox.addItem(SA);

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


    }





    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             


        searchAllResults DA = new searchAllResults(townComboBox.getSelectedItem());
     DA.setVisible(true);
     dispose();
    }                                            

 public static void main(String args[]) {
  java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Search_All().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JButton searchButton;
    private javax.swing.JComboBox townComboBox;
    // End of variables declaration
}

Thanks guys any help would be appreciated

Recommended Answers

All 7 Replies

Did you try calling pack() on your JFrame after adding all the components?

Yep no joy im afraid. I have tried changing that class around quite alot but nothing i do seem to make any difference. Its like theres an error some where thats preventing all changes from being implemented O_o. But there is nothing in the code that leads me to believe there's a serious error?

This thing is diving me insane :( especially since this isn't the hard part haha

No-one here can run your code because (a) that's not the definitive current complete version and (b) we don't have the database. Perhaps you can prepare and post a complete runnable stand-alone minimum version that someone here can run to reproduce and help fix you problem?

Cool heres a mock database :
CREATE DATABASE DB;

CREATE TABLE table1 (
    id INT,
    name VARCHAR(20),
    email VARCHAR(20),
    Location VARCHAR(20)
);
INSERT INTO table1 (id,name,email,Location) VALUES(1,"Tom","tom@yahoo.com","Ennis"); 

CREATE TABLE table2 (
    id INT,
    name VARCHAR(20),
    email VARCHAR(20),
    Location VARCHAR(20)
);
INSERT INTO table2 (id,name,email,Location) VALUES(2,"John","John@yahoo.com","Ennis"); 

CREATE TABLE table3 (
    id INT,
    name VARCHAR(20),
    email VARCHAR(20),
    Location VARCHAR(20)
);
INSERT INTO table3 (id,name,email,Location) VALUES(3,"Jack","Jack@yahoo.com","Ennis"); 

CREATE TABLE table4 (
    id INT,
    name VARCHAR(20),
    email VARCHAR(20),
    Location VARCHAR(20)
);
INSERT INTO table4 (id,name,email,Location) VALUES(5,"Martin","Martin@yahoo.com","Ennis"); 

CREATE TABLE table5 (
    id INT,
    name VARCHAR(20),
    email VARCHAR(20),
    Location VARCHAR(20)
);
INSERT INTO table5 (id,name,email,Location) VALUES(4,"Tim","Tim@yahoo.com","Ennis"); 

CREATE TABLE table6 (
    id INT,
    name VARCHAR(20),
    email VARCHAR(20),
    Location VARCHAR(20)
);
INSERT INTO table6 (id,name,email,Location) VALUES(12,"Kim","Kim@yahoo.com","Ennis"); 

------------------------------------------------------------------------------------------------------
Heres the code for the search box:

------------------------------------------------------------------------------------------------------

import com.sun.rowset.JdbcRowSetImpl;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Search_All extends javax.swing.JFrame {


    public Search_All() {

    initComponents();
     try {
             JdbcRowSetImpl rowSet = new JdbcRowSetImpl();

                rowSet.setUrl("jdbc:mysql://localhost:3306/db");
                rowSet.setUsername("root");
                rowSet.setPassword("MySQL5");

    rowSet.setCommand("SELECT DISTINCT name FROM location order by name");
                rowSet.execute();
                while (rowSet.next()) {
                    String SA = rowSet.getString("name");
                    townComboBox.addItem(SA);

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


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        townComboBox = new javax.swing.JComboBox();
        searchButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        townComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                townComboBoxActionPerformed(evt);
            }
        });

        searchButton.setText("Search");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        exitButton.setText("Exit");

        jLabel3.setText("Choose your Area:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(73, 73, 73)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(townComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29)
                        .addComponent(searchButton)
                        .addGap(27, 27, 27)
                        .addComponent(exitButton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(townComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton)
                    .addComponent(exitButton))
                .addContainerGap(70, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void townComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
    }                                            

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
     Display_All DA = new Display_All(townComboBox.getSelectedItem());
     DA.setVisible(true);
     dispose();
    }                                            

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Search_All.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Search_All.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Search_All.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Search_All.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Search_All().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton searchButton;
    private javax.swing.JComboBox townComboBox;
    // End of variables declaration
}

And the display class:

------------------------------------------------------------------------------------------------------

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

public class Display_All extends JFrame
{
   Object JFrame;
   Object JTable;
   Object JScrollpane;


    public Display_All(Object Location)
    {
        Vector columnNames = new Vector();
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
//  Get column names


                columnNames.addElement( "ID" );
                columnNames.addElement( "Name" );
                columnNames.addElement( "Email" );
                columnNames.addElement( "Location" );


        try
        {
            //  Connect to an Access Database


            String driver = "com.mysql.jdbc.Driver";
            String url ="jdbc:mysql://localhost:3306/db";
            String userid = "root";
            String password = "pass";

            Class.forName( driver );
            Connection connection = DriverManager.getConnection( url, userid, password );

            //  Read data from a table

            String sql = "(SELECT id, name, email, Location FROM table1 WHERE Location ='"+Location+"')"
                    + "UNION ALL ( SELECT id, name, email, Location FROM table2 WHERE Location = '"+Location+"')"
                    + "UNION ALL ( SELECT id, name, email, Location FROM table3 WHERE Location = '"+Location+"')"
                    + "UNION ALL ( SELECT id, name, email, Location FROM table4 WHERE Location = '"+Location+"')"
                    + "UNION ALL ( SELECT id, name, email, Location FROM table5 WHERE Location = '"+Location+"')"
                    + "UNION ALL ( SELECT id, name, email, Location FROM table6 WHERE Location = '"+Location+"')";



            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery( sql );
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();


            //  Get row data

            while (rs.next())
            {
                Vector row = new Vector(columns);

                for (int i = 1; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );
                }

                data.addElement( row );
            }

           rs.close();
           stmt.close();
           connection.close(); 
        }
        catch(Exception e)
        {
            System.out.println( e );

        }



        //  Create table with database data

        JTable table = new JTable(data, columnNames )
        {
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                    {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );

      JPanel buttonPanel = new JPanel();
        getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    }

  public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Display_All frame = new Display_All("Location");
            frame.setDefaultCloseOperation( DISPOSE_ON_CLOSE );




            frame.setVisible(true);
        }       
    });
}

}

Is this what you mean? I've gotten rid of any unnessecarys and made the database basic.

Thanks in advance for any help :)

Just try adding a pack(); after line 106 ( getContentPane().add( buttonPanel, BorderLayout.SOUTH ); )

Lifesaver man can't thank you enough :)

can't thank you enough

That's easy! Just follow this forum and when someone posts a problem where you can help, chip in and help. That's the best way to say thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.