0

i am new in java programming. everything is going well. but it seems that i am having a problem in my jframe whenever a create a Jtable called in a JScrollPane. Sometimes all the components (e.i. buttons, labels etc.) won't appear. but when i comment the table and its properties, components appear. what may be my problem? thank you very much for any help. Thanks a lot! Here is my method for creating table. thanks again.

package myphonebookbeta;

import java.awt.event.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
 import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class MainForm extends JFrame implements ActionListener{

//<editor-fold defaultstate="collpased" desc="my components">

JFrame f=new JFrame();
JPanel p=new JPanel(null); 
JLabel fnameLbl,lnameLbl,addressLbl,cpLbl;
JTextField fname,lname,address,cp;
JButton save,delete,cancel,update;
JTable table=null;
JScrollPane scrollPane=null;
JDesktopPane dp=null;
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="sql variabled">

private final String url="jdbc:mysql://localhost:3306/";
private final String db="dbnetbeans";
private final String uid="root";
private final String pwd="";
private final String driver="com.mysql.jdbc.Driver";
private Connection con=null;
private Statement st=null;
private ResultSet rs;
private ResultSetMetaData md;
private String sql;

//</editor-fold>

public MainForm(){

   mainFormGui();

}//end MainForm

private void mainFormGui(){

   f.setTitle("My Phonebook Beta");
   f.setSize(600,400);
   f.setLocationRelativeTo(f);
   f.setVisible(true);
   f.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
   f.addWindowListener(new WindowAdapter(){
       @Override
       public void windowClosing(WindowEvent e){
           int cls=JOptionPane.showOptionDialog(null,"You are about to exit the program! Do you wish to proceed?","WARNING",
                   JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null,null,null);
           if (cls==0){
               System.exit(0);
           }
       }
   });

    initComponents();

}//end of mainFormGui

private void initComponents(){

    //<editor-fold defaultstate="collapsed" desc="components declaration">

    fnameLbl=new JLabel("First Name : "); fnameLbl.setBounds(10,18,90,24);
    lnameLbl=new JLabel("Last Name : "); lnameLbl.setBounds(10,52,90,24);
    addressLbl=new JLabel("Address : "); addressLbl.setBounds(10,86,90,24);
    cpLbl=new JLabel("Contact No. :"); cpLbl.setBounds(10,120,90,24);

    fname=new JTextField(""); fname.setBounds(100,14,140,24);
    lname=new JTextField(""); lname.setBounds(100,48,140,24);
    address=new JTextField(""); address.setBounds(100,82,140,24);
    cp=new JTextField(""); cp.setBounds(100,116,140,24);

    save=new JButton("SAVE"); save.setBounds(10,150,110,24);
    cancel=new JButton("Cancel"); cancel.setBounds(130,150,110,24);
    update=new JButton("Update"); update.setBounds(10,180,110,24);
    delete=new JButton("Delete"); delete.setBounds(130,180,110,24);


    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="adding to panel">
    p.setVisible(true);

    p.add(fnameLbl); p.add(fname);
    p.add(lnameLbl); p.add(lname);
    p.add(addressLbl); p.add(address);
    p.add(cpLbl); p.add(cp);

    p.add(save);p.add(delete); p.add(update); p.add(cancel);


    //</editor-fold>

    btnAction();

// createTable();

    f.add(p); 


}//end of initComponents

private void btnAction(){
    cancel.addActionListener(this);
    save.addActionListener(this);
    delete.addActionListener(this);

}//end void btnAction

@Override
public void actionPerformed(ActionEvent ae){

    String fn=fname.getText();
    String ln=lname.getText();
    String ad=address.getText();
    String cpn=cp.getText();

    try{

        //<editor-fold defaultstate="collapsed" desc="cancel_click">

        if(ae.getSource()==cancel){

            clearFields();

        }//end cancel

        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="save_click">

        if(ae.getSource()==save){

            sql="Insert into tbphonebook (firstname,lastname,address,cp)"
                    + " value('"+fn+"','"+ln+"','"+ad+"','"+cpn+"')";
            connect();
            st=con.createStatement();
            st.executeUpdate(sql);
            disconnect();
            JOptionPane.showMessageDialog(null,"Info successfully SAVED!","confirmation - SAVE ", JOptionPane.INFORMATION_MESSAGE);
            clearFields();

        }//end save

        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="delete_click">

        if(ae.getSource()==delete){

            int ch=JOptionPane.showOptionDialog(null,"This action is irrevocable. Do you wish tocontinue?",
                    "Delete this contact?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null,null,null);

            if (ch==0){

                sql="delete from tbphonebook where firstname like '"+fn+"' and lastname like '"+ln+"'";
                connect();
                st=con.createStatement();
                st.executeUpdate(sql);
                disconnect();
                JOptionPane.showMessageDialog(null,"Contact successfully DELETED!","confirmation - DELETE ", JOptionPane.INFORMATION_MESSAGE);
                clearFields();

            }//end if(ch==0)

        }//end delete

        //</editor-fold>


    }//try

    catch(Exception e){
            e.printStackTrace();
    }//catch
}//end actionPerformed

private void connect(){

   try{
       Class.forName(driver).newInstance();
       con=DriverManager.getConnection(url+db,uid,pwd);
   } 
   catch(Exception ex){
       ex.printStackTrace();
   }


}//end connect

private void disconnect(){

   try{
       con.close();
   } 
   catch(Exception ex){
       ex.printStackTrace();
   }


}//end disconnect   

private void clearFields(){

   fname.setText("");
   lname.setText("");
   address.setText("");
   cp.setText("");
   fname.requestFocus();

}//end clearField

private void createTable(){

    scrollPane=new JScrollPane(this.table);
    scrollPane.setBounds(250,14,320,160);
    scrollPane.setVisible(true); 
    scrollPane.setViewportView(table);
    p.add(scrollPane);

}//end createTable

private void fillTable() throws SQLException{

    ArrayList colNames=new ArrayList();
    ArrayList data=new ArrayList();
    ArrayList row=new ArrayList();

    sql="select * from tbphonebook";
    connect();
    st=con.createStatement();
    rs = st.executeQuery(sql);

    try{

        md =rs.getMetaData();
        int col=md.getColumnCount();

        //to getcolumn names
        for (int i=1;1<=col;i++){
            colNames.add(md.getColumnName(i));
        }

        //to get row data
        while(rs.next()){

            for(int i=1;1<=col;i++){

                row.add(rs.getObject(i));

            }

            data.add(row);
        }

    }
    catch(Exception ex){

        ex.printStackTrace();

    }


}//end fillTable
}
deo toh
  • 15
  • 1
  • 7
  • 2
    post up your code plz – Kick Buttowski Sep 21 '14 at 03:17
  • seems to be repaint problem – Madhawa Priyashantha Sep 21 '14 at 03:18
  • 1
    For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example). – Andrew Thompson Sep 21 '14 at 03:19
  • 2
    @madhawapriyashantha *"seems to be repaint problem"* Rarely is repaint the problem, but there is really too little code (i.e. none) to tell at this moment. – Andrew Thompson Sep 21 '14 at 03:21
  • 1
    thanks guys. i'll send the full codes. – deo toh Sep 21 '14 at 03:24
  • 1
    Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Sep 21 '14 at 03:27
  • 1
    1) Don't use setBounds(). Swing was designed to be used with layout managers. 2) You don't need scrollPane.setVisible(true). Swing components are visible by default. 3) This is not an MCVE. The code does not compile. We have no idea if "p" is using a layout manager or not. We have no idea the order you add your components to the panel. Maybe start with the [Sorting and Filtering](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting) demo code. It will show you an example with a table and other components and give you a better idea how to structure your code. – camickr Sep 21 '14 at 03:27
  • As an aside. It is usually a better strategy to create and add the table as the GUI is created, then simply populate it with data when data is available. Alternately add the table to a `CardLayout` and add another card that is a blank panel. – Andrew Thompson Sep 21 '14 at 03:30
  • thank you guys for all the reply. I'll try to rewrite the codes. I am also new in stackOverFlow. don't know much yet. but guys, thanks for all the help. I guess i'll start learning what MCVE is so you guys won't be burdened by my questions. – deo toh Sep 21 '14 at 03:32
  • *"so you guys won't be burdened by my questions"* Creating MCVEs will solve a lot of problems before they appear here, but questions are never a 'burden'. If people don't like a particular question or feel they are such, they might down-vote, or perhaps vote to close, then move on. No burden. ;) – Andrew Thompson Sep 21 '14 at 03:35
  • 1
    thanks guys. this site is sure a good one. – deo toh Sep 21 '14 at 03:54
  • Guys, i seemed to solved it. I tried Mr. Andrew Thompson's suggestion. i add .repaint on my Jframe and it just happened to work properly now. All of you guys are big help to me. thanks. – deo toh Sep 21 '14 at 04:29

1 Answers1

1
JPanel p=new JPanel(null); 

Do not use the null layout unless you have to. Read this article on how to use GridBagLayout. It is easy to use and very flexible.

About your repaint problem: Are you sure to execute that code on the Event Dispatch Thread?

Stephan
  • 4,395
  • 3
  • 26
  • 49
  • thank you Stephan.. i'll do that. I'm new in programming and doing a self-study. this article will be a big help. thanks. – deo toh Sep 21 '14 at 09:25
  • i just noticed that i could not use setBounds if the panel is not set as null, but gridlayout and other layout does. – deo toh Sep 30 '14 at 13:17
  • Use setPreferredSize() to set the size. The location is calculated by the layout. – Stephan Oct 01 '14 at 13:09