JTable Trouble

I have trouble with the following code. This method could place the data it receives in information onto a JTable but it does not work. The code compiles perfect and the values that information has are correct. I have commented the lines where the data is actually put onto the table. Its about two thirds way down. I would appreciate any help.
Thanks
Michael
public void place_info_table(String information[][])
if(!(information.length > 1))
JOptionPane.showMessageDialog(this,"Sorry, there is no server at present to satisfy your request. ","Peer 2 Peer Client",JOptionPane.ERROR_MESSAGE);
client_open.setEnabled(false);
client_refresh.setEnabled(false); //all buttons except refresh are disabled.
client_search.setEnabled(false);
client_view_files.setEnabled(false);
client_quit.setEnabled(true);
else
client_open.setEnabled(true);
client_refresh.setEnabled(true);
client_search.setEnabled(true);
client_view_files.setEnabled(false); //else all the buttons except view files are enabled
client_quit.setEnabled(true);
int j=0;
for(int i=0;i<information.length;i++) // Here is where the info is added
client_listing.setValueAt(information[0],j,0);
j++;
client_quit.setEnabled(true);
client_refresh.setEnabled(true);
System.out.println(information[i][0]);
client_open.addActionListener(this);
client_refresh.addActionListener(this);
client_search.addActionListener(this);
client_view_files.addActionListener(this);
client_quit.addActionListener(this);

I have trouble with the following code. This method could place the data it receives in information onto a JTable but it does not work. The code compiles perfect and the values that information has are correct. I have commented the lines where the data is actually put onto the table. Its about two thirds way down. I would appreciate any help.
Thanks
Michael
public void place_info_table(String information[][])
if(!(information.length > 1))
JOptionPane.showMessageDialog(this,"Sorry, there is no server at present to satisfy your request. ","Peer 2 Peer Client",JOptionPane.ERROR_MESSAGE);
client_open.setEnabled(false);
client_refresh.setEnabled(false); //all buttons except refresh are disabled.
client_search.setEnabled(false);
client_view_files.setEnabled(false);
client_quit.setEnabled(true);
else
client_open.setEnabled(true);
client_refresh.setEnabled(true);
client_search.setEnabled(true);
client_view_files.setEnabled(false); //else all the buttons except view files are enabled
client_quit.setEnabled(true);
int j=0;
for(int i=0;i<information.length;i++) // Here is where the info is added
client_listing.setValueAt(information[0],j,0);
j++;
client_quit.setEnabled(true);
client_refresh.setEnabled(true);
System.out.println(information[i][0]);
client_open.addActionListener(this);
client_refresh.addActionListener(this);
client_search.addActionListener(this);
client_view_files.addActionListener(this);
client_quit.addActionListener(this);

