0

Possible Duplicate:
JTable won’t show column headers
How to see column labels in JTable?

I'm creating a user registration form using swing. Some labels are not displayed properly and column names aren't displayed either.

Below is my code:

import java.awt.EventQueue;

import javax.swing.JFrame;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.Window.Type;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollBar;
import java.awt.Scrollbar;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.ListSelectionModel;


public class UserRegistration {

    private JFrame frmUserRegistrationForm;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTextField textField_3;
    private JCheckBox chckbxNewCheckBox;
    private JCheckBox chckbxUpdate;
    private JCheckBox chckbxDelete;
    private JComboBox UserTypecomboBox;
    private JLabel lblUserType;
    private JLabel lblIsactive;
     private JPanel panel;
     private JTable table;
     private JComboBox isActive; 
     static Vector<Vector<String>> data=null;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UserRegistration window = new UserRegistration();
                    window.frmUserRegistrationForm.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public UserRegistration() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmUserRegistrationForm = new JFrame();
        frmUserRegistrationForm.setTitle("User Registration Form");
        frmUserRegistrationForm.setBounds(100, 100, 700, 700);
        frmUserRegistrationForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmUserRegistrationForm.getContentPane().setLayout(null);

        JLabel lblUserRegistrationForm = new JLabel("User Registration Form");
        lblUserRegistrationForm.setBounds(211, 6, 198, 24);
        lblUserRegistrationForm.setFont(new Font("Times New Roman", Font.BOLD, 20));
        frmUserRegistrationForm.getContentPane().add(lblUserRegistrationForm);

        JLabel lblUserName = new JLabel("User Name* :");
        lblUserName.setBounds(197, 35, 130, 16);
        frmUserRegistrationForm.getContentPane().add(lblUserName);

        textField = new JTextField();
        textField.setBounds(350, 29, 122, 28);
        textField.setColumns(10);
        frmUserRegistrationForm.getContentPane().add(textField);

        JLabel lblPassword = new JLabel("Password* :");
        lblPassword.setBounds(197, 68, 130, 16);
        frmUserRegistrationForm.getContentPane().add(lblPassword);

        textField_1 = new JTextField();
        textField_1.setBounds(350, 62, 122, 28);
        textField_1.setColumns(10);
        frmUserRegistrationForm.getContentPane().add(textField_1);

        JLabel lblVerifyPassword = new JLabel("Verify Password* :");
        lblVerifyPassword.setBounds(197, 96, 150, 16);
        frmUserRegistrationForm.getContentPane().add(lblVerifyPassword);

        textField_2 = new JTextField();
        textField_2.setBounds(350, 90, 122, 28);
        textField_2.setColumns(10);
        frmUserRegistrationForm.getContentPane().add(textField_2);

        JLabel lblEmail = new JLabel("Email :");
        lblEmail.setBounds(197, 124, 60, 16);
        frmUserRegistrationForm.getContentPane().add(lblEmail);

        textField_3 = new JTextField();
        textField_3.setBounds(350, 118, 122, 28);
        textField_3.setColumns(10);
        frmUserRegistrationForm.getContentPane().add(textField_3);

        lblUserType = new JLabel("User Type* :");
        lblUserType.setBounds(197, 152, 80, 16);
        frmUserRegistrationForm.getContentPane().add(lblUserType);

        UserTypecomboBox = new JComboBox();
        UserTypecomboBox.setBounds(350, 147, 122, 26);
        UserTypecomboBox.setModel(new DefaultComboBoxModel(new String[] {"Admin", "User"}));
        frmUserRegistrationForm.getContentPane().add(UserTypecomboBox);

        JLabel lblCreate = new JLabel("Previlages* :");
        lblCreate.setBounds(196, 193, 100, 16);
        frmUserRegistrationForm.getContentPane().add(lblCreate);

        chckbxNewCheckBox = new JCheckBox("Create");
        chckbxNewCheckBox.setBounds(350, 192, 59, 18);
        frmUserRegistrationForm.getContentPane().add(chckbxNewCheckBox);

        chckbxUpdate = new JCheckBox("Update");
        chckbxUpdate.setBounds(440, 192, 62, 18);
        frmUserRegistrationForm.getContentPane().add(chckbxUpdate);

        chckbxDelete = new JCheckBox("Delete");
        chckbxDelete.setBounds(538, 192, 58, 18);
        frmUserRegistrationForm.getContentPane().add(chckbxDelete);

