JTable, L&F and a TableCellRenderer

hey guys :)
i have a lil prob in my swing application. i use a JTable to display my data and i use custom CellEditors and CellRenderers - so far so good. the problem i have now, that the cell itself isnt highlighted (in any way) if it's row is currently selected.
therefore i took my renderer and changed this method:
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
if(isSelected)
     setBackground(new Color(204,204,255));
     System.out.println("selected");
else
     setBackground(Color.white);
[...]that's in accordance with the metal L&F color scheme.
it works - but it's not the right way to do that... and if the user changes the L&F it's obvious.
my question is, how can i get the colors (foreground and background) wich i have to use?
(i know it's an L&F method but i hadnt found it up to now)
ta :)

If the component you are producing is a JLabel then the easiest way to do this is to make your TableCellRenderer extend the DefaultTableCellRenderer and start your getTableCellRendererComponent method with a call to the same method in the superclass e.g.
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
// ... make your other changes to label
return label;
This is the easiest way to get all the selection, focus, etc. behaviour
so long as you can use the JLabel.
If you need to know how to do it for a different component ask.

Similar Messages

  • Refreshing JTable contents (rows and columns) handling.

    Hi,
    I have a general question related to refreshing the contents of JTable and handling some application specific requirements.In our application we are planning to refresh the contents of JTable automatically after certain period of time by fetching data from database and update the JTable contents or user has clicked refresh button.
    But following scenarios we are planning to handle when refresh is called automatically or user has clicked refresh button.
    1) User is working with data of JTable. Like rows of JTable has checkBoxes and user selects them and doing operation like viewing the details of selected rows in new details dialog. So if refreshing is done then the selection will be lost if I update the whole data in JTable.
    a)Will it be possible to append the data at the end of JTable rows without disturbing the existing JTable contents.
    b) Is it feasible to compare the data of existing rows and newly fetched rows and update only the rows whose values are changed in database or update specifically updated columns. But this comparision for finding changed values will result in performance problems.So are there any other alternatives of doing this, ideas are most welcome.
    c) Simple way is to alert the user that data will be updated and everything will be refreshed will be the choice in worst case.
    I guess many may have encountered such problems and may have solved it depending on the product requirements.
    Ideas and suggestions are most welcome.
    Regards.

    Hi,
    Here are my views and my assumptions.
    Assumptions :
    1) Your JTable is populated with list of Objects.
    2) Your tables in database is having columns like created date, created time, updated date updated time
    3) Order by clause for all the time will remain same.
    If these assumptions are correct then I think you can achieve your goal.
    Here how it is.
    Your application session will maintain last db hit time and will maintain for every hit that applicate made to fetch data from db.
    When object is created on the server side once it fetch data from table it will compare the created date/time or update date/time with the session varibale that holds last visit date/time. Based on this flag need to be set to indicate if this item is added/updated/deleted since last visit.
    And when all these object is returned to your client, the table model will iterate through the list and based on object index in the list and and if object is changed will update only that perticular row.
    Hope this is what you want to achieve.
    Regards

  • Multi threading race condition in JTable while rendering and truncating?

    Hi All,
    It seems that there is a race confition when rendering a large table which is truckated by another thread while rendering it on a JTable view.
    Let me try to explain what I think is the problem:
    When considering the folowing code from BasicTableUI
    First the size of the tbale model is determined in
    public void paint(Graphics g, JComponent c) {
    [snip]
            if (rMax == -1) {
             rMax = table.getRowCount()-1;
            }then this cMax is passed to:
    private void paintCells(Graphics g, int rMin, int rMax, int cMin, int cMax) {
         JTableHeader header = table.getTableHeader();
         TableColumn draggedColumn = (header == null) ? null : header.getDraggedColumn();
         TableColumnModel cm = table.getColumnModel();
         int columnMargin = cm.getColumnMargin();
            Rectangle cellRect;
         TableColumn aColumn;
         int columnWidth;
         if (table.getComponentOrientation().isLeftToRight()) {
             for(int row = rMin; row <= rMax; row++) {
              cellRect = table.getCellRect(row, cMin, false);
                    for(int column = cMin; column <= cMax; column++) {
                        aColumn = cm.getColumn(column);
                        columnWidth = aColumn.getWidth();
                        cellRect.width = columnWidth - columnMargin;
                        if (aColumn != draggedColumn) {
                            paintCell(g, cellRect, row, column);
                        cellRect.x += columnWidth;
         } else {The prepareRenderer works like this:
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Object value = getValueAt(row, column);
    [snip]
         return renderer.getTableCellRendererComponent(this, value,
                                                       isSelected, hasFocus,
                                                       row, column);
        }Here the above getValueAt is called for every cell to be rendered (in one thread) , while async a row can be deleted (in another thread) while the tables rendereing is still in progress. This leads to a value to be unexpectedly be null in the above return renderer.getTableCellRendererComponent method call: this method could return an empty panel to indicated that the cell is gone which is strange behaviour because the row doesn't exists anymore. The other option would be to return a null renderer so that the cell won't be rendered but that is impossible because the code doens't expect a null renderer. The third option could to be synchronize somehow the 2 threads so that any delete on the model has to wait until the rendering has finished.
    A possble solution could be to make paintCells at least protected and change to code to see if the designated row still exists, and if not don't increment the row height
    Any help/feedback is greatly appreciated!
    Note that this question is based upon Java5 and I do not know if this is also true for Java6
    Thnx
    Andr'e

    So this means that a TableModel must be manupulated (setValueAt , adding deleting and/or updating objects in this TableModel) through a thread in the EventQueue!
    i.e. (pseudo code)
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    getTableModel().setValueAt(........)
            });A

  • Custom JTable cell editors and persistence

    I have a JTable with an underlying data model (an extension of AbstractTableModel) that uses custom cell editors in the last column. The cell editor in that column, for a given row, depends on the value selected in another column of the same row. The cell editors include text, date, list, and tree editors (the last one in a separate dialogue). The number of rows is changeable.
    I have need to persist the data for a populated table from time to time, for restoration later on. I've achieved that, such that the data model is recreated, the table appears correct, and the appropriate cell editors activated (by creating new instances of the editors' classes).
    However, my problem is that the (custom) cell editors do not reflect the data in the model when editing mode is begun the first time after restoration. Eg. the text editor is always empty, the list editor shows the first item, and no node is selected in the tree editor.
    If I've restored the model correctly, should the editors properly reflect the underlying data when they are set to editing mode?
    I suspected not, and thus tried to explicitly 'set' the correct values immediately after each editor is recreated ... but to no avail.
    Does anyone have any thoughts, or experience with something similar? I'm happy to supply code.

    You can use html tags within Swing, so I think you can do the following:
    * MyRenderer.java
    * Created on 26 April 2007, 10:27
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package newpackage;
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.table.TableCellRenderer;
    * @author CS781RJ
    public class MyRenderer extends JLabel implements TableCellRenderer
        public MyRenderer()
            setHorizontalTextPosition(SwingConstants.RIGHT);
            setIconTextGap(3);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column)
            if (isSelected)
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            else
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            if (value instanceof String)
                if ((value != null) && (value.toString().length() > 0))
                    System.out.println("Value: " + value.toString());
                    setFont(new java.awt.Font("Tahoma", 0, 11));
                    setText("<html>" + value.toString().replaceAll("\n", "<br>") + "</html>");
            return this;
    }In the class that has the JTable, use the code AFTER declaring the values, columns, etc:
    jTable1.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
    jTable1.setValueAt("Riz\nJavaid", 0, 0);One thing I haven't done is to resize the cell heights, make sure this is done.
    Hope this helps
    Riz

  • [JTable] prepareRenderer() override and foreground selection setting

    Hello,
    I can't solve this problem :
    To get a JTable's cell blinking in different colors, I overrided the JTable's prepareRenderer() method : this works fine.
    "But", because there's always a butt, if I restore the cell default background and foreground color when I want the cell to stop blinking, I lose the cell selection foreground color. If I don't restore those colors, the cell selection foreground color (translucent blue) is kept, but cell background and foreground colors will remain in the last blinking state.
    Can you see why or should I submit it as a Java bug (I already read and followed other topics on cell blinking, but it doesn't cover this very point) ?
    Here is the problematic code snippet (to get this method called, I manually and regularly trigger a fireTableCellUpdated() in a thread). The alternative issue is commented in it :
            public Component prepareRenderer(TableCellRenderer renderer,int row,int column) {
                Component res;
                res = null;
                res = super.prepareRenderer(renderer,row,column);
                // conditions required to make the cell blink
                if(
                   (isRunningThreadNewLog) &&
                    (row == 0) &&
                    (column == 0)
                   (! isCellSelected(row,column))
                    res.setBackground(newItemColor[0][lastItemColorIndex]);
                    res.setForeground(newItemColor[1][lastItemColorIndex]);
                    lastItemColorIndex = (lastItemColorIndex + 1) % newItemColor[0].length;
                * Here is where the problem occurs :
                *  - if I build ans runs as it, cell selection foreground will be painted with the default translucent blue color, but cell background and foreground colors won't be reset
                *  - if I uncomment, build and run, ccell background and foreground colors will be paint, but cell forground will be lost, or exactly, it will be painted to the cell foreground color, not the cell selection foreground color
               else {
                    res.setBackground(defaultItemColor[0]);
                    res.setForeground(defaultItemColor[1]);               
                return res;
            }Thanks for help :)
    Edited by: Rockz on Mar 5, 2009 1:19 PM

    or should I submit it as a Java bugLets see, you write some custom code and it doesn't work the way you want it to, so it must be a Java bug?
    Did you ever think it might be a problem with your code?
    First of all, whats with all the brackets in the if statement? Why do you try to group the row and column test?
    So lets take a look at your code. You have 4 conditions. If any one of them fail then you will go into the "else" which automatically resets the foreground and background colors "even" if the isCellSelected() test is true.
    Basically, the isCellSelected should be a separate test. Maybe something like:
    if (! isCellSelected(...))
        if (isRunningThreadNewLog
        && row == 0
        && column == 0)
            // do something
        else
            // do something else
    }If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • JTable custom selection and mouse drag events

    Hello
    I am currently experiencing a problem when using a JTable and a custom selection. I have made a small example to demonstrate the probem. Selection works for this example by listening for when the user clicks or clicks and drags (button held down) and moves the mouse across cells in the table. For each MouseEvent received in the MouseMotionListener mouseDragged method I store the coordinates of that cell at the point of the mouse and render the cell at those coordinates with a line border allowing a more versatile cell selection. The problem that occurs is when you click+drag and move the mouse fast, it looks MouseEvents are created every x milliseconds so when you move fast there isn't a MouseEvent raised for each cell in the click+drag from A -> B. If you run the following example then click and hold down the mouse button and move fast downwards from the top of the table to the bottom you can see that not all the cells are selected vertically.
    Is there someway of increasing the mouse poll (if this is indeed the problem) during the click+drag or a better solution to this problem that any one knows!?
    I have tried attaching the example but it exceeded the message length for the forum post here is a link to code
    [http://www.oneandonlyluppy.pwp.blueyonder.co.uk/TableTest.java]
    [http://www.oneandonlyluppy.pwp.blueyonder.co.uk/TableTest.zip] <-- Contains the source and compiled classes
    I'll try adding the code again as a separate post
    Thanks
    Edited by: oneandonlyluppy on Jan 8, 2009 2:44 AM
    Edited by: oneandonlyluppy on Jan 8, 2009 2:45 AM

    AFAIK the mouse polling rate is OS dependent (being interrupt driven), and may even be affected by processor load. What you could do is store the mouse location (Point) of the last mouseDragged event, and compute a line to the current location, then use some coordinate geometry to identify any intervening cells which are presently being skipped.
    db

  • JTable fixed Row and Column in the same window

    Hi
    Could anyone tip me how to make fixed row and column in the same table(s).
    I know how to make column fixed and row, tried to combine them but it didnt look pretty.
    Can anyone give me a tip?
    Thanks! :)

    Got it to work!
    heres the kod.. nothing beautiful, didnt clean it up.
    * NewClass.java
    * Created on den 29 november 2007, 12:51
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package tablevectortest;
    * @author Sockan
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class FixedRowCol extends JFrame {
      Object[][] data;
      Object[] column;
      JTable fixedTable,table,fixedColTable,fixedTopmodelTable;
      private int FIXED_NUM = 16;
      public FixedRowCol() {
        super( "Fixed Row Example" );
        data =  new Object[][]{
            {      "","A","A","A","",""},
            {      "a","b","","","",""},
            {      "a","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "I","","W","G","A",""}};
        column = new Object[]{"A","B","C","D","E","F"};
        AbstractTableModel fixedColModel = new AbstractTableModel() {
          public int getColumnCount() {
            return 1;
          public int getRowCount() {
            return data.length;
          public String getColumnName(int col) {
            return (String) column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel    model = new AbstractTableModel() {
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col+1];
          public Object getValueAt(int row, int col) {
            return data[row][col+1];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col+1] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedTopModel = new AbstractTableModel() {
          public int getColumnCount() { return 1; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedModel = new AbstractTableModel() {     
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return FIXED_NUM; }
          public Object getValueAt(int row, int col) {
            return data[row + (data.length - FIXED_NUM)][col+1];
        table = new JTable( model );
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTable = new JTable( fixedModel );
        fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedColTable= new JTable(fixedColModel);
        fixedColTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedColTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTopmodelTable = new JTable(fixedTopModel);
        fixedTopmodelTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTopmodelTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);   
        JScrollPane scroll      = new JScrollPane( table );
         scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
          public void setColumnHeaderView(Component view) {}
        fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        fixedScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        JScrollBar bar = scroll.getVerticalScrollBar();
        JScrollBar dummyBar = new JScrollBar() {
          public void paint(Graphics g) {}
        dummyBar.setPreferredSize(bar.getPreferredSize());
        scroll.setVerticalScrollBar(dummyBar);
        final JScrollBar bar1 = scroll.getHorizontalScrollBar();
        JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
        bar2.addAdjustmentListener(new AdjustmentListener() {
          public void adjustmentValueChanged(AdjustmentEvent e) {
            bar1.setValue(e.getValue());
        JViewport viewport = new JViewport();
        viewport.setView(fixedColTable);
        viewport.setPreferredSize(fixedColTable.getPreferredSize());
        fixedScroll.setRowHeaderView(viewport);
        fixedScroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedColTable
            .getTableHeader());   
        JViewport viewport2 = new JViewport();
        viewport2.setView(fixedTopmodelTable);
        viewport2.setPreferredSize(fixedTopmodelTable.getPreferredSize());
        scroll.setRowHeaderView(viewport2);
        scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTopmodelTable
            .getTableHeader()); 
        scroll.setPreferredSize(new Dimension(600, 19));
        fixedScroll.setPreferredSize(new Dimension(600, 100)); 
        getContentPane().add(     scroll, BorderLayout.NORTH);
        getContentPane().add(fixedScroll, BorderLayout.CENTER);   
      public static void main(String[] args) {
        FixedRowCol frame = new FixedRowCol();
        frame.addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent e ) {
            System.exit(0);
        frame.pack();
        frame.setVisible(true);
    }

  • Issue with re-sizing JTable Headers, JTabbedPane and JSplit pane

    Ok, hopefully I'll explain this well enough.
    In my Swing application I have a split pane, on the left hand side is a JTable and on the right hand is a JTabbedPane. In the tabs of the JTabbedPane there are other JTables.
    In order to make the rows in the JTable on the left and the JTable(s) on the right line up, the Table Header of all the tables is set to the size of the tallest (deepest?) table header.
    Hopefully so far I'm making sense. Now to get to the issue. One of the tables has a number of columns equal to the value on a NumberSpinner (it represents a number of weeks). When this value is changed the table is modified so that it contains the correct number of columns. As the table is re-drawn the table header goes back to its default size so I call my header-resize method to ensure it lines up.
    The problem is this: if I change the number of weeks when selecting a tab other than the one containing my table then everything is fine, the table header is re-sized and everything lines up. If I change the number of weeks with the tab containing the table selected, the column headers stay at their standard size and nothing lines up.
    To make things more complicated, I also put System.out.println's in as every method called in the process to obtain the size of the table header. And every println returned the same height, the height the table header should be.. So I'm really confused.
    Could anyone shed any light on this?
    Thanks.

    Okay I managed to solve the problem by explicitly revalidating and repainting the table header.
    Not sure why it wasnt doing it properly for that table when all the others where fine.
    Oh well...

  • JTable allows sorting and filtering at same time

    Hi All:
    Any one has experience about having a JTable allows column sorting and row filtering at same time ?
    I've got JTable allows sorting, as well as a JTable allows filtering; but had a hard time to combine these functionality together. It seems I can't use separate TableModel since I need perform these two operations together on on JTable.
    any help is going to be greatly appreciated!

    Have a look at the QuoteTableModel at www.javapractices.com/Topic162.cjp
    (almost at the bottom of the page)

  • JTable X System_Look-And-Feel Interaction

    Friends,
    I'm developing an application that is centered around a JTable. The column header labels are centered and have a yellow background.
    When I use the Metal look-and-feel, no problem. However, if I switch to the system look-and-feel, the column labels will no longer be centered, and their yellow background does not show up.
    I've attached some code below that will duplicate this problem. Just un-remark one look-and-feel (line 16), and then the other (line 18), and see how this affects the JTable's header.
    I've searched a lot of documentation, tutorials, and forums and have not seen a reference to this problem. I hope that you can help.
    Thank you.
    Victor
    import java.awt.Color;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    public class testLNF {
    public static void main(String[] args) {
    // set look-and-feel to the local system:
    String systemLookAndFeel = UIManager.getSystemLookAndFeelClassName();
    System.out.println(systemLookAndFeel);
    try {
    // include this for Metal Look-And-Feel
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    // include this line for System Look-And-Feel
    //UIManager.setLookAndFeel(systemLookAndFeel);
    } catch (Exception e) {
    System.out.println("Exception: " + e);
    // Display the simple JTable
    tempFrame ff = new tempFrame();
    ff.setSize(300, 150);
    ff.setLocationRelativeTo(null);
    ff.setVisible(true);
    ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    } // main
    private static class tempFrame extends JFrame {
    private tempFrame() {
    // Create a simple JTable to work with
    JTable t = new JTable(4, 4);
    t.getTableHeader().setBackground(Color.YELLOW);
    t.getTableHeader().setForeground(Color.BLACK);
    t.getTableHeader().setOpaque(true);
    t.setShowGrid(true);
    t.setGridColor(Color.DARK_GRAY);
    // Add it to a JScrollPane
    JScrollPane s = new JScrollPane(t);
    add(s);
    } // class tempFrame
    } // class testLNF

    Thank you for your guidance on this issue. I've started work with cell renderers in this table -- I'm using one to center my numbers in each cell. I'll get back to work on learning the basics.
    Can you help me with what you mean by "delegate to the L&F renderer?" Can you give me an example?
    Thank you!

  • Search on a row in jTable...and load a file into jTable...

    hello i'm new to this community however...
    i'm trying to source in jtable row...let's say i have 3 columns...and 3 rows...the third row is filled with data like: "John", "Johnny", "94252" ... the two other rows are filled with other data...now i want to search for "John"...when the word is found the row get highlighted...any ideas ?? and another thing... i want to load a textfile into a jTable cells...the file is saved as a textfile which seperates each word with the character ; like ... Camel;Nanny;552353 ... any ideas about this one ?
    thnx
    //Andr�

    It didn't work of course...or did i missunderstand you ?1) You need to loop through all rows, since you don't know which row contains the string your are searching for.
    2) Never use "==" when comparing Objects. You use the equals method:
    if (....getValueAt(row, 0).equals( str ))

  • JTable Moving Columns and keeping the index for re-display

    I have a JTable with data. The data in the table is refreshed every two minutes. The user is allowed to move the columns around, but when the refresh happens, the columns go back to their original layout. I have a TableColumnModelListener attached to the table and I know that there is a columnMoved method and I can capture the the "toIndex" but where do I set this new index in the model?

    The TableColumnModel controls the ordering of the the Table columns.
    When you use the setModel(...) method the fireTableStructureDataChanged() event is fired. This causes the TableColumnModel to be recreated. However you can turn this off, assuming the structure of the TableModel is the same, and only the data has changed. After creating the table the first time you can use:
    table.setAutoCreateColumnsFromModel( false );

  • JTable column movement and scroll bar

    Hello:
    I have a JTable with about 30-40 columns. Sometimes I would like to drag the column from rightmost to closer to the left end. I am not able to do that in one shot. and instead have to do it in multiple steps. Is there a way for the scroll bar to sort of move alongside the column as I drag it along?

    i dont know if there is way off hand. But you can put your own mouseListener of the JScrollPane and i am sure there is some method to check if you are dragging the JTable and if you are move the JScrollBar in the direction.
    I think that you are going to have to make you own implementation of this.
    David

  • How to input id data in jtable column 1 and load the detail in other column

    Dear all,
    I am new to java, I am writing a POS using Java. I want to scan goods barcode into column 1 of a jtable, then the program will load the product's name and price in
    column 2 and column 3 from database. And also I want to have another row available where the barcode is scanned in previous row, i.e. I can add multiple products. And then I need to write the good's barcode to database. Please suggest any related article or code example. Thanks.

    Peter-Hon wrote:
    Dear all,
    I am new to java, I am writing a POS using Java. I want to scan goods barcode into column 1 of a jtable, then the program will load the product's name and price in
    column 2 and column 3 from database. And also I want to have another row available where the barcode is scanned in previous row, i.e. I can add multiple products. And then I need to write the good's barcode to database. Please suggest any related article or code example. Thanks.Your scanner will probably be a keyboard wedge, so any input from it will be equivalent to typing on the keyboard. You may be able to set it up to send a character, or sequence of characters that you can interpret as "move focus to the input cell, and input the remainder of the input there", if you can't do that, then you will have to just deal with the fact that people will end up scanning the bar codes into the quantity field.

  • A JTable, a datamodel and a refresh method walk into a pub...

    Hi. I have been reading the forums all morning to get help with this but can't seem to find something to suit so far.
    I've made a configurable db connector and a GUI for viewing its contents in a JTable after specifying ip address, port number etc.
    So far I've got a customised AbstractTableModel to set itself up on default db connection settings and the JTable opens up with that datamodel.
    Fine up to this. Its static, just shows up and sits there.
    =====================================
    What I need:
    The JTable should have a default setting of everything blank.
    After specifying the db connection you click launch connection button.
    I want to be able to connect to a database (no problem there) and get the JTable to populate from this current database.
    Then clicking the button again closes the db connection (again, no problem there) and I want the JTable to return to default blank.
    =====================================
    In a nutshell:
    'How can I use a TableModel that can change its contents and refresh/update a JTable from it?'
    Any Ideas?

    <code>
    public class DataTableModel extends AbstractTableModel
    private int maxCol = 0;
    private List header = new ArrayList();
    private List data = new ArrayList();
    public DataTableModel() {
    public int getRowCount() {
    if(data.size()==0)
    return 6;
    return data.size();
    public int getColumnCount() {
    if(maxCol == 0)
    return 6;
    return maxCol;
    public String getColumnName(int columnIndex) {
    if(columnIndex>=header.size())
    return "Colonne "+(columnIndex+1);
    return header.get(columnIndex).toString();
    public Class getColumnClass(int columnIndex) {
    try{
    return Class.forName("String");
    }catch(Exception e){}
    return null;
    public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
    public Object getValueAt(int rowIndex, int columnIndex) {
    if(rowIndex>=data.size())
    return null;
    List tmp = (List) data.get(rowIndex);
    if(columnIndex>=tmp.size())
    return null;
    return tmp.get(columnIndex);
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    /**@todo: Implement this javax.swing.table.TableModel method*/
    throw new java.lang.UnsupportedOperationException("Method setValueAt() not yet implemented.");
    public void addRow(List row){
    data.add(row);
    if(row.size() > maxCol)
    maxCol = row.size();
    public void setHeader(List header){
    this.header = header;
    if(header.size()>maxCol)
    maxCol = header.size();
    public void setColumName(String value,int index){
    if(header.size()==0){
    for(int i=0;i<index;i++)
    header.add("Colonne "+(i+1));
    header.add(value);
    double max = Math.max(maxCol,6);
    for(int i=header.size();i<max;i++)
    header.add("Colonne "+(i+1));
    return;
    header.remove(index);
    header.add(index,value);
    public void reinit(){
    header.clear();
    data.clear();
    </code>
    this the code of my table model...At the beginning the table has 6 colums and 6 rows.

Maybe you are looking for

  • Creation of domain using template

    Hi All, I have been trying to create a domain in weblogic 10.3 using the template . The domain gets created as well the server starts but when I try to deploy my application , I get following error <May 10, 2010 4:58:16 PM IST> <Warning> <HTTP> <BEA-

  • Is there a way to duplicate a User Account when setting up an iMac

    I have a lab of 30 iMac computers.  I am planning on imaging 29 of them from 1 master machine.  In the process of setting this one machine up, I need to create 4 user accounts that will have identical settings, but will simply have different names. 

  • Adobe Premiere Elements 8 Can't finish installing Air Runtime Process, and Can't open New Project!

    Hey guys,      I'm having some major issues installing PE8.  I can open the installer screen fine, and it installs fine until it gets to installing the Air Runtime Process.  I have left it downloading that one process for about 5 hours, and i'm not e

  • BEx Query Formating - Displaying both Sum and Average in the same report

    Hi everybody, I need to create a BW report in the below format,                       Company Code                                            Total       Total Average                                0001            0002      0003      0004 Doc Type  

  • Sync my Mac Mini to my iPhone 4

    Can I sync my Mac Mini to my iPhone 4, remotely using home sharing? Basically I want to be able to sync music, movies, and audio books to my iPhone without having to dig round the back of my computer for my apple cabble. I want to know if its possibl