JTABLE in jsp

is there any way to get the swing JTable functionality(editable) in jsp,servlet or html without using Applet.

You can do that functionality. but its a difficuilt job too. u can place a html table in the form post and allow editable and have to write scripts to post the edited table while submitting the button. it works same as the swing JTable functionality but dose not have the same look and feel but simillar lok and feel u will get
Good Luck

Similar Messages

  • Displaying search results in a JTable..

    Hello,
    I've got a stupid problem. I'm trying to have a search dialog box that returns it's results into a JTable. Seems like it should be pretty straightforward. My immediate problem is that with the following code (based on an example I found in the forums):
         Vector vColumnNames = new Vector();
         Vector vData = new Vector();
         vColumnNames.add("Company Name");
         vColumnNames.add("Contact");
         vColumnNames.add("Booth #");
         vColumnNames.add("Status");
         for (int i=0; i<4; i++)
             vData.add(new String("blah"));
         dm = new DefaultTableModel(vData, vColumnNames);
         jtResults = new JTable(dm);
         jsp = new JScrollPane(jtResults, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
             jtResults.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);It generates an java.lang.ClassCastException: java.langString exception. After some testing the part that causes this to die is adding the strings to vData. if I comment out the for loop it works fine, except with no data of course. What gives? I'm sure I'm doing something totally stupid wrong, but I don't understand why the Vector of Strings works for column names but nto for the data.
    My secondary concern is: I need to be able to reuse the table for multiple searches, I think if I just update the TableModel and repaintit should be ok; also I'd like the table to appear as an empty white background when there's no data in it as well; currently the insides of the table just show up as grey when there's no data. Is there a way to fix that?
    Thanks!
    xanatos

    Hmm. Nevermind, I think I figured it all out. ^_^
    xanatos

  • JTable bean in forms

    I would like to display JTable based bean in Oracle Forms 10g but I get:
    *** VBean null PropertyManager for id = FOREGROUND
    *** VBean Got FOREGROUND = null
    *** VBean null PropertyManager for id = BACKGROUND
    *** VBean Got BACKGROUND = null
    *** VBean Setting debugMode to ALL
    *** VBean Setting beanName to plusplus.PPCalendar
    *** plusplus.PPCalendar Registering properties
    *** plusplus.PPCalendar     int pWidth
    *** plusplus.PPCalendar     int pDebugGraphicsOptions
    *** plusplus.PPCalendar     int pHeight
    *** plusplus.PPCalendar     boolean pOpaque
    *** plusplus.PPCalendar     javax.swing.InputVerifier pInputVerifier
    *** plusplus.PPCalendar     Failed to introspect class: class plusplus.PPCalendar java.lang.NullPointerExceptionPPCalendar's code:
    public class PPCalendar extends JPanel
      private JTable table;
      private DefaultTableModel model;
      private JScrollPane jsp;
    public PPCalendar() {
       super();
       model = new DefaultTableModel( new String[] [] {  {"1x1", "1x2"},  {"2x1", "2x2"}}, new String [] {"First", "Second"});
       table = new JTable(model);
       jsp = new JScrollPane(table);
       jsp.setAutoscrolls(true);
       this.add(jsp);
       this.setVisible(true);
      public void setHead(String nes) {
        String val1 = (String) model.getValueAt(0,0);
        System.out.println("val1: " + val1);
      public String getHead() {
        return (String) model.getValueAt(0,0);
      }Setting property (     fbean.set_property('tb.ptable', 1, 'head', 'Blah');) fails, but I can set properties (introspection still fails) if I try something similar with:
    package plusplus;
    //import java.awt.Panel;
    //import java.awt.Label;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    public class Simple extends JPanel  {
      private JLabel naziv = new JLabel();
      public Simple() {
        try {
          jbInit();
        } catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        naziv.setText("XXX");
        this.add(naziv, null);
      public void setNaziv(String tekst) {
        naziv.setText(tekst);
    }What am I doing wrong? Are there some "more advanced" swing based bean examples?
    Is there some kind of documentation on oracle.ewt.* and Dynamic Bean Manager?

    The problem is that you're extending JPanel - the issue is not your fault (or ours for that matter) it's a problem in the base JPanel class which causes a NPE when introspecting the properties that it exposes because it does not conform to the JavaBeans Spec.
    We've put a WorkAround into the FBean code in Forms 10.1.2 but for the moment you will have to extend Panel rather than JPanel and all should be ok - this should make no difference to the operation of the Bean.
    Another option would be to write a BeanInfo class for your Bean and prevent the exposure of the problem property (inputMap) that way.

  • Trying to run a query

    I'm trying to run a query in a JTextField and then have that query display the output in a JTable. When I try to use .getText() to store the query in a string I keep getting errors about SQLException. Can anyone lend me in hand in telling me what I'm doing wrong?
    This is the error I get when the line below would say:
    query=jtf.getText();
    c:\java>java myguidemo
    Exception in thread "main" java.sql.SQLException: Invalid SQL type
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
    :112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
    :146)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
    :208)
    at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:67)
    at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:946)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStateme
    nt.java:1169)
    at oracle.jdbc.driver.OracleStatement.doScrollExecuteCommon(OracleStatem
    ent.java:4044)
    at oracle.jdbc.driver.OracleStatement.doScrollStmtExecuteQuery(OracleSta
    tement.java:4196)
    at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:
    1280)
    at myguidemo.<init>(myguidemo.java:39)
    at myguidemo.main(myguidemo.java:106)
    c:\java>
    Here is what I have so far. I took out the oracle IP and login. This is a working version, but where query = "SELECT * ....." I would like that to get whatever is typed in the JTextField. Also button1-5 is supposed to display the entire table in the JTable just by clicking it. Right now I just have them to change background color to make sure they worked.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class myguidemo extends JFrame implements ActionListener{
              Connection connection;
              Statement stmt;
              String query;
              ResultSet results;
              ResultSetMetaData md;
              int numrows, numcols;
              AbstractTableModel dataModel;
              Object [][] data;
    JTextField jtf;
    JTable jtb;
    JPanel jp;
    JScrollPane jsp;
    JButton button1, button2, button3, button4, button5;
    public myguidemo() throws Exception{
              Class.forName( "oracle.jdbc.driver.OracleDriver" );
              connection = DriverManager.getConnection("jdbc:oracle:thin:@);
              jp = new JPanel();
              add(jp,BorderLayout.SOUTH);
    jtb = new JTable();
    add(jtb,BorderLayout.CENTER);
    jtf = new JTextField();
    add(jtf,BorderLayout.NORTH);
    query = "SELECT * FROM PATIENT";
    stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    results = stmt.executeQuery(query);
    md = results.getMetaData();
              numcols = md.getColumnCount();
              numrows = 0;
              while(results.next()) numrows++;
              results.beforeFirst();
              data = new Object[numrows][numcols];
              results.next();
              for(int i=0; i<numrows; i++){
                   for(int j=1; j<=numcols; j++){
                        data[i][j-1] = results.getString(j);
                   results.next();
    dataModel = new AbstractTableModel(){
         public int getColumnCount() {return numcols;}
         public int getRowCount() {return numrows;}
         public Object getValueAt(int row, int col) {return data[row][col];}
    jtf.addActionListener(this);
    jtb = new JTable(dataModel);
    jsp = new JScrollPane(jtb);
    add(jsp);
    button1 = new JButton("Doctor");
    button2 = new JButton("Medication");
    button3 = new JButton("Patient");
    button4 = new JButton("Prescription");
    button5 = new JButton("Supplier");
    jp.add(button1);
    jp.add(button2);
    jp.add(button3);
    jp.add(button4);
    jp.add(button5);
    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);
    button4.addActionListener(this);
    button5.addActionListener(this);
    setTitle("CSIT");
    setSize(1280,720);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
    public void actionPerformed(ActionEvent e){
    if (e.getSource() == jtf){
         jtf.setText("");
    if (e.getSource() == button1) jtb.setBackground(Color.RED);
    if (e.getSource() == button2) jtb.setBackground(Color.GREEN);
    if (e.getSource() == button3) jtb.setBackground(Color.BLUE);
    if (e.getSource() == button4) jtb.setBackground(Color.ORANGE);
    if (e.getSource() == button5) jtb.setBackground(Color.YELLOW);
    public static void main(String args[]) throws Exception{
         new myguidemo();
    Edited by: rizzo18 on Dec 12, 2009 1:46 PM
    Edited by: rizzo18 on Dec 12, 2009 2:06 PM

    I'm trying to run a query in a JTextField and then have that query display the output in a JTable.1. Write classes that only do JDBC. If there is any GUI code at all in them then it is wrong.
    2. Test those classes and modify until they work.
    3. Use those classes in your GUI code (other classes) to do what you want.
    Questions about 1 and 2 go in this forum. Questions about 3 go into a GUI forum.
    Use code tags when you post code.

  • TableHeader Resizing Problem

    Hello everyone.
    I am trying to work out a header_resizable table with specified header height,
    but when drag the next to the last column's header make the last one dispeared.
    I've got a workaround by making the header's preferredSize wide enough,
    but want to know what the gulus will do in this situation.
    Can anybody explain me why this happaned, and teach me the ultimate solution?
    Thanks for any reply in advance.
    Here is the so-called SSCCE.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class TableHeaderResizeTest extends JFrame {
        private TableHeaderResizeTest(){
            int colNum = 4;
            int rowNum = 4;
            String[] columnNames = new String[colNum];
            String[][] tableData = new String[rowNum][colNum];
            for (int i = 0; i < columnNames.length; i++) {
                columnNames= "COLUMN"+i;
    for (int i = 0; i < tableData.length; i++) {
    for (int j = 0; j < tableData[i].length; j++) {
    tableData[i][j] = "R"+i+"C"+j;
    JTable jt = new JTable();
    JScrollPane jsp = new JScrollPane(jt);
    jsp.setPreferredSize(new Dimension(400,200));
    jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    DefaultTableModel dtm = new DefaultTableModel(tableData,columnNames);
    jt.setModel(dtm);
    for (int i = 0; i < colNum; i++) {
    jt.getColumnModel().getColumn(i).setPreferredWidth(200);
    Dimension d = jt.getTableHeader().getPreferredSize();
    // if wide enough, it seemed help to excute normally
    // d.width =1000000;
    d.height = 40;
    jt.getTableHeader().setPreferredSize(d);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(jsp,BorderLayout.CENTER);
    public static void main(String[] args) {
    JFrame f = new TableHeaderResizeTest();
    f.setTitle("JTableExTest");
    f.pack();
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    f.setResizable(true);
    f.setVisible(true);
    The problem is: If you drag the COLUMN2 to some extent, the COLUMN3 will disapear.

    OK, i want further help if possible, and here is my SSCCE.
    It works not very fine for me , maybe i missed something.
    I am sorry that it is a little long .
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.border.Border;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableCellRenderer;
    public class TableHeaderResizeTest extends JFrame {
        private TableHeaderResizeTest(){
            int colNum = 4;
            int rowNum = 4;
            String[] columnNames = new String[colNum];
            String[][] tableData = new String[rowNum][colNum];
            for (int i = 0; i < columnNames.length; i++) {
                columnNames= "COLUMN"+i;
    for (int i = 0; i < tableData.length; i++) {
    for (int j = 0; j < tableData[i].length; j++) {
    tableData[i][j] = "R"+i+"C"+j;
    JTable jt = new JTable();
    jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    DefaultTableModel dtm = new DefaultTableModel(tableData,columnNames);
    jt.setModel(dtm);
    for (int i = 0; i < colNum; i++) {
    jt.getColumnModel().getColumn(i).setPreferredWidth(200);
    JTableHeader header = jt.getTableHeader();
    TableCellRenderer defaultRenderer = header.getDefaultRenderer();
    header.setDefaultRenderer( new MyTableHeaderRenderer(defaultRenderer) );
    Dimension d = header.getPreferredSize();
    // if wide enough, it seemed help to excute normally
    // d.width =1000000;
    d.height = 40;
    header.setPreferredSize(d);
    JScrollPane jsp = new JScrollPane(jt);
    jsp.setPreferredSize(new Dimension(400,200));
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(jsp,BorderLayout.CENTER);
    private class MyTableHeaderRenderer implements TableCellRenderer
    private TableCellRenderer tableCellRenderer;
    private Border border;
    public MyTableHeaderRenderer(TableCellRenderer tableCellRenderer)
    this.tableCellRenderer = tableCellRenderer;
    // JLabel label = (JLabel)tableCellRenderer;
    Border current = UIManager.getBorder("TableHeader.cellBorder");
    Border empty = new EmptyBorder(10, 0, 10, 0);
    border = new CompoundBorder(current, empty);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    Component c = tableCellRenderer.getTableCellRendererComponent(table, value,
    isSelected, hasFocus, row, column);
    JLabel l = (JLabel) c;
    l.setBorder(border);
    return c;
    public static void main(String[] args) {
    JFrame f = new TableHeaderResizeTest();
    f.setTitle("TableHeaderResizeTest");
    f.pack();
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    f.setResizable(true);
    f.setVisible(true);
    Message was edited by:
    morning3evening4

  • JSplitPane: can I programatically do what the oneTouchExpandable does?

    Hi All,
    I'm looking for a method call I can use to do the same thing as the oneTouchExpandable buttons do on the JSplitPane divider. I basically want to call a method to collapse the left hand side and then same/simlar call to restore it. Is such a method available? I know I can do setDividerLocation(0), but I'm looking for something less manual. Thanks in advance.

    hi,
    just check this program, just click on the button then you can came to know what is happing
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    public class SplitPaneDemo extends JFrame
        JTextField jtf = new JTextField(15);
        String cols[] = {"asdfasdfasdf","asdfasdfsadf","asdfasdf","aaaaaaaaaaaa","aaaaaaaaaaaaaaaaa"};
        JPanel jp = new JPanel();
        JPanel jp1 = new JPanel();
        JPanel jp2 = new JPanel(new BorderLayout());
        JTable tbl = new JTable(10,10);
        JScrollPane jsp = new JScrollPane(tbl);
        public SplitPaneDemo() {
            JButton jb = new JButton("sdf");
            tbl.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            jsp.setAutoscrolls(true);
            jb.addActionListener( new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    if(jp1.isVisible())
                        jp1.setVisible(false);
                    else
                        jp1.setVisible(true);
            jp.setEnabled(true);
            jp.add(jsp, "Center");
            jp.setBorder(BorderFactory.createBevelBorder(1));
            jp1.add(new JLabel("asdfeeeeeeeeeeeeeeeeee"));
            jp2.add(jsp, "Center");
            jp2.add(jp1, "West");
            getContentPane().add(new JPanel().add(jb),"West");
            getContentPane().add(jp2, "Center");
            pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
        public static void main(String[] args)
            new SplitPaneDemo();
    }hopes it helps
    daya

  • How can i load A gui JTable bean through jsp:useBean tag in a jsp page

    Hi,
    i am chiranjit , i am in a jsp project . i am desparately looking a solution for below stated problem:
    i want to make a jsp page for master entry , that why i want to load a GUI Java bean in my jsp page.This GUI Bean contaning a JTable in which allow grid type data entry in the jsp page. But i am unable load that bean in the jsp page through jsp:useBean tag in my page.So if you have any solution then send in the forum as early as possible.
    Thank you
    chiranjit

    No can do. JSPs can only output plain HTML (and javascript...) They are not used like normal Java classes.
    If you need a complex GUI then you might use an Applet instead. If you want to use a JSP then you are stuck using normal HTML components, like <table> <form...> <input type="text"> etc...

  • Display data in JTable

    I am trying to display data from database into the JTable swing component. I can see the table and the heading coming from the vector. I cannot see why the data from the databse table is not loaded on to the Jtable. I just get a table with 6 rows blank.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class dataTable extends JApplet
    String dbdriver="jdbc:oracle:thin:@ds1.ctateu.edu:1521:wpac";
    String dbuser="system";
    String dbpass="pass";
    Container c;
    JScrollPane jsp;
    JTable table;
    int v,h;
    Connection connection;
    Statement stmt;
    ResultSet rs;
    String param_start,param_end, param_disp_start, param_disp_end,param_shortdesc, param_longdesc;
    public void init()
    c= getContentPane();
    c.setLayout (new BorderLayout());
    v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
    h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
    Vector heading = new Vector();
    heading.addElement("Event Start Date");
    heading.addElement("Event End Date");
    heading.addElement("Display Start Date");
    heading.addElement("Display End Date");
    heading.addElement("Short Description");
    heading.addElement("Long Description");
    Vector data = new Vector();
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection=DriverManager.getConnection(dbdriver,dbuser,dbpass);
    stmt=connection.createStatement();
    rs= stmt.executeQuery("select * from univevents");
    while(rs.next())
    param_start = rs.getString("start_date");
    param_end = rs.getString("end_date");
    param_disp_start = rs.getString("display_start");
    param_disp_end =rs.getString("display_end");
    param_shortdesc = rs.getString("short_desc");
    param_longdesc = rs.getString("long_desc");
    catch (Exception e)
    //JOptionPane.showMessageDialogue("Exception: "+e.getMessage());
    data.addElement(param_start);
    data.addElement(param_end);
    data.addElement(param_disp_start);
    data.addElement(param_disp_end);
    data.addElement(param_shortdesc);
    data.addElement(param_longdesc);
    table = new JTable(data, heading);
    jsp = new JScrollPane(table,v,h);
    //Add scrollpane to container
    c.add("Center",jsp);
    }//init
    }//JApplet

    Your data vector should be a Vector of Vectors.
    I think you need to change your loop to look something like this:
    while(rs.next())
        Vector row = new Vector();
        row.addElement( rs.getString("start_date") );
        row.addElement( rs.getString("end_date") );
        row.addElement( rs.getString("display_start") );
        row.addElement( rs.getString("display_end") );
        row.addElement( rs.getString("short_desc") );
        row.addElement( rs.getString("long_desc") );
        data.addElement( row );
    } Then remove your data.addElement() statements found outside the loop.

  • JTable with row header plus value extraction from headers

    Hi, I am trying to do the following:
    Short Version-
    1. Create a table that has both row and column headers
    2. Allow the user to mouse over any of these headers such that doing so will display an image I have produced on a panel. (I already know how to create the image and how to display it, I'm just not sure how to associate it with a particular row or column header)
    3. Make the row headers look as much as possible like the column headers.
    Slightly Longer Version-
    Column headers will be labled A-H (maximum) while row headers will be labled 1-12 (maximum). Either can be less, however, depending on user input. After the table has been realized, the user will move the mouse over say, header 'H' and when they do, a JPEG image will appear on another panel and a tooltip will appear above the cell showing a formula. This happens when either row or column headers are moused over.
    Currently, I am using the following code from the O'reilly Swing book as a baseline for experimentation but any help you can offer will be appreciated. I'm fairly new to the JTable world... :-(
    TableModel tm = new AbstractTableModel(){
                   String data[] = {"", "a", "b", "c", "d", "e"};
                   String headers [] = {"Row #", "Column1", "Column2", "Column3", "Column4", "Column5"};
                   public int getColumnCount(){ return data.length;}
                   public int getRowCount() { return 1000;}
                   public String getColumnName(int col){ return headers[col];}
                   public Object getValueAt(int row, int col){
                        return data[col] + row;
              //creates a column model for the main table. This model ignores the first
              //column added and sets a minimum width of 150 pixels for all others
              TableColumnModel cm = new DefaultTableColumnModel(){
                   boolean first = true;
                   public void addColumn(TableColumn tc){
                        if(first) {first = false; return;}
                        tc.setMinWidth(150);
                        super.addColumn(tc);
              //Creates a column model that will serve as the row header table. This model
              //picks a maxium width and stores only the first column
              TableColumnModel rowHeaderModel = new DefaultTableColumnModel(){
                   boolean first = true;
                   public void addColumn(TableColumn tc){
                        if(first) {
                             tc.setMaxWidth(tc.getPreferredWidth());
                             super.addColumn(tc);
                             first = false;
              JTable grid = new JTable(tm, cm);
              //set up the header column and hook it up to everything
              JTable headerColumn = new JTable(tm, rowHeaderModel);
              grid.createDefaultColumnsFromModel();
              headerColumn.createDefaultColumnsFromModel();
              //make sure the selection between the main table and the header stay in sync
              grid.setSelectionModel(headerColumn.getSelectionModel());
              headerColumn.setBorder(BorderFactory.createEtchedBorder());
              headerColumn.setBackground(Color.lightGray);
              headerColumn.setColumnSelectionAllowed(false);
              headerColumn.setCellSelectionEnabled(false);
              JViewport jv = new JViewport();
              jv.setView(headerColumn);
              jv.setPreferredSize(headerColumn.getMaximumSize());
              //to make the table scroll properly
              grid.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              //have to manually attach row headers but after that, the scroll pane
              //keeps them in sync
              JScrollPane jsp = new JScrollPane(grid);
              jsp.setRowHeader(jv);
              jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
              gridPanel.add(jsp, BorderLayout.NORTH);

    There a number of nice examples on JTable: http://www.senun.com/Left/Programming/Java_old/Examples_swing/SwingExamples.html
    Hope you could find something suitable ...
    Regards,
    Anton.

  • Cant get data from text file to print into Jtable

    Instead of doing JDBC i am using text file as database. I cant get data from text file to print into JTable when i click find button. Goal is to find a record and print that record only, but for now i am trying to print all the records. Once i get that i will change my code to search desired record and print it. when i click the find button nothing happens. Can you please take a look at my code, dbTest() method. thanks.
    void dbTest() {
    DataInputStream dis = null;
    String dbRecord = null;
    String hold;
    try {
    File f = new File("customer.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
    Vector dataVector = new Vector();
    Vector headVector = new Vector(2);
    Vector row = new Vector();
    // read the record of the text database
    while ( (dbRecord = dis.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(dbRecord, ",");
    while (st.hasMoreTokens()) {
    row.addElement(st.nextToken());
    System.out.println("Inside nested loop: " + row);
    System.out.println("inside loop: " + row);
    dataVector.addElement(row);
    System.out.println("outside loop: " + row);
    headVector.addElement("Title");
    headVector.addElement("Type");
    dataTable = new JTable(dataVector, headVector);
    dataTableScrollPane.setViewportView(dataTable);
    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());
    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    } // end if
    } // end finally
    } // end dbTest

    Here's a thread that loads a text file into a JTable:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=315172
    And my reply in this thread shows how you can use a text file as a simple database:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=342380

  • Hiding a column in jtable made from DefaultTableModel.

    I have made my jtable from DefaultTableModel.
    I want to keep one column in the jtable as hidden storing some data containing neccessary information like the "path of the file"
    which need not be shown to the user.
    Please tell me how I can hide one column in the Jtable.
    please provide siome link or code for the same.
    Tia,
    Sarwa

    dayanandabv wrote:
    [http://search.sun.com/search/onesearch/index.jsp?qt=hide+column%2B+JTable&rfsubcat=&col=developer-forums]
    My thought exactly.
    db

  • To change the font of a selected row in a Jtable

    Hello,
    Is it possible to change the font of a selected row in a jtable?
    i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
    thank you.

    String will be left justified
    Integer will be right justified
    Date will be a simple date without the time.
    As it will with this renderer.Only if your custom renderer duplicates the code
    found in each of the above renderers. This is a waste
    of time to duplicate code. The idea is to reuse code
    not duplicate and debug again.
    No, no, no there will be NO duplicated code.
    A single renderer class can handle all types ofdata.
    Sure you can fit a square peg into a round hole if
    you work hard enough. Why does the JDK come with
    separate renderers for Date, Integer, Double, Icon,
    Boolean? So that, by default the rendering for common classes is done correctly.
    Because its a better design then having code
    with a bunch of "instanceof" checks and nested
    if...else code.This is only required for customization BEYOND what the default renderers provide
    >
    And you would only have to use instanceof checkswhen you required custom
    rendering for a particular classAgreed, but as soon as you do require custom
    renderering you need to customize your renderer.
    which you would also have to do with theprepareRenderer calls too
    Not true. The code is the same whether you treat
    every cell as a String or whether you use a custom
    renderer for every cell. Here is the code to make the
    text of the selected line(s) bold:
    public Component prepareRenderer(TableCellRenderer
    renderer, int row, int column)
    Component c = super.prepareRenderer(renderer, row,
    , column);
         if (isRowSelected(row))
              c.setFont( c.getFont().deriveFont(Font.BOLD) );
         return c;
    }It will work for any renderer used by the table since
    the prepareRenderer(...) method returns a Component.
    There is no need to do any kind of "instanceof"
    checking. It doesn't matter whether the cell is
    renderered with the "Object" renderer or the
    "Integer" renderer.
    If the user wants to treat all columns as Strings or
    treat individual columns as String, Integer, Data...,
    then they only need to override the getColumnClass()
    method. There is no change to the prepareRenderer()
    code.
    Have you actually tried the code to see how simple it
    is?
    I've posted my code. Why don't you post your solution
    that will allow the user to bold the text of a Date,
    Integer, and String data in separate column and then
    let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.Vector;
    public class TableRendererDemo extends JFrame{
        String[] headers = {"String","Integer","Float","Boolean","Date"};
        private JTable table;
        public TableRendererDemo() {
            buildGUI();
        private void buildGUI() {
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            Vector headerVector = new Vector(Arrays.asList(headers));
             Vector data = createDataVector();
            DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
                public Class getColumnClass(int columnIndex) {
                    return getValueAt(0,columnIndex).getClass();
            table = new JTable(tableModel);
    //        table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
            table.setDefaultRenderer(String.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
            JScrollPane jsp = new JScrollPane(table);
            mainPanel.add(jsp, BorderLayout.CENTER);
            pack();
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private Vector createDataVector(){
            Vector dataVector = new Vector();
            for ( int i = 0 ; i < 10; i++){
                Vector rowVector = new Vector();
                rowVector.add(new String("String "+i));
                rowVector.add(new Integer(i));
                rowVector.add(new Float(1.23));
                rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
                rowVector.add(new Date());
                dataVector.add(rowVector);
            return dataVector;
        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                public void run() {
                    TableRendererDemo tableRendererDemo = new TableRendererDemo();
                    tableRendererDemo.setVisible(true);
            SwingUtilities.invokeLater(runnable);
        class MyTableCellRenderer extends DefaultTableCellRenderer{
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                 super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if ( isSelected){
                    setFont(getFont().deriveFont(Font.BOLD));
                else{
                    setFont(getFont().deriveFont(Font.PLAIN));
                if ( value instanceof Date){
                    SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
                    setText(formatter.format((Date)value));
                if(value instanceof Number){
                   setText(((Number)value).toString());
                return this;
    }Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
    Cheers
    DB

  • Please Help.JTable insert styled text

    Hi all java guru,
    on post http://forum.java.sun.com/thread.jsp?forum=57&thread=485469 i've depicted my scenario in which i have a JTable where i want to add styled text.
    i've implemented a CustomTableModel that maintains information about text style, in such way that when renderer cell, i can rebuild exact text with its style....same method is adopted for CellEditor.
    It is possible to have more than one JTable in my application....then to correctly handle all JTables ' put them in a vector and during editing and rendering i find current focusable/selected JTable and edit/render it.
    Clearly i maintain information about style of text when i insert it, that is when i insert text, i update my CustomTableModel...same thing must be done when i delete text from JTable...that is, i must update CustomTableModel too in this case.
    Because my CellEditor is a JEditorPane component (extend it) i've registered document associated to it to a DocumentListener that notify every time that a remove operation is happens.
    What is the problem now???problem is that when i finish to edit a cell and click on another cell i've got a removeUpdate(DocumenEvent e) event, and i can't distinguish it.....it seems a real remove event....
    In this case(when i change cell) the code that is executes returns wrong result and invalidate all the rest.
    I think error is where i register celleditor , now i do it in CustomCellRenderer class that extend JEditorPane and implements TableCellRenderer.
    Please help me...this is a great trouble that invalidate all my work :(
    Any new idea is welcome.
    regards,
    anti-shock

    Hi stanislav, of course i can...you're a myth :)
    public class CustomCellEditor extends AbstractCellEditor implements TableCellEditor {
           CellEditor cellArea;
         JTable table;
         public CustomCellEditor(JTable ta) {
              super();
              table = ta;
              // this component relies on having this renderer for the String class
              MultiLineCellRenderer renderer = new MultiLineCellRenderer();
              table.setDefaultRenderer(String.class,renderer);
         public Object getCellEditorValue() {
              return cellArea.getText();
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,     int row, int column) {
              int start = 0;
              int end = 0;
                                               // Get current selected table
              TableEditor tb = (TableEditor) TableEditor.getSelectedTable();
              TableModel model = (TableModel) tb.getModel();
              Vector fontInfo = model.getFontFor(row,column);
              CellEditor cellArea = (CellEditor) ((CustomCellEditor)tb.getCellEditor (row,column)).getCellEditor();
              Document doc = cellArea.getDocument();
              String content = tb.getValueAt(row,column).toString();     
              if (doc!=null && fontInfo.size()>0 && !content.equals("")) {
                                                     // This method reads from model and get right style info
                                                     // for current text, and restore them
                                                     restoreFontWithAttributes(doc,fontInfo,content);
              else
                   cellArea.setText(tb.getValueAt(row,column).toString());
              cellArea.rowEditing = row;
              cellArea.columnEditing = column;
              cellArea.lastPreferredHeight = cellArea.getPreferredSize().height;
              return cellArea;
          * @return
         public CellEditor getCellEditor() {
              return cellArea;
         public class CellEditor extends JEditorPane {
              private CellStyledEditorKit k;
              public CellEditor() {
                    super("text/plain","");
                    k = new CellStyledEditorKit();
                    setEditorKit(k);
                    // I tried to add document here, but i have had wrong behavior
                   doc = new DocumentListener() {
                   public void removeUpdate(DocumentEvent e) {
                      // Get current selected table
                      TableEditor tb = (TableEditor) TableEditor.getSelectedTable();
                      TableModel model = (TableModel) tb.getModel();
                      model.updateFontInfo();
                   getDocument().addDocumentListener(doc);
    }Ok, stan...this is my CustomCellRenderer class....as i have already said, i have some style text info mainteined by CustomTableModel associated with JTable.
    I update CustomTableModel every time that an insert and remove operation happens.
    If i add a DocumentListener to CellEditor (that rapresents editor cell of my table) happens that, if i remove some character from an editing cell, i got a removeUpdate event.....and this is right!!! But if i change cell (e.g. supposing editing cell(1,1), click on cell(2,1) then stop edit cell(1,1) and start edit cell(2,1)) i got a removeUpdate event, that I don't wait for to me..
    Look at this:
    empty cell | some text
    cell 0 ------- cell1
    supposing you're in cell1 and you have finished to insert "some text".Then click on cell0, that is empty....then document associated with CellArea(extend JEditorPane) before of the click on cell0 had some text, but after click have no text, then for it a removeUpdate is happens.....and is that one i got..
    it's as if an unique document is associated to all cells, while should be one document for each cell (i hope this is right).
    Clearly, i've same code for renderer, in such way that i can restore style of text on rendering.
    Hope is clear....if U have any idea or suggestion please give to me.
    Tnx a lot Stanislav..
    regards,
    anti-shock

  • How to put data in JTable from database

    hi everyone,
    i want to query the databse and put the result in the JTable and if possible i want to edit some information. For example: i have 5 records in the database query them and place them in JTable and each record has its own status. if i want to change the status For Example: the status of the 4 records are "Cleared" and the other one is "RELEASEd" so if i have JCombo Box to set the 4 records in to RELEASED status and then save the changes is that possible?
    thank you
    dhing

    In [url /thread.jsp?forum=54&thread=387565]this thread I describe how to use a result set as a basis for table data. Check some database tutorials for information on getting a result set.

  • How to create a cell column with JTextArea in JTable

    I am developing an Application using Java Swings. I need to use JTextArea in my JTable. I need the code to do so. I also want to show the scrollbars in the JTextArea.
    Any efforts in this regard would be of great help. Thanks in advance.
    Thanks
    Alagu

    have a look at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=134412

Maybe you are looking for

  • Help on custom function...

    Hi all I'm having a problem with this custom function/report posted on TechNet while back for ConfigMgr 2007 http://social.technet.microsoft.com/wiki/contents/articles/7870.sccm-2007-create-report-of-upcoming-maintenance-windows-by-client.aspx I've m

  • New User - Cannot select drum kit loops

    Hi, I am a trying out GarageBand for the first time and having a lot of fun. However I was following one of the Apple tutorials where I clicked on song writing and had a basic drum track. The tutorial said if you don't like the drum track you can del

  • External VGA stopped working

    Hi, Approximately week or more ago my external VGA port stopped working - Catalyst control center detects new monitor attached, but there is no output signal (at least monitor says so). Monitor itself & cable is tested and works fine. It seems that e

  • ITunes on windows 7 does not recognise my iPhone 5 anymore

    Hi everyone , Today I tried to sync my iPhone 5, I updated it to the latest software and did the same on my PC . Now when I plug in my phone it shows the phone , but thinks its a new one and asks me to delete my phone then reconnect. However there's

  • Another bug in Flow layout ?

    If a Flow object gets its content during initialization it doesn't take the specified size of the children into account. The sizes are kept if the children are added afterwards. But then they're stacked on top of each other; as described in the other