        JButton btnRegisterUser = new JButton("Add User");
        btnRegisterUser.setBounds(355, 250, 105, 28);

        btnRegisterUser.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                boolean validate = Validate();
                if(validate){
                    System.out.println("date to database");
                    try {
                        insertData();
                        addJtable();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });
        frmUserRegistrationForm.getContentPane().add(btnRegisterUser);
        Vector<String> headers=new Vector<String>();
           headers.add("User Name");
           headers.add("Email");
           headers.add("Previllage_create");
           headers.add("Previllage_update");
           headers.add("Previllage_delete");
           headers.add("User Type");
           headers.add("is_active");
        table = new JTable();
        table.setSurrendersFocusOnKeystroke(true);
        table.setShowVerticalLines(true);
        table.setCellSelectionEnabled(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        try {
            getData();
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        table.setModel(new DefaultTableModel(data,headers) {
            Class[] columnTypes = new Class[] {
                String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class
            };
            public Class getColumnClass(int columnIndex) {
                return columnTypes[columnIndex];
            }
        });
        table.getColumnModel().getColumn(2).setPreferredWidth(106);
        table.getColumnModel().getColumn(5).setPreferredWidth(113);
        table.setShowHorizontalLines(true);
        table.setBounds(33, 290, 619, 345);
        frmUserRegistrationForm.getContentPane().add(table);

        JScrollBar scrollBar = new JScrollBar();
        scrollBar.setBounds(637, 290, 15, 345);
        frmUserRegistrationForm.getContentPane().add(scrollBar);

        JLabel lblNewLabel = new JLabel("Is Active* :");
        lblNewLabel.setBounds(197, 221, 80, 16);
        frmUserRegistrationForm.getContentPane().add(lblNewLabel);

        isActive = new JComboBox();
        isActive.setModel(new DefaultComboBoxModel(new String[] {"Yes", "No"}));
        isActive.setBounds(350, 212, 60, 26);
        frmUserRegistrationForm.getContentPane().add(isActive);
    }
    public boolean Validate(){
         String userName = textField.getText();
         String passowrd = textField_1.getText();
         String verifyPassword = textField_2.getText();
         boolean validates = true;
         String message="";
         System.out.println("test" + userName);
        if((null== userName || userName.equals("")) && (null== passowrd || passowrd.equals("")) && (null== verifyPassword || verifyPassword.equals(""))&& !chckbxUpdate.isSelected() && !chckbxNewCheckBox.isSelected() && !chckbxDelete.isSelected()){

            JOptionPane.showMessageDialog(null,"Enter all mandatory fields");
            validates = false;

        }else{
        if(null== userName || userName.equals(""))
        {
            message= "User Name, ";
        }
        if(null== passowrd || passowrd.equals(""))
        {
            message=message+ "Passowrd, ";
        }
        if(null== verifyPassword || verifyPassword.equals(""))
        {
            message=message+ "verifyPassword, ";
        }
        if(!chckbxUpdate.isSelected() && !chckbxNewCheckBox.isSelected() && !chckbxDelete.isSelected()){
            message=message+ "Previlages";
        }
        if(!message.equals("")){
            JOptionPane.showMessageDialog(null,"Enter data for " +message+" fields");   
            validates=false;
        }
        }
        return validates;

    }

    public void insertData() throws SQLException{
         String userName = textField.getText();
         String passowrd = textField_1.getText();
         String verifyPassword = textField_2.getText();
         boolean prev_create= chckbxNewCheckBox.isSelected();
         boolean prev_update= chckbxUpdate.isSelected();
         boolean prev_delete= chckbxDelete.isSelected();
         String emial = textField_3.getText();
         String userType = (String)UserTypecomboBox.getSelectedItem();
         String isactive = (String) isActive.getSelectedItem();
         Connection con = null;
         try {
            Class.forName("com.mysql.jdbc.Driver");

         con = DriverManager
                         .getConnection("jdbc:mysql://127.0.0.1:3306/fingerprint",
                                         "root", "root");

         PreparedStatement ps = con
                         .prepareStatement("Insert into users(user_name,password,verify_pwd,email,previllage_create,previllage_update,previllage_delete,user_type,is_active) values(?,?,?,?,?,?,?,?,?)");
         ps.setString(1, userName);
         ps.setString(2, passowrd);
         ps.setString(3, verifyPassword);
         ps.setString(4, emial);
         if(prev_create)
         ps.setString(5, "Y");
         else
         ps.setString(5, "N");   
         if(prev_update)
         ps.setString(6, "Y");
         else
         ps.setString(6, "N");
         if(prev_delete)
         ps.setString(7, "Y");
         else
         ps.setString(7, "N");
         ps.setString(8, userType);
         ps.setString(9, isactive);
         ps.executeUpdate();
         con.close();

         } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         finally{
             con.close();
         }
    }
     private static void getData() throws ClassNotFoundException, SQLException
     {
      // Enter Your MySQL Database Table name in below Select Query.
         data=new Vector<Vector<String>>();
      String str="select user_name,password,verify_pwd,email,previllage_create,previllage_update,previllage_delete,user_type,is_active from users";
      Connection con = null;
      ResultSet rs = null;
      Statement st = null;

      try {
       // Change the database name, hosty name, 
       // port and password as per MySQL installed in your PC.
          Class.forName("com.mysql.jdbc.Driver");

             con = DriverManager
                             .getConnection("jdbc:mysql://127.0.0.1:3306/fingerprint",
                                             "root", "root");

       st=con.createStatement();

       rs=st.executeQuery(str);

       while(rs.next())
       {
        Vector <String> d=new Vector<String>();

        d.add(rs.getString("user_name"));
        d.add(rs.getString("email"));
        d.add(rs.getString("previllage_create"));
        d.add(rs.getString("previllage_update"));
        d.add(rs.getString("previllage_delete"));
        d.add(rs.getString("user_type"));
        d.add(rs.getString("is_active"));
        d.add("\n\n\n\n\n\n\n");
        data.add(d);
       }

      } catch (SQLException e) {

       e.printStackTrace();
      }
      finally{
          st.close();
          rs.close();
          con.close();
      }
     }

     public void addJtable(){
            Vector<String> headers=new Vector<String>();
               headers.add("User Name");
               headers.add("Email");
               headers.add("Previllage_create");
               headers.add("Previllage_update");
               headers.add("Previllage_delete");
               headers.add("User Type");
               headers.add("is_active");
            table = new JTable();
            table.setSurrendersFocusOnKeystroke(true);
            table.setShowVerticalLines(true);
            table.setCellSelectionEnabled(true);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            try {
                getData();
            } catch (ClassNotFoundException | SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            table.setModel(new DefaultTableModel(data,headers) {
                Class[] columnTypes = new Class[] {
                    String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class
                };
                public Class getColumnClass(int columnIndex) {
                    return columnTypes[columnIndex];
                }
            });
            //table.getColumnModel().getColumn(2).setPreferredWidth(50);
            //table.getColumnModel().getColumn(5).setPreferredWidth(50);
            table.setShowHorizontalLines(true);
            table.setBounds(33, 290, 619, 345);
            //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            TableColumn column = table.getColumnModel().getColumn(0);
            column.setPreferredWidth(10);


            column = table.getColumnModel().getColumn(1);
            column.setPreferredWidth(350);



            frmUserRegistrationForm.getContentPane().add(table);

            JScrollBar scrollBar = new JScrollBar();
            scrollBar.setBounds(637, 290, 15, 345);
            frmUserRegistrationForm.getContentPane().add(scrollBar);
     }


}

Below is the screenshot of the app:

enter image description here

In the screenshot, labels like create, update and delete are appearing properly but table columns are not getting displayed.

Edit.

Below is screenshot after adding frmUserRegistrationForm.getContentPane().add(new JScrollPane(table));

enter image description here

Community
  • 1
  • 1
developer
  • 9,116
  • 29
  • 91
  • 150
  • This is too much code for me to go through for a SO question, but you may want to compare against the documentation here: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#width – Cory Kendall Oct 22 '12 at 04:11
  • 1
    Way to load up the example code with irrelevant dross! See if you can reproduce the problem in <100 lines of code, as opposed to >400! – Andrew Thompson Oct 22 '12 at 04:12
  • 2
    this is one of the most common gotchas of working with JTable, see the duplicate question, there is an explanation why this is done by design. – Denis Tulskiy Oct 22 '12 at 04:16

1 Answers1

7

You create the table and add it directly to the content pane...Tables expect to be added to a JScrollPane.

Try something like...

frmUserRegistrationForm.getContentPane().add(new JScrollPane(table));

Also, I HIGHLY recommend that you take advantage of appropriate layout managers. Give me 3 seconds and I will ruin all you hard work with calculating the absolute layouts...and I probably won't need to change a thing about your code or my system.

I would recommend you have a read of

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366