2012-10-22 400 views
0

可能重複:
JTable won’t show column headers
How to see column labels in JTable?列名不JTable中顯示

我使用擺動創建一個用戶註冊表單。 某些標籤顯示不正確,列名也不顯示。

下面是我的代碼:

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); 
    } 


} 

下面是應用程序的截圖:

enter image description here

在截圖中,標籤喜歡的創建,更新和刪除顯示正常,但表中的列沒有得到顯示。

編輯。

下面是添加frmUserRegistrationForm.getContentPane().add(new JScrollPane(table));

enter image description here

+0

讀這是我經歷的SO問題太多的代碼,但是你可能想在此處與文檔進行比較:http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#width –

+1

加載示例代碼的方法不相干的渣滓!看看你是否可以在<100行代碼中重現問題,而不是> 400! –

+2

這是使用JTable最常見的問題之一,請參閱重複的問題,有一個解釋爲什麼這是由設計完成的。 –

回答

7

您創建表,並直接將它添加到內容窗格中......表希望將其添加到JScrollPane後的截圖。

嘗試類似...

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

另外,我強烈建議您採取適當的佈局管理器的優勢。給我3秒鐘,我會毀掉你所有的計算絕對佈局的努力......我可能不需要改變你的代碼或我的系統。

我建議你有

+0

感謝您的建議,您是否對我的代碼進行了任何更改? – developer

+0

我會推薦的唯一更改(其他使用佈局管理器)是答案中的一個,將該表添加到「JScrollPane」中。 – MadProgrammer

+0

我按照您所提到的那樣進行了更改,但Jtable已經消失並且上面附有screemshot。 – developer