Similar Messages

  • Please help me..JTable trouble

    Hi all java guru,
    i've have a JTable in which i want to insert some styled text (e.g. bold,underline,italic).... i use a JEditorPane as CellEditor and JEditorPane as renderer. In each JEditorPane i have registered a StyledEditorKit that is used for styles.
    I've noted that when i insert styled text, initially cell maintains text style, but when i click on other cell,style of text disappears....i want to specify that i don't want to add style to entire cell, but i wish to add style at a portion of text.....
    notbold bold | not styled text
    Cell0 ----------------------- Cell1
    Is this behavior normally ???
    Then 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 the in a vector and during editing and rendering i find current focusable JTable and edit/render it.
    It seems a right solution ???
    I insert style on text using a toolbar and menubar in a dynamically way.
    Please, give to me an advice...Is right this solution??Or exist another way to resolve this proble in a more elegant way??
    Tnx in advance
    regards,
    anti-shock

    That's correct.
    Try to set HTMLEditorKit for your editor/renderer JTextPane. In the TableModel you can save text from textPane.getText() and set the text in the renderer component in the appropriate renderer's method.
    regards,
    Stas

  • Trouble updating a JtextArea from a JTable ListSelectionListener..

    Hi, I'm having trouble updating a JtextArea from a JTable ListSelectionListener, it is working for another JTextArea but I have created JNMTextArea which extends JTextArea and I am getting no data passed to it.
    Any help is really greatly appreciated. Im a relative newbie to Java.
    Here is the class declaration for JNMTextArea
    public class JNMTextArea extends JTextArea
         //Constructor
         public JNMTextArea(String text){
              super(text);
              setLineWrap(true);
              setEditable(false);
         //Constructor
         public JNMTextArea()
              this(new String());
         //This sets the data in setText, works ok.
         void displayPacket(Packet p){
              //Function works fine
              //Need to pass this data to the JNMTextArea!!!
              setText(buffer.toString());
              setCaretPosition(0);
    Here is where I use JNMTextArea, Im
    class JNMGui extends JFrame implements ActionListener, WindowListener{
         public static JNMTextArea txtPktContent;
         //Constructor
              JNMGui(){
                   buildGUI();
         private void buildGUI(){
         mainWindow = new JFrame("Monitor");
         tblPacket = new JTable(tblPacketM);
         tblPacket.setToolTipText("Packet Panel");
         tblPacket.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         if (ALLOW_ROW_SELECTION) {
              ListSelectionModel rowSM = tblPacket.getSelectionModel();
              rowSM.addListSelectionListener(new ListSelectionListener() {                     public void valueChanged(ListSelectionEvent e) {
                        if (e.getValueIsAdjusting())
                             return;
                        ListSelectionModel lsm =      (ListSelectionModel)e.getSource();
                        if (lsm.isSelectionEmpty()) {
                             System.out.println("No rows are selected.");
                        else {
                             int selectedRow = lsm.getMinSelectionIndex();
                             selectedRow++;
                             String str;// = "";
                             //Unsure if I need to create this here!
                             txtPktContent = new JNMTextArea();
                             //This works perfectly
                             txtPktType.append ( "Packet No: " + Integer.toString(selectedRow) + "\n\n");
                             Packet pkt = new Packet();
                             pkt = (Packet) CaptureEngine.packets.elementAt(selectedRow);
                             if(pkt.datalink!=null && pkt.datalink instanceof EthernetPacket){
                                  str = "Ethernet ";
                                  //THis works txtPktType is another JTextArea!!          
                                  txtPktType.append ( s );
                                  //This is not working
                                  //I realise displayPacket return type is void but how do get
                                  //the setText it created to append to the JNMTextArea??               
                                  txtPktContent.displayPacket(pkt);
              //Adding to ScrollPane
              tblPane = new JScrollPane(tblPacket);
              txtPktTypePane = new JScrollPane ( txtPktType );
              txtPktTypePane.setToolTipText("Packet Type");
              txtPktContentPane = new JScrollPane ( txtPktContent );
              txtPktContentPane.setToolTipText("Packet Payload");
              panel.add( tblPane, BorderLayout.CENTER );
    //End Class JNMGui

    void displayPacket(Packet p){
              //Function works fine
              //Need to pass this data to the JNMTextArea!!!
              setText(buffer.toString());
              setCaretPosition(0);
    This seems really odd. Notice that you pass in "p" but use "buffer". Where is "buffer" defined?

  • Trouble viewing column headers JTable

    I am having trouble with the column headers showing up. I have added a JScrollPane to the JTable, yet it fails to show up
    Here is the array for the data and column headings:
         String[] tableheadings = {"","Jan", "Feb", "Mar","Apr","Jun", "Jul"};
         Object data[] [] = { { "Rent","","","","","",""},
                             {"Utilities","","","","","",""},
                             {"Groceris","","","","","",""},
                             {"Clothes","","","","","",""},
                             {"Bills","","","","","",""},
                             {"Automobile","","","","","",""},
    and here is the method calling the array and placing into a JTable:
         public void doEside()
              east = new JPanel (new GridLayout(2,1));
              quote = new JLabel ("<HTML><FONT SIZE=+1><CENTER><B>\"Healthy</B>"
                   +"<BR>Wealthy</BR>"
                   +"<BR>and</BR>"
                   +"<BR>Wise\"</BR></CENTER></FONT>", JLabel.CENTER);
              table = new JTable(data, tableheadings);
              DefaultTableModel dmodel = new DefaultTableModel(data, tableheadings)
                   public boolean isCellEditable(int row,int column)
                        return false;
              table = new JTable(dmodel);
              table.setPreferredScrollableViewportSize(new Dimension( 200,70));
              table.getColumnModel().getColumn(0).setPreferredWidth(70);
              table.getColumnModel().getColumn(1).setPreferredWidth(10);
              table.getColumnModel().getColumn(2).setPreferredWidth(10);
              table.getColumnModel().getColumn(3).setPreferredWidth(10);
              table.getColumnModel().getColumn(4).setPreferredWidth(10);
              table.getColumnModel().getColumn(5).setPreferredWidth(10);
              table.getColumnModel().getColumn(6).setPreferredWidth(10);
              table.getTableHeader();
              JScrollPane sp = new JScrollPane(table);
              sp.add(table);
              east.add(quote);
              east.add(table);
              add(east, BorderLayout.EAST);
                   

    That's a Swing question, it should be asked in the Swing forum.
    A JTable always represents the values provided by a TableModel.
    The JTable constructor that directly takes the heading and data is just a convenience constructor which creates a DefaultTableModel and populates it using the supplied arguments.
    You code extract creates two JTable object. The first one (the one with the data and headings) is lost for good after you reassign the variable table to the second JTavble instance. And this second instance is created with an empty DefaultTableModel.
    What you want is probably to create one single JTAble object, using a model created as:
    dtmodel = new DefaultTableModel(data, tableheadings);Edited by: jduprez on Nov 19, 2009 1:18 PM

  • Hi, i'm having trouble in filling a jtable with data

    hi, i'm having trouble in filling a jtable with data, but the real problem is that i have stablished a JDBC connection throught the windowsxp ODBC to my database written on microsoft access platform, so i created my table
    public CenterPanel(){
    panel = new JPanel();
    dataTable = new JTable(10,10);
    dataTable.setBorder(BorderFactory.createLineBorder(Color.black,2));
    panel.add(dataTable);
    setLayout(new BorderLayout());
    add(panel,BorderLayout.CENTER);
    i can see the table on my driver, but i want to fill it by connecting to the database and fil the fields from the database, i have the code to connect and retrieve the fields but on the dos, i want to fill them in the table,
    the code for accessing is
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection conn1 = DriverManager.getConnection      ("jdbc:odbc:EHLAN",
                             "marius","svasdiga");
                   Statement stmt1 = conn1.createStatement();
                   Statement stmt2 = conn1.createStatement();
                   ResultSet rs1 = stmt1.executeQuery ("select * from Appartment");
                   System.out.println("App. Num, Stair Num, Elec. Num");
              while (rs1.next()) {
                   System.out.print (rs1.getInt ("appnum") + ","+" ");
                   System.out.print (rs1.getString ("staircase") + ","+" ");
                   System.out.println (rs1.getInt("electrnum") );
    ResultSet rs2 = stmt2.executeQuery ("select * from Person");
    System.out.println("First Name, Last Name, Blood Type");
              while (rs2.next()) {
                   System.out.print (rs2.getString ("namef") + ","+" ");
                   System.out.print (rs2.getString ("namel") + ","+" ");
                   System.out.println (rs2.getString("bloodType") );
    so help me to fill this data to the table. thank you
    yours sincerely,
    marius ajemian

    hi, i'm having trouble in filling a jtable with data, but the real problem is that i have stablished a JDBC connection throught the windowsxp ODBC to my database written on microsoft access platform, so i created my table
    public CenterPanel(){
    panel = new JPanel();
    dataTable = new JTable(10,10);
    dataTable.setBorder(BorderFactory.createLineBorder(Color.black,2));
    panel.add(dataTable);
    setLayout(new BorderLayout());
    add(panel,BorderLayout.CENTER);
    i can see the table on my driver, but i want to fill it by connecting to the database and fil the fields from the database, i have the code to connect and retrieve the fields but on the dos, i want to fill them in the table,
    the code for accessing is
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection conn1 = DriverManager.getConnection      ("jdbc:odbc:EHLAN",
                             "marius","svasdiga");
                   Statement stmt1 = conn1.createStatement();
                   Statement stmt2 = conn1.createStatement();
                   ResultSet rs1 = stmt1.executeQuery ("select * from Appartment");
                   System.out.println("App. Num, Stair Num, Elec. Num");
              while (rs1.next()) {
                   System.out.print (rs1.getInt ("appnum") + ","+" ");
                   System.out.print (rs1.getString ("staircase") + ","+" ");
                   System.out.println (rs1.getInt("electrnum") );
    ResultSet rs2 = stmt2.executeQuery ("select * from Person");
    System.out.println("First Name, Last Name, Blood Type");
              while (rs2.next()) {
                   System.out.print (rs2.getString ("namef") + ","+" ");
                   System.out.print (rs2.getString ("namel") + ","+" ");
                   System.out.println (rs2.getString("bloodType") );
    so help me to fill this data to the table. thank you
    yours sincerely,
    marius ajemian

  • Having trouble with multiple lines of text in a JTable

    Hello,
    I am trying to use a JTable rather like a table in Word so that as I type text into a cell that row of cells grows in height to accomodate the text typed.
    I used custom cell editors and renderers to put a JTextField (I think it was) into each cell. These allow the entry of more than one line but the row height is still wrong. So I interceot every key press and work out the height of the custom editor, and set the row height to the max of the cells in the row on each key depression. However, this is a very clunky solution and also does not cope with cell resizing.
    I can't believe that it is this hard to get cells/rows that resize in response to typing. So I'd be grateful if someone knows of a better way of doing this.
    Many thanks in advance...
    Gary

    I've never tried it buy you can read the Swing tutorial on "How to Use HTML is Swing Components":
    http://java.sun.com/docs/books/tutorial/uiswing/TOC.html

  • Trouble with JTables

    So i can make my JTable and can remove, add and insert values. What i would like to know is
    1) Is it possible to prevent cells from being edited and still be able to be selected (i.e. not using setEnabled(false)). I have used a table model that doesnt allow the data to be permanently changed but double clicking on a cell allows you to edit the data but on the click else where or pressing enter the data returns to its previos value which is sort of what i want but i would prefer if you could just select the row and not be able to change the data even for a few seconds.
    2) Is there anyway to make the columns stay where they are? What i mean is when a table is made you can switch the columns round with the mouse which is a feature i do not want?
    So if any one can help could you please

    1) You can't help that...it's a stupid design in the JTable.
    2) jTable1.getTableHeader().setReorderingAllowed(false); That fixes #2.

  • Trouble understanding JTable renderers

    I dont properly understand how to JTable.
    In the application I'm writing, I have on main JFrame, with a menu.
    Onto this I load a jTabbed pane and then onto this a JTable , with
    some data loaded from a file , some coulmns are text , others integers
    floats and theres one date column
    I've successfully set up a TableModel extending AbstractTableModel
    as a separate class java file. I can set column widths ok too.
    But I cant get the renderer working , the numeric coumns are left aligned.
    Question 1 :How do I get a column of numeric data in a JTable to be right aligned? Some examples I have found seem to refer to specific cells eg
    // in the custom renderer...
    if(value instanceof Double)
    setHorizontalAlignment(SwingConstants.RIGHT);
    setText(value);
    I've also read this sites JTable tutorial but still dont understand the
    renderer bit.
    Question 2 : where do I put the renderer code, in with the table model
    class file , or in my main application (where I define the column widths)?
    [The JDK is 1.4, the OS is win 98.]
    Thanks in advance for any help
    Mike2z

    HONK !
    Thanks for the reply. The code
    public Class getColumnClass(int c)
    switch (c)
    case 0: return Integer.class;
    case 1: return String.class;
    case 2: return String.class;
    case 3: return String.class;
    case 4: return String.class;
    case 5: return String.class;
    case 6: return Integer.class;
    case 7: return Float.class;
         case 8: return Float.class;
    case 9: return Float.class;
    case 10: return Floatclass;
    default : return getValueAt(0, c).getClass();
    // return getValueAt(0, c).getClass();
    // return Object.class;
    seems to be the key. When I use that (instead of either of the commented
    out lines I was trying before) it works in that numbers are right
    aligned.
    However when I attemp to right scroll on the scroll pane I get a garbled display and the error :
    java.lang.IllegalArgumentException: Cannot format given Object as a Number
         at java.text.NumberFormat.format(NumberFormat.java:219)
         at java.text.Format.format(Format.java:133)
         at javax.swing.JTable$DoubleRenderer.setValue(JTable.java:3348)
         at javax.swing.table.DefaultTableCellRenderer.getTableCellRendererComponent(DefaultTableCellRenderer.java:160)
         at javax.swing.JTable.prepareRenderer(JTable.java:3682)
         at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:1149)
         at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1051)
         at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:974)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
         at javax.swing.JComponent.paintComponent(JComponent.java:537)
         at javax.swing.JComponent.paint(JComponent.java:804)
         at javax.swing.JComponent.paintChildren(JComponent.java:643)
         at javax.swing.JComponent.paint(JComponent.java:813)
         at javax.swing.JViewport.paint(JViewport.java:707)
         at javax.swing.JComponent.paintChildren(JComponent.java:643)
         at javax.swing.JComponent.paint(JComponent.java:813)
         at javax.swing.JComponent._paintImmediately(JComponent.java:4642)
         at javax.swing.JComponent.paintImmediately(JComponent.java:4464)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:404)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:443)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:190)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    If I just use
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();          // this
    // return Object.class;          // or this
    I can right scroll without that error appearing, but am back to the original problem of left aligned numeric data.
    Don't suppose you encountered the same problem?
    Mike2z

  • Trouble with JTable.prepareRenderer: NullPointerException

    Hello all,
    I managed to display data from MySQL into a JTable, but unable to properly sort the Integer columns.
    I searched around for a solution and came up with this:
    DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames){
                @Override
                public Class getColumnClass(int column) {
                    switch(column) {
                        case 0: return String.class;
                        default: return int.class;
           jTable1.setModel(tableModel);
           jTable1.setRowSorter(new TableRowSorter(tableModel));I had to declare rowData[][] as String to accommodate the leftmost column, which is a String.
    Object[][] rowData = new Object[column1.length][columns.length];}Having overridden getColumnClass(int col), I tried to compile again and got this error:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at javax.swing.JTable.prepareRenderer(JTable.java:5729)I remove the overriding, and it compiles fine. But the integers doesn't sort properly.
    Can anybody give me a hint on this?
    Thanks in advance.

    Hello Walter and Darryl, thanks for your solution.
    I replaced return int.class to return Integer.class. It compiles fine. However the integers still don't sort properly.
           DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames){
                @Override
                public Class getColumnClass(int column) {
                    switch(column) {
                        case 0: return String.class;
                        default: return Integer.class;
           };The code does work, because I wrote a short piece to check the class of the columns and the results were as expected.
           for (i=0;i<columnNames.length;i++){
               System.out.println(jTable1.getColumnClass(i));
           }results:
    class java.lang.String
    class java.lang.IntegerSo now the column class is java.lang.Integer, which means sorting should be properly done, but it's not.
    Are there any other reasons why the integers are not sorting properly?
    Thanks in advance.

  • Trouble with resizing jpanels / jscrollviews and jtables

    Hi,
    This is not exactly my code but the problem is the same.... When I run this I get a nice view, exacty how I want it. however when I resize the frame I get these problems
    1) Upon maximize the scroll view stays with the table and doesn't expand down
    2) When you shrink the window to less space than the table then the scroll bars don'r adjust and you loose the panel at the bottom, even though its not in the scroll view...
    Help is definately required here..
    Code:
    * Window2.java
    * Created on den 16 november 2005, 10:11
    /** you probably don't need this (for the forum)
    package se.mazarin.battrick.gui;
    * @author Benjamin Janes
    public class Window2 extends javax.swing.JFrame {
    /** Creates new form Window2 */
    public Window2() {
    initComponents();
    /** 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.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;
    pnlViewPanel = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jPanel1 = new javax.swing.JPanel();
    bmStatus = new javax.swing.JTextField();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    pnlViewPanel.setLayout(new java.awt.GridBagLayout());
    jTable1.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {
    {null, null, null, null},
    {null, null, null, null},
    {null, null, null, null},
    {null, null, null, null}
    new String [] {
    "Title 1", "Title 2", "Title 3", "Title 4"
    jTable1.setAutoCreateColumnsFromModel(false);
    jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
    jTable1.setAutoscrolls(false);
    jTable1.setMaximumSize(new java.awt.Dimension(1600, 1200));
    jTable1.setPreferredSize(new java.awt.Dimension(1024, 768));
    jScrollPane1.setViewportView(jTable1);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    pnlViewPanel.add(jScrollPane1, gridBagConstraints);
    getContentPane().add(pnlViewPanel, java.awt.BorderLayout.NORTH);
    jPanel1.setLayout(new java.awt.BorderLayout());
    bmStatus.setBackground(new java.awt.Color(224, 223, 227));
    bmStatus.setEnabled(false);
    bmStatus.setMaximumSize(new java.awt.Dimension(1600, 20));
    bmStatus.setMinimumSize(new java.awt.Dimension(800, 20));
    bmStatus.setName("bmStatus");
    bmStatus.setPreferredSize(new java.awt.Dimension(1024, 20));
    jPanel1.add(bmStatus, java.awt.BorderLayout.SOUTH);
    getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
    pack();
    // </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Window2().setVisible(true);
    // Variables declaration - do not modify
    public javax.swing.JTextField bmStatus;
    public javax.swing.JPanel jPanel1;
    public javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTable jTable1;
    public javax.swing.JPanel pnlViewPanel;
    // End of variables declaration
    }

    Erk - nasty generated code!!
    It looks like you've added the scroll pane to the north of your layout manager whereas the center might be more appropriate.
    More precisely: you've added the panel that contains your scroll pane to the north of the your content pane.
    Hope this helps.

  • Trouble with components and JTables

    hey everyone i have a question. i created a gui that has 2 panels each containing a table. each table contains a certain amount of default data. i have a jmenu bar also and when one of the menus is clicked a dialog is presented that returns a new sql statement to place into the table. that all works fine i get the sql statement i search the database and all is good.
    here is my problem
    when i try to remove the table from the panel an add a new table to the same panel nothing is presented but a blank panel.(ie the table doesnt show up). but if i add the new table to a seperate frame the new table shows up fine. any suggestions
    matt
    [email protected]

    use java.awt.CardLayout

  • How to print a JTable  in Java Swing ?

    Hi,
    I have an application written in java swing.Now I want to write a print module that prints some details.The details includes the JTextArea and JTable that changes in size dynamically.One solution i found is to put them in a panel and print that panel.But it is static.The size of JTable and JTextArea changes, according to the given input.Please give me a solution for this.

    Printing is a bit of a nightmare, actually. Most of the trouble is layout. Basically a Printable is passed a page number and a graphics context and has to work out what components go on that page and where. It can't depend on the pages being requested in sequence.
    You can call getPrintable from a JTable, and you can call that through your own Printable in order to add extra pages. However you can't ask a Printable how many pages it's going to produce, you just have to invoke it and see if it returns a code to say that the page is out of range.
    And the Printable JTable generates is very limited, the table has to occupy full pages, you can't tell it to start in a different place on the first page, or find out how much space it's used on the last page. The headers and footers generate JTable's own idea of a page number, not yours.
    You can call print() on most Swing components, but you'll need to set their size and location first, and/or mess with the transformation in the graphics context.

  • Changing a JTable's model

    Hello everyone,
    I dont have a whole lot of experience w/ JTables and this problem has been troubling me for a while now. I have a JTable that significantly changes when the user hits the calculate button, so instead of going through the trouble of completely reformatting the table by adding/removing columns and table headers, I simple make a new model and set the table's model to the new one, and then call table.updateUI(). The problem is that my custom cell renderer that displays a down or up arrow depending on how the given column is sorted stops working. The sorter works properly and the table displays properly, but the arrows do not change from up to down or vise versa when a column is resorted. The whole process works just fine the first time, but the more times the user pushes the calculate button the more off it gets. I have added a flag in the actionPerformed method in my cell renderer that tells me when the table header is clicked. Every time the calculate button is hit, more flags appear when the table header is clicked. Therefore the arrows change position on odd numbers and do not on evens (because the evens cancel eachother out and the arrow appears to sit still), however the sorter still works properly. It seems as though somehow a new mouse listener or cell renderer is added after each time the calculate button is pressed. Either that or the entire table is not being reset somehow and something is still invisible in the background.
    Here is some of my code.
    // The initial table with no data
    String[] str = {"class 1", "class 2", "class 3", "class 4", "class 5", "= GPA"};
    String[][]  data= {{"", "", "", "", "", ""},
    pmModel = new ProjectionModel(str, data);
    mainTable = new JTable(pmModel);
    mainTable.getTableHeader().setDefaultRenderer(new SortButtonRenderer());
    // After the calculate button has been pushed:
    // The table is reset here. TableSorter extends TableMap
        ProjectionModel newModel = new ProjectionModel(courseList, charList);
        TableSorter sorter = new TableSorter(newModel);
        // this method is shown below
        sorter.addMouseListenerToHeaderInTable(mainTable);
        sorter.sortedUp = false;
        mainTable.addNotify();
        mainTable.setModel(sorter);
        // SortButtonRenderer extends TableCellRenderer
        SortButtonRenderer renderer = new SortButtonRenderer();
        mainTable.getTableHeader().setDefaultRenderer(renderer);
        // set the arrow to DOWN on the first column
        renderer.setSelectedColumn(0);
        renderer.setSelectedColumn(0);
        mainTable.updateUI();
    // This is the addMouseListenerToTable(JTable table) found in the TableSorter class
        public void addMouseListenerToHeaderInTable(JTable table) {
            final TableSorter sorter = this;
            final JTable tableView = table;
            tableView.setColumnSelectionAllowed(false);
            MouseAdapter listMouseListener = new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    TableColumnModel columnModel = tableView.getColumnModel();
                    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                    int column = tableView.convertColumnIndexToModel(viewColumn);
                    if (e.getClickCount() == 1 && column != -1) {
                      SortButtonRenderer renderer =
                            (SortButtonRenderer)tableView.getTableHeader().getDefaultRenderer();
                        //int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
                        //boolean ascending = (shiftPressed == 0);
                        boolean ascending = (renderer.getLastColumn() == column && !sortedUp);
                        renderer.setLastColumn(column);
                        sorter.sortByColumn(column, ascending);
                        if (ascending) sortedUp = true;
                        else sortedUp = false;
                        renderer.setSelectedColumn(column);
                        // the flag that prints the column that is pressed
                        System.out.println(column + " " + sortedUp);
            JTableHeader th = tableView.getTableHeader();
            th.addMouseListener(listMouseListener); // it seems like i need a way to remove any
    // previous mouseListeners here, i think this would solve the problem
        }The flag's output looks something like this:
    < first time calculate button is clicked >
    < column 0 is clicked> 0 false
    < column 0 is clicked again > 0 true
    < second time calculate button is clicked >
    < column 0 is clicked >
    0 false
    0 true
    notice they cancel eachother out so the arrow stays in the same position
    < third time calculate button is clicked >
    < column 0 is clicked >
    0 false
    0 true
    0 false
    notice they dont cancel eachother out, so the arrow changes positions
    This problem is really bugging me. I appreciate any help. Thanks.
    -kc

    Well I fixed my problem but I kind of cheated...
    I used a static variable in the class that inits the GUI to keep track of the MouseListeners that are added to the table headers by the TableSorter. In the TableSorter class's addMouseListenerToTableHeader(JTable table) class I added a line of code before the "th.addMouseListener(listListener)" line: "th.removeMouseListener(Projector.lastListener))"
    It works but it kind of sucks. If there is a better way to do it that would be great. I'm sorry if you read through all of that stuff and then I ended up fixing my own problem anyway :(
    Thanks anyway.
    -kc

  • Trying to add a new row to a JTable

    I'm having trouble adding a row dynamically to a JTable. I've been able to populate the table with an array and that works well, but how do you add new rows after the program is running?

    You need to make TableModel that does dynamic resizing od the underlying data 2d array. This one will resize for both rows and columns.
        private Vector dataNames= new Vector();
        private Vector dataData =new Vector();
            javax.swing.table.TableModel dataModel = new javax.swing.table.AbstractTableModel()
                public int getColumnCount()
                    return dataNames.size();
                public int getRowCount()
                    return dataData.size();
                public Object getValueAt(int row, int col)
                    try
                        java.util.Vector v=(java.util.Vector)dataData.elementAt(row);
                        return v.elementAt(col);
                    catch(Exception e)
                        System.out.println("e :"+e.getMessage());
                        return null;
                public String getColumnName(int column)
                    return (String)dataNames.elementAt(column);
                public Class getColumnClass(int col)
                    if(getValueAt(0,col)!=null)
                        return getValueAt(0,col).getClass();
                    else
                        if(col==0)
                            return Integer.class;
                        else if(col==1 || col==2)
                            return Double.class;
                        else
                            return String.class;
                public boolean isCellEditable(int row, int col)
                    if(col > 0 && col <4)
                        return mapTableEditable;
                    else
                        return false;
                public void setValueAt(Object aValue, int row, int column)
                    if(row>=dataData.size())
                        if(dataData.size()==0)
                            for(int i=0;i<row+1;i++)
                                dataData.addElement(new java.util.Vector());
                                java.util.Vector v2=(java.util.Vector)dataData.lastElement();
                                v2.setSize(getColumnCount());
                        else
                            java.util.Vector v1=(java.util.Vector)dataData.lastElement();
                            int dataSize=row-dataData.size()+1;
                            for(int i=0;i<dataSize;i++)
                                dataData.addElement(new java.util.Vector());
                                java.util.Vector v2=(java.util.Vector)dataData.lastElement();
                                v2.setSize(v1.size());
                    java.util.Vector v=(java.util.Vector)dataData.elementAt(0);
                    if(column>=v.size())
                        for(int i=0;i<dataData.size();i++)
                            v=(java.util.Vector)dataData.elementAt(i);
                            v.setSize(column+1);
                    if(row<dataData.size())
                        v=(java.util.Vector)dataData.elementAt(row);
                        v.setElementAt(aValue,column);
            };

  • Filtering the rows of a JTable based on JCombobox selection

    Hi,,,
    I write an application where I have a combobox contains the JTable first column data when i click on the item it should give me the rows, which contains the selected item as their first column data. I am enable to get the list like that, please, help me in this.........................................
    Thanks In Advance,
    Sun_sgrk

    Hi Albert,
    I write the code like this.............., please, check it, if I am following any where wrong let me know.......
         JComboBox filterCb=(JComboBox)evt.getSource();
            if(filterCb==filterComboBox){
                for(int i=0;i<wtOb.length;i++){
                    for(int j=0;j<4;j++){
                        if(wtOb[0].toString()==filterComboBox.getSelectedItem())
    System.out.println(""+wtOb[i][j]);
    This code I written in netbeans, when I am printing the values of wtOb[i][j] in console its getting the rows, suppose I am selecting the topic as GeneralTopic then its givining me the output as-----
    GeneralTopic
    Dealer5
    Player3
    BlackJack2
    GeneralTopic
    Dealer7
    Player6
    BlackJack
    but I am getting the trouble when i want to show these rows only in my table, please, give me any suggestion or any help to resolve it. I tried with table.setModel also but its not working.
    Regards,
    sun_sgrk

Maybe you are looking for

  • At My Wits End - Please Help Before I Contact OFCO...

    I have been loyal BT customer since... well having a landline in my name. We have been experiencing problems with BT / BT Broadband now for over 3 months. During this period we have had over 6 engineer visits an countless phone calls to BT Customer S

  • ITunes won't start after Windows 7 Repair install

    Hi there I recently had to repair my Windows 7 64 bit Home Premium edition installation. It warned me before reinstalling that there could be some problems with iTunes following the repair but I followed the instructions to counter this and repair Wi

  • Drag and Drop onto a Panel

    Does anybody know how to enable drag and drop onto a panel? I need my users to be able to choose an image from a grid and place it where ever they want on a panel or something. How can I do this in flex? I know how to do drag and drop from grid to gr

  • Dialog Proces

    Hi All, I came across this situation today, all the Dialog work processes of the server were u2018runningu2019 and it was same for all the Update work processes .Semaphores could also be seen in front of respective work process (SM50).This occurs 2-3

  • Can't see Shared Libraries with iTunes 7

    I can no longer see shared music/libraries since I updated to iTunes 7. My roommate can but she can only see her own music. She has a Windows XP computer, I have a Mac Powerbook running OS X 10.4.7. Also, when I quit sometimes, it says people are con