JTable with ImageIcon

Hi all

I would like to create a JTable.

Each cell contains a table of 4 items:

[0] ImageIcon

[1] ImageIcon

[2] number

[3] Boolean


(1) once displayed JTable, each cell display only [0].

(2) later, based on the user clicking on the cell, cell must display [1]

No idea how can I use a table with 4 values in the table cell?

I am still fighting with 1)

Thank you
Aykut

I suggest using a TableModel supported by a list of Row objects.

Your line should have the additional properties to retain framebuffer is that the user has already clicked on this line.

in the getValueAt() of the TableModel method you can choose to index 1 issue null (or empty image) or the actual image.

Good bye

DPT

Tags: Java

Similar Questions

  • JTable with custom column model and model table does not display the table header

    Hello

    I create a JTable with a custom table model and a custom column template. However the table header is not displayed (Yes, it's in a get). I have narrowed the problem down in one compilable example:

    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    
    public class Test1 extends JFrame
    {
         public static void main(String args[])
         {
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
    
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
    
              frame.setSize(200,200);
              frame.setVisible(true);
         }
    
         private static DefaultTableColumnModel createTestColumnModel()
         {
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
    
              return columnModel;
         }
    
         static class TestTableModel extends AbstractTableModel
         {
              public int getColumnCount()
              {
                   return 1;
              }
    
              public Class<?> getColumnClass(int columnIndex)
              {
                   return String.class;
              }
    
              public String getColumnName(int column)
              {
                   return "col";
              }
    
              public int getRowCount()
              {
                   return 1;
              }
    
              public Object getValueAt(int row, int col)
              {
                   return "test";
              }
    
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
              {
              }
         }
    }
    Published by: 802416 on October 14, 2010 04:29
    added
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue (java.lang.Object)
    When the TableColumn is created, the default headerValue is null
    So the header ends up rendered empty label (probably of size 0 if the JTable calculates its size of header based on the size of the default rendering tool).

    It worked:

         private static DefaultTableColumnModel createTestColumnModel()
         {
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
                    TableColumn col = new TableColumn(0);
                    col.setHeaderValue("Header Title");
              columnModel.addColumn(col);
                    return columnModel;
         }
    

    Published by: jduprez on October 14, 2010 14:09
    Beaten by a fraction of a second!

    Published by: jduprez on October 14, 2010 14:10
    OK, by a split of 17 minutes, specifically: o)

  • Help! coloring a bottom line for 3 seconds in JTable with SwingTimer

    Hi, I'm fighting with this for the last three days, but can not find a solution.

    I have a JTable and when I insert a new line, I want to give this line a backgroundcolor for 3 seconds / or let it Flash for 3 seconds and then let it return to its original background color. While the current line is yellow, I want to insert a new line which would also yellow for 3 seconds. The previous row would return white earlier that line, because this line is inserted earlier.

    the problem is that when I add a new line, while the current line is yellow, the new line should the timer from the previous row, which means that the last inserted row will remain yellow for a time of shirter, which I don't want.
    I want a bgcolor 3 second for everyrow inserted. How can I achieve this?

    My code:

    startBlinking() is called when a new row is added to the JTable

    Public Sub startBlinking() throws InterruptedException {}

    If (timer.isRunning ()) {}
    }
    timer.setInitialDelay (2);
    Timer.Start ();
    }

    -in another class:

    attributes
    Action updateCursorAction = getAction().
    Timer Timer = new Timer (3000, updateCursorAction);


    public Action getAction() {}
    updateCursorAction = new AbstractAction() {}
    Boolean shouldDraw = false;

    public void actionPerformed (ActionEvent e) {}
    If (shouldDraw =! shouldDraw) {}
    blinkingYellow();
    } else {}
    blinkingWhite();
    Timer.Stop ();
    }
    }
    };
    Return updateCursorAction;
    }


    public void blinkingWhite() {}
    receiverdata_Table.setRowSelectionInterval (0, 0);
    receiverdata_Table.setSelectionBackground (Color.White);
    }

    public void blinkingYellow() {}

    receiverdata_Table.setRowSelectionInterval (0, 0);
    receiverdata_Table.setSelectionBackground (Color.Yellow);
    }

    RishiSU wrote:
    Hello

    Thanks for your reply.

    I decided to go with for my Gui SwingX.

    great :-)

    Unfortunately the site is down,

    sigh, what happens... not so occasionally, see

    http://www.Java.NET/forum/topic/javadesktop/Java-Desktop-technologies/SwingLabs/FYI-swingxdemos-project-homes-are-Javan-0

    contains all the info on How to get to the source, releases... the newest is 1.6.2

    My question is, how can I use the code that you just pasted in my IDE?
    I have already added the Jar files in my path. The only thing that keeps me from compliling and execution of the code is the:

    Import org.jdesktop.swingx.InteractiveTestCase;

    Yes, it is not part of the output of swingx, it's part of our test support (we are lazy :-). Your options are at the checkout the complete code (including support for test) of the House of project and compile it in your ide - or just give up and replace it with a configuration of the 'normal' UI as shown below, no rocket science :-)

    HTH
    Jeanette

    public class DynamicHighlighterExperiments { //extends InteractiveTestCase {
    
        // public static void main(String[] args) {
        // DynamicHighlighterExperiments test = new DynamicHighlighterExperiments();
        // try {
        // test.runInteractiveTests();
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        // }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JXFrame frame = new JXFrame("DynamicHighlighterExperiments");
                    frame.add(new DynamicHighlighterExperiments().createContent());
                    frame.pack();
                    frame.setLocation(WindowUtils.getPointForCentering(frame));
                    frame.setVisible(true);
                }
            });
        }
    
    //    public void interactiveHighlightOnInsert() {
          protected JComponent createContent() {
            final JXTable table = new JXTable(10, 4);
    
            final ColorHighlighter hl = new ColorHighlighter(HighlightPredicate.NEVER,
                    Color.YELLOW,  null);
            table.addHighlighter(hl);
    
            final List recentRows = new ArrayList();
            ActionListener l = new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    int insertedRow = table.getModel().getRowCount();
                    recentRows.add(insertedRow);
                    ((DefaultTableModel) table.getModel()).addRow(new Object[] {insertedRow});
                    table.scrollRowToVisible(table.convertRowIndexToView(insertedRow));
                    updateHighlighter(hl, recentRows, insertedRow);
                }
            };
            Timer insertTimer = new Timer(500, l);
            insertTimer.start();
    //        showWithScrollingInFrame(table, "highlight inserted rows");
            return new JScrollPane(table);
        }
    
  • problem with jtable + timer

    Hello I'm new to ce Java and I have a big problem and I need help et I try to update one JTable with a timer every 15 seconds, but When you upgrade is a random point le program crashes , je problado Autour and can not find How to do work, the filling method Treaty in the program which works well.
    Here is the code for allows you to see and error.
    Excuse my English because I'm not talking very well, thank you very much greetings


    Java

    Docking package;

    Import Clases.orden;

    import java.awt.Color;

    java.awt.Component import;

    import java.sql.SQLException;

    import java.util.Calendar;

    import java.util.Date;

    import java.util.Timer.

    java.util.TimerTask to import;

    import java.util.logging.Level;

    to import java.util.logging.Logger;

    to import javax.swing.JLabel;

    javax.swing.JTable import;

    javax.swing.SwingConstants import;

    Import javax.swing.table.DefaultTableModel;

    javax.swing.table.TableCellRenderer import;

    Import javax.swing.table.TableColumn;

    SerializableAttribute public class liquidación extends javax.swing.JFrame {}

    Main P = null;

    public String valorBuscado = "";

    Timer Timer = new Timer(); El timer that encarga administrar los repeticion tiempo

    public int seconds; el valor del contador handle

    Before date = new Date();

    After date = new Date();

    Orden o = new orden();

    Suite int = 0;

    public Liquidacion() {}

    initComponents();

    }

    {LIQUIDACIÓN (main aThis)}

    initComponents();

    P = aThis;

    try {}

    Start (15);

    } catch (Exception ex) {}

    Logger.getLogger (Liquidacion.class.getName ()) .log (Level.SEVERE, null, ex);

    }

    }

    class MiTarea extends TimerTask {}

    public void run() {}

    Orden o = new orden();

    before = new Date();

    Calendar calendar = Calendar.GetInstance (); get the date of hoy

    Calendar.Add (Calendar.DATE,-20);

    antes.setDate (calendar.get (Calendar.DATE));

    antes.setMonth (calendar.get (Calendar.MONTH));

    antes.setYear (calendar.get (Calendar.YEAR) - 1900);

    After = new Date();

    DefaultTableModel value;

    value = new DefaultTableModel() {}

    Class [] types = new class [] {}

    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class

    };

    canEdit Boolean [] = new boolean [] {}

    false, false, false, false, false, false, false, false

    };

    @Override

    Public Class getColumnClass (int columnIndex) {}

    return types [columnIndex];

    }

    @Override

    ' public boolean isCellEditable (int rowIndex, int columnIndex) {}

    return canEdit [columnIndex];

    }

    };

    Object columns [] = {"NAVE/VIAJE", "PUERTO", "SHIP", "ARMADOR', 'ARRIVAL DATE',"DATE ZARPE"," USER A COMPLETE ","DIAS FALTANTES"};

    for (Col of the object: columns) {}

    value.addColumn (Col);

    }

    tablaRegistros.setModel (value);

    try {}

    tablaRegistros.setModel (o.ListarTabla1 ("", before, after, value));

    } catch (SQLException ex) {}

    System.out.println ("error :"); tabla

    Logger.getLogger (Liquidacion.class.getName ()) .log (Level.SEVERE, null, ex);

    }

    } / / end of race)

    } / / end SincronizacionAutomatica

    public void Start (int pSeg) throws Exception {}

    the una tarea al timer asignamos

    Timer.Schedule (new MiTarea(), 0, pSeg * 1000);

    } / / end

    }

    ce is the error


    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 > = 0 = > or this Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 5 > = 5 ".

    at java.util.Vector.elementAt(Vector.java:470)

    at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:294)

    at javax.swing.plaf.basic.BasicTableHeaderUI.getHeaderHeight(BasicTableHeaderUI.java:733)

    at javax.swing.plaf.basic.BasicTableHeaderUI.createHeaderSize(BasicTableHeaderUI.java:765)

    at javax.swing.plaf.basic.BasicTableHeaderUI.getPreferredSize(BasicTableHeaderUI.java:796)

    at javax.swing.JComponent.getPreferredSize(JComponent.java:1660)

    at javax.swing.ViewportLayout.preferredLayoutSize(ViewportLayout.java:95)

    at java.awt.Container.preferredSize(Container.java:1788)

    at java.awt.Container.getPreferredSize(Container.java:1773)

    at javax.swing.JComponent.getPreferredSize(JComponent.java:1662)

    at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:723)

    at java.awt.Container.layout(Container.java:1503)

    at java.awt.Container.doLayout(Container.java:1492)

    at java.awt.Container.validateTree(Container.java:1688)

    at java.awt.Container.validate(Container.java:1623)

    to javax.swing.RepaintManager$ 2.run(RepaintManager.java:679)

    to javax.swing.RepaintManager$ 2.run(RepaintManager.java:677)

    at java.security.AccessController.doPrivileged (Native Method)

    in java.security.ProtectionDomain$ 1.doIntersectionPrivilege(ProtectionDomain.java:76)

    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:676)

    to javax.swing.RepaintManager$ ProcessingRunnable.run (RepaintManager.java:1650)

    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)

    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)

    at $200 (EventQueue.java:103) java.awt.EventQueue.access

    in java.awt.EventQueue$ 3.run(EventQueue.java:688)

    in java.awt.EventQueue$ 3.run(EventQueue.java:686)

    at java.security.AccessController.doPrivileged (Native Method)

    in java.security.ProtectionDomain$ 1.doIntersectionPrivilege(ProtectionDomain.java:76)

    at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)

    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)

    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)

    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)

    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)

    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)

    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

    Try using javax.swing.Timer instead of java.util.Timer. Alternatively, you can use SwingUtilities.invokeLater to define the model.

  • Automatic database update of JTable

    Greetings. I'm here because I want to do this and I don't know how to start.

    I do an application that needs a JTable with data from an existing database. I need the table to periodically (I intend to use a timer) reflect the changes to the DB (insert new lines, deletion, or update existing lines) without making the dirty of the JTable together approach clearing and filling it again, which is not pleasant. I must just add/change/remove the necessary lines, not all of the table.

    periflo90 wrote:

    I need optimization for two reasons: less impact on the user (I mean, the table, take the refresh time is very ugly) and computers that are using my application are quite old. On records, I expected at this table, I expect to be hundreds or thousands.

    That means you cannot show them both on screen anyway. Then you should think about pagination.

    You're right about the separate thread, it will be better. Because my application GUI is prepared with swing, can I use a SwingWorker or regular NET? I'm quite new to competitive access.

    Use of Threads is quite easy in Java. When you design an application Swing under you should have used wire already. If you idn can't you did all your work inside the event Dispatching Thread which will be bock your request effectively when you work any longer. And Yes, SwingWorker is an appropriate tool.

    On the last questions, no, the table has these identifiers.

    Your request is then impossible. How will you know the differences without either all data back to the database or to reload all the data to make the comparison on the client side.

    I think that the background loading is your best option.

    Good bye

    DPT

  • Order of JTable

    Hello

    I want to sort the rows in a table, but I'm a little arrested. I would like to move the empty cells to the bottom of the table at any time. This works if the direction of the order is ascending, otherwise the cells will be at the top of the table. Anyone can propose a solution to this problem?
    public class Table {
    
    private static JFrame frame;
    private static JScrollPane scrollPane;
    private static JTable table;
    private static String[] columns;
    private static String[][] rows;
    
    static {
        rows = new String[][]{{"apple"}, {"pear"}, {"banana"}, {"paradise"}, {""}, {""}};
        columns = new String[]{"Fruits"};
    }
    
    public static void main(String[] args) {
        frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(table(), BorderLayout.PAGE_START);
        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    private static JScrollPane table() {
        table = new JTable(rows, columns);
        TableRowSorter tableRowSorter = new TableRowSorter(table.getModel());
        tableRowSorter.setComparator(0, new Comparator<String>() {
    
        @Override
        public int compare(String s1, String s2) {
            if (s1.isEmpty() && s2.isEmpty()) {
                return 0;
            } else if (s1.isEmpty() && !s2.isEmpty()) {
                return 1;
            } else if (!s1.isEmpty() && s2.isEmpty()) {
                return -1;
            }
            return s1.compareTo(s2);
        }
        });
        table.setRowSorter(tableRowSorter);
        scrollPane = new JScrollPane(table);
        return scrollPane;
    }
    }

    Sort the JTable with a blank line

    DB

  • Set the color of a row in a JTable

    Hi all
    I need to set the color of a line (or simply a cell) in a JTable to a specific color,
    I read these pages:

    http://StackOverflow.com/questions/1057710/how-to-set-the-colour-of-my-1st-row-in-my-JTable-to-yellowor-any-colour
    http://www.roseindia.NET/Java/example/Java/Swing/SadingRows.shtml
    http://StackOverflow.com/questions/3875607/change-the-background-color-of-a-row-in-a-JTable
    http://www.codeguru.com/Forum/archive/index.php/t-34478.html
    http://www.thatsjava.com/Java-Swing/16549/

    and lots and lots of links like these... all of them are too complicated and HARD...
    What I need, it's too simple: pick a line and then set the color red for example...
    Can you help me please...

    I need the simplest code possible

    Thank you very much

    {/ / Here a Question: this is the beginning of the block what?} Method? class? where is the name?

    It's what we call a "class internal annonymous. Its extension JTable and similar to the override of the prepareRenderer() method if you do not need a separate source file.

    This method returns a component... while I was expecting, it does the job and returns nothing (void)...

    The code is substituting a JTable method defined in the API.

    It seems that these codes CREATE a JTable with a custom look, whereas what I need is to EDIT and CHANGE a JTable that is ALREADY CREATED

    Custom made is a design time decision. That is, you need to create and implement an API at design which allows to dynamically change the rendering at runtime. The default API does not support line-level rendering which is why you need to create your own API to do this.

    I need to set the color of a line (or simply a cell) in a JTable to a specific color,

    Converters of work by making the data contained in a table cell. If you want a rendering engine, a cell or a row of a table a different color, so you need to store this information somewhere so that the rendering engine knows what to do.

    If you feared strictly for color lines, then approach you could do is create acard. When you want a row to be a specific color, then you add and entry to the map. The best way to use this information would override the method prepareRenderer() to check the card each time to see if a custom color is for the line to be renderered.

    Here is a simple example of a simple API added to the JTable which lets you row rendered level:

    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    
    public class RowTable extends JTable
    {
         Map rowColor = new HashMap();
    
         public RowTable(TableModel model)
         {
              super(model);
         }
    
         @Override
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
         {
              Component c = super.prepareRenderer(renderer, row, column);
    
              if (!isRowSelected(row))
              {
                   Color color = rowColor.get( row );
                   c.setBackground(color == null ? getBackground() : color);
              }
    
              return c;
         }
    
         public void setRowColor(int row, Color color)
         {
              rowColor.put(row, color);
         }
    
         public static void main(String[] args)
         {
              DefaultTableModel model = new DefaultTableModel(10, 4);
              RowTable table = new RowTable( model );
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
    
              table.setRowColor(1, Color.YELLOW);
              table.setRowColor(4, Color.RED);
              table.setRowColor(7, Color.ORANGE);
    
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.add( new JScrollPane( table ) );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
         }
    }
    
  • Request for assistance on tweeking a JList JCheckBox

    Hi, I have a problem with a JCheckBox JList I found on the web. I normally do not ask for help since I've found that no matter what question seems to me usually gets solved by some intense research on Google. but here's my dilemma:

    I was looking for a JList JCheckBox I implement in my script, I found one on the web that someone had produced. It works fine I just need something tweeked thereon.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    
    public class CheckBoxInList
    {
       public static void main(String args[])
       {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JList list = new JList(new CheckListItem[] {new CheckListItem("1"), new CheckListItem("2"), new CheckListItem("3"), new CheckListItem("4"), new CheckListItem("5")});
    
            list.setCellRenderer(new CheckListRenderer());
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.addMouseListener(new MouseAdapter()
            {
                public void mouseClicked(MouseEvent event)
                {
                    JList list = (JList) event.getSource();
                    int index = list.locationToIndex(event.getPoint());
                    CheckListItem item = (CheckListItem)
                    list.getModel().getElementAt(index);
                    item.setSelected(! item.isSelected());
                    list.repaint(list.getCellBounds(index, index));
                }
            });
    
            frame.getContentPane().add(new JScrollPane(list));
            frame.pack();
            frame.setVisible(true);
            }
        }
    
        class CheckListItem
        {
            private String  label;
            private boolean isSelected = false;
    
            public CheckListItem(String label)
            {
                this.label = label;
            }
    
            public boolean isSelected()
            {
                return isSelected;
            }
    
            public void setSelected(boolean isSelected)
            {
                this.isSelected = isSelected;
            }
    
            public String toString()
            {
                return label;
            }
        }
    
        class CheckListRenderer extends JCheckBox  implements ListCellRenderer
        {
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean hasFocus)
            {
                setEnabled(list.isEnabled());
                *setSelected(((CheckListItem)value).isSelected()); // This is part of the problem, when I currently try to select a CheckBox there is a nullpointer example with my method*
                setFont(list.getFont());
                setBackground(list.getBackground());
                setForeground(list.getForeground());
                *setText(value.toString()); // This is also part of the problem, when I currently try to select a CheckBox there is a nullpointer example with my method *
                return this;
            }
        }
    This is the code, now what I'm trying to do right now is rather than add JCheckBoxes as well:
    new CheckListItem("1")
    I was hoping to do something like this:
    int arrayAmount = 20;
    String textArray[] = {"Text", "More Text", "Even More Text", "Etc."};
    JCheckBox jcheckboxArray[] = new JCheckBox[arrayAmount];
    JList list = new JList(jcheckboxArray);
    And set values later by doing this (it will be called from another class that reads its information in a file, they will be already initialized by this point):
    for (int i = 0; i < arrayAmount; i ++)
            {
                jcheckboxArray[i] = new JCheckBox(textArray);
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    If you need a list of items that reflect a selected State independent of the selection of lines, use a 2 columns JTable with a Boolean and a string column and grid based on your need.

    DB

  • The addition of several windows in a print job. How?

    Heya!

    I'm having difficult (i.e. hitting my head against the wall) time to find a way to achieve the following:

    I have a JTable with search results. Search results represent a sort of... maps registry. When you double-click on a single line in the table, you get a new image with filled JTextfields. What I have to do is to be able to print this "UI map" framework for each resultline without showing them as a single frame. Search result can be up to like 100 or something, if its not like one or two.

    So to sum this up:
    -Print several JFrames with content without showing them. Prefferably by adding them to a single print job, comes with several pages (where an image is printed page).

    How can I achieve this? Is this possible?

    Certainly, they do: see the Images [url http://jasperforge.org/uploads/publish/jasperreportswebsite/trunk/samples.html] section in samples of Jasper.

  • Java Swing problem

    Hey everybody,

    I'm designing a Java application with GUI, using NetBeans for this purpose.
    I want to, when I click on a button to create a new JTable (account JScrollField) in the control panel I. However, I click the button and the JTable is not displayed.

    Can we, based on this place in the code where the error can be?
    During execution with no exceptions are thrown. No error code is indicated. The application has everything simply nothing when I click on the button.

    Thank you for your help.

    Note: right panel is a component created visually
    private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            
            Vector data = new Vector(10,10);
            data.addElement(new Alarm("Outgassing",-10,10));
    
            SimpleTableModel stm = new SimpleTableModel(data);
            JTable table = new JTable(stm);
    
            JScrollPane xmlTableScrollField = new JScrollPane(table);
            xmlTableScrollField.setVisible(true);
            rightPanel.setVisible(true);
            rightPanel.add(xmlTableScrollField);
    
            //readXMLToList(filename);
    }
    Class SimpleTableModel:
    package main;
    
    import alarms.Alarm;
    import java.util.Vector;
    import javax.swing.table.AbstractTableModel;
    
    class SimpleTableModel extends AbstractTableModel{
        public String[] colNames = {"Alarm name", "MinValue", "MaxValue"};
        public Vector rows;
    
        public SimpleTableModel(Vector data)
        {
            super();
            this.rows = data;
        }
    
        public int getRowCount() {
            return rows.size();
        }
    
        public int getColumnCount() {
            return colNames.length;
        }
    
        public String getColumnName(int col)
        {
            return colNames[col];
        }
    
        public Object getValueAt(int row, int col) {
            Alarm alarm = (Alarm) rows.elementAt(row);
    
            switch(col)
            {
                case 0:
                    return alarm.getName();
                case 1:
                    return alarm.getMin();
                case 2:
                    return alarm.getMax();
            }
    
            return "";
        }
    
        public void setValueAt(Object value, int row, int col)
        {
            Alarm alarm = (Alarm) rows.elementAt(row);
    
            switch(col)
            {
                case 0:
                    alarm.setName((String)value);
                    break;
                case 1:
                    alarm.setMin((Double)value);
                    break;
                case 2:
                    alarm.setMax((Double)value);
                    break;
            }
        }
    }
    Alarm class:

    package alarms;
    
    public class Alarm {
        String name;
        Double min;
        Double max;
    
        public Alarm(String argName, double argMin, double argMax)
        {
            this.name = argName;
            this.min = argMin;
            this.max = argMax;
        }
    
        public String getName()
        {
            return name;
        }
    
        public void setName(String value)
        {
            this.name = value;
        }
    
        public double getMin()
        {
            return min;
        }
    
        public void setMin(double value)
        {
            this.min = value;
        }
    
        public double getMax()
        {
            return max;
        }
    
        public void setMax(double value)
        {
            this.max = value;
        }
    }
    Published by: user11898723 on November 8, 2010 08:23

    The normal way to refresh the data in a JTable is not to create a new and try to replace the old on the screen by the new. The normal way is to create a JTable only once and to add it to the screen at all times. Then when you want to refresh its data, you create a new model of table and call the JTable with her setModel method. (Or is it setTableModel? You could look for.)

  • Inconsistent behavior of focusLost with JTable and JTree

    Swing has known problems for a long time with the cells and the loss of the thematic demonstrations in the JTables. Generally, users expect loss of focus to commit their changes rather than cancel the change. Then edit controls (for example, JTextFields) located in CellEditors should generally be listeners of update and manage focusLost() by calling cellEditor.stopCellEditing (). It is very clear.

    JTables to have an additional, special problem associated with a generation (or not) of focus events when moving from one cell to another cell in the same table. To do this, the code that creates the JTable needs to call table.putClientProperty ("terminateEditOnFocusLost", Boolean.TRUE). Setting this property to 'magic' on the table allows expected behaviors Assembly when moving from cell to cell.

    These issues are well described here: http://tips4java.wordpress.com/2008/12/12/table-stop-editing/

    I've set up the property of the client and the listener to focus, and they perform as expected in most cases. But I seems to have discovered a third case that is not managed by one of these two known workarounds.

    We have a design of the user interface master/detail where the master is a tree control and retail is the JTable of editable cells. The (master) JTree and JTable (detail) are each cashed in the JPanels which are in turn greeted in an enclosing JPanel.

    If I am editing within a cell and click completely outside this hierarchy - for example, in the menus of the main application bar - the focusLost() is managed and the change is committed, as you wish. And if I click anywhere in the JTable, also commits the change.

    But if I'm editing a cell and choose the JTree specifically, the change is aborted.

    I added logging for focusLost() Manager. I found that in the majority of cases, for example when clicking on menus or other completely different control bar, table.isEditing () returns TRUE for the JTable both focusLost() Manager is running. Because the change is running, the Manager is capable of broadcasting of stopCellEditing() and validate the user change.

    But when I click on the outside for the JTree specifically, then in focusLost() Manager I find isEditing() is WRONG - that is, the change has already been cancelled and there is no way to recover already cancelled user input. The text field focusLost Manager pointed out that 'the opposite element' (wins the focus) is a JTree control as expected.

    So it seems that something either the JTree or the locking hierarchy Panel made a subtle change to the behavior of the focusLost(). And therefore bypasses of modification of standard tables do not fully work in our application. And unfortunately, clicking on cells change directly in the tree turns out to be a common case in our design of the user interface. Failing to validate the edition in this case with bad consequences that should be fixed.

    Any suggestion would be appreciated. Note: the question is similar to related to this issue:

    JTree does not call focusLost on headphone

    but the tail wire. I concede that I'm not provide code either and he can't promise right now.
    - - -
    Jeff

    Rainmaker says:
    Right now seems to be a lot to a precise definition of the terms so I ask this question with regard to the docs.

    good start :-)

    >

    You wrote:

    invokesStopCellEditing and terminateEditOnFocusLost set up different behaviors, without overlap.

    Yes, I did, it meant and still means he

    >

    The setInvokesStopCellEditing() docs say:

    + Determines what happens when the edition is interrupted by selecting another node in the tree, a change of data of the tree, or by other means. Setting this property a value of true causes changes to be automatically saved when editing is stopped. +

    Well, your fat is your old problem: assumptions yet ;-) My focus is

    + Determines what happens when the change is interrupted by selecting another node in the tree, a change of data of the tree, or by some other means.

    And which is supported by reading on:

    
         * @param newValue true means that stopCellEditing is invoked
         *        when editing is interrupted, and data is saved; false means that
         *        cancelCellEditing is invoked, and changes are lost
    

    in the total sense: he's interrupted (whatever that means, no conclusive specification except this model or the selection change), this propterty determines whether editing is stopped or cancelled. Conversely: if it is not interrupted, the property has no effect.

    Do you mean that the part of the sentence by other means does not include loses focus? I have to disagree. Of course loses focus is a "way" to interrupt the editing.

    Nothing to accept or not: is done, it's the 'interrupt' that matters. Obviously (although without doubt) lose focus don't consider an interruption - nothing happens when moving the cursor somewhere else, neither commit nor cancel.

    So if invokesStopCellEditing is defined, and the tree loses focus, it should save your work. And that's why the invokesStopCellEditing overlap with terminateEditOnFocusLost.

    just to drive home ;-) - the item no.

    >

    Note that I stick to the definition in the docs.

    No, you interpret the doc to fit your expectations.

    I did an example code and checked the validation works when the tree loses focus.

    You should have (it's a two-liner to add to your example) - see the divergence of expectations and reality, rethink your accession ;-)

    In which case it's bugged, because the docs say it should.

    In fact, I don't think it is (as you may have guessed so read up to here ) the text doc of course is not as easy as it could be, as is unfortunately a habit running in the swing. Assuming that means it that you wait that means is a trap. My general advice is to read the documentation of the api carefully and until its end and then check against the actual behavior expectations. The advice to take it or leave it - your choice, of course.

    CU
    Jeanette

  • Problem with the rendering of JProgressBar in JTable

    I have some problems with the rendering of JProgressBar in JTable. In the case of several lines, when a progress bar is updated, and its text is changing, then he painted all the progress bars in this column.

    Here is my code I used to create the table:
    --------------------------------------------------------------------------------------
    JTable convertTable = new JTable(convertTableModel) {
    
                public Component prepareRenderer(TableCellRenderer renderer,
                        int rowIndex, int vColIndex) {
                    Component c = null;
                    if (renderer != null) {
                        c = super.prepareRenderer(renderer, rowIndex, vColIndex);
    
                        if (vColIndex == INDEX_CONVERT_STATUS) {
                            //System.out.println("c = "+c.getClass());
                            if(c instanceof JProgressBar) {
                                //System.out.println("inside = ");
                                c.setBackground(Color.BLUE);
                            }
                        }
                    }
                    return c;
                }
    
                public boolean isCellEditable(int rowIndex, int mColIndex) {
                    if (mColIndex == INDEX_CONVERT_SELECT) {
                        return true;
                    } else if (mColIndex == INDEX_CONVERT_STATUS) {
                        return false;
                    } else {
                        return false;
                    }
                }
    
                /*
                 * JTable uses this method to determine the default renderer/
                 * editor for each cell.  If we didn't implement this method,
                 * then the last column would contain text ("true"/"false"),
                 * rather than a check box.
                 */
                public Class getColumnClass(int c) {
                    if (getValueAt(0, c) != null) {
                        return getValueAt(0, c).getClass();
                    }
                    return null;
                }
            };
    --------------------------------------------------------------------------------------

    Then I applied on this table rendering engine

    ---------------------------------------------------------------------------------------
    // Applying JProgressBar Renderer for convert table
            TableColumn col = convertTable.getColumnModel().getColumn(INDEX_CONVERT_STATUS);
            ProgressBarRenderer progressBarRenderer = new ProgressBarRenderer();
            col.setCellRenderer(progressBarRenderer);
    ---------------------------------------------------------------------------------------

    Class code ProgressBarRenderer is as follows:
    ---------------------------------------------------------------------------------------
    public class ProgressBarRenderer extends JProgressBar implements TableCellRenderer {
    
        private Hashtable ht = new Hashtable();
    
        public ProgressBarRenderer() {
            super(0);
            this.setMinimum(0);
            this.setMaximum(100);
            this.setStringPainted(true);
            this.setBorderPainted(true);
    
            UIDefaults defaults = UIManager.getDefaults();
            Font font = new Font("Arial", Font.BOLD, 12);
            defaults.put("ProgressBar.font", font);
        }
    
        public void setRowEnabled(int row, boolean enabled) {
            ht.put(row, enabled);
        }
    
        public void setForeground(Color c, int row) {
            //System.out.println("setString ht = " + ht.size() + "  row= " + row + "  Selected= " + (Boolean) ht.get(row) + " color= " + c);
            if (ht.isEmpty()) {
                this.setForeground(c);
            } else if (ht.size() == 1) {
                this.setForeground(c);
            } else if ((Boolean) ht.get(row)) {
                this.setForeground(c);            
            } else {
                this.setForeground(c);
            }
        }
    
        public void setString(String s, int row) {
    
            //System.out.println("setString ht = " + ht.size() + "  row= " + row + " text= " + s);
            if (ht.isEmpty()) {
                this.setString(s);
            } else if (ht.size() == 1) {
                this.setString(s);
            } else if ((Boolean) ht.get(row)) {
                this.setString(s);
            } else {
                this.setString(s);
            }
    
        }
    
        @Override
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            
            //System.out.println("getTableCellRendererComponent = " + table);
            //System.out.println("Renderer ht = " + ht.size() + "  row= " + row + "  Selected= " + (Boolean) ht.get(row));
            
            if (ht.isEmpty()) {
                return this;
            } else if (ht.size() == 1) {
                return this;
            } else if ((Boolean) ht.get(row)) {
                return this;
            } else {
                return null;
            }
        }
    }
    ---------------------------------------------------------------------------------------

    I add the next line and rendered the progress column is follows:
       convertTableModel.addRow(new Vector());
       ((ProgressBarRenderer) convertTable.getCellRenderer(row, INDEX_CONVERT_STATUS)).setRowEnabled(row, false);
    ---------------------------------------------------------------------------------------

    When I add the first row, it works fine, but when I add the second row, he painted the entire column.

    Naturally, you will have problems if you set a string or a color of a table cell value when the class of the column is declared as integer. As I have already said, you need to spend some time with the tutorials.

    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    
    public class ProgressBarTableCellRendererExample {
    
      Random random = new Random();
      JTable table;
    
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
    
          public void run() {
            new ProgressBarTableCellRendererExample().makeUI();
          }
        });
      }
    
      public void makeUI() {
        table = new JTable(10, 1) {
    
          @Override
          public boolean isCellEditable(int row, int column) {
            return false;
          }
        };
        for (int i = 0; i < table.getRowCount(); i++) {
          table.setValueAt(0, i, 0);
        }
        table.getColumnModel().getColumn(0).
                setCellRenderer(new ProgressBarTableCellRenderer());
    
        JButton button = new JButton("Increment");
        button.addActionListener(new ActionListener() {
    
          public void actionPerformed(ActionEvent e) {
            increment();
          }
        });
    
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(table), BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      private void increment() {
        for (int i = 0; i < table.getRowCount(); i++) {
          Object value = table.getValueAt(i, 0);
          if (value instanceof Integer) {
            Integer oldValue = (Integer) table.getValueAt(i, 0);
            int newValue = Math.min(100, oldValue + random.nextInt(25));
            switch (newValue) {
              case 13: // and its multiples
              case 26:
              case 39:
              case 52:
              case 65:
              case 78:
              case 91:
                table.setValueAt("Failed", i, 0);
                break;
              case 100:
                table.setValueAt("Completed", i, 0);
                break;
              default:
                table.setValueAt(newValue, i, 0);
            }
          }
        }
      }
    
      private class ProgressBarTableCellRenderer
              extends JProgressBar implements TableCellRenderer {
    
        private TableCellRenderer stringRenderer =
                new DefaultTableCellRenderer();
    
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus,
                int row, int column) {
          if (value instanceof Integer) {
            setValue((Integer) value);
            return this;
          } else {
            return stringRenderer.getTableCellRendererComponent(table,
                    value, isSelected, hasFocus, row, column);
          }
        }
        // Override void validate(), invalidate(), revalidate(), repaint()
        // and all overloads of firePropertyChange(...) as no-ops
        // for efficiency
      }
    }
    

    DB

  • JTable - partial text selection

    Hey all,.

    I have a table read-only.

    Currently, when a user clicks on a cell, the entire cell is selected.

    I want to allow the user to choose only a partial text in the cell - mostly copy purposes.

    How can I achieve that?

    The trick (with Swing) is the JTable needs to be enabled, and you must register a custom Tableeditor which prevents changing the string:

    public class SelectableTextTableTest {
        public static void main(String[] args) {
            DefaultTableModel notEditableModel = new DefaultTableModel(11, 5) {
                @Override
                public Object getValueAt(int row, int column) {
                    return "Column " + column + " / Row " + row;
                }
    
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
    
            JTable table = new JTable(notEditableModel) {
    
                @Override
                public boolean isCellEditable(int row, int column) {
                    return true;
                }
            };
    
            JTextField textField = new JTextField();
            textField.setEditable(false);
            table.setDefaultEditor(Object.class, new DefaultCellEditor(textField));
            JOptionPane.showMessageDialog(null, table);
        }
    }
    

    Good bye

    DPT

  • Box dosnt get shown in jtable...

    I accept the values of the server through sockets in the message form.
    The message is divided and shown in the jtable like this:

    String [] parts = message.split("\t");
    data = new Object [parts.length / 2] [3];
    for (i = 0, r = 0; r < data.length; r ++)
    {
    [r] data [0] = parts [i ++];
    data [r] [1] = new Float(parts[i++]);
    [r] data [2] = new Boolean (true); See the checkbox doesn't but shows like 'true '.
    }

    Object [col] is {"Sensor", "Values", "checkbox"};.

    I have problem with not displaying check boxes do not (see comments)

    You must override the getColumnClass() method in your subclass AbstractTableModel extended chart as a template below:

    Suppose I'm store my data in the table in a two-dimesional array dataArray [] [] then

    public class getColumnClass(int columnIndex)
    {
       return dataArray[0][columnIndex].getClass();
    }
    

    By substituting the above method, you say to tabe DefaultTableCellRenderer, which make each cell in the table according to its data type of the columns. If your type of cell data type Boolean CheckBox is displayed.

  • random data in JTable model

    Hi all:
    I'm testing a JTable example, I create a test as data model below:
    class MyDataModel extends AbstractTableModel{
              private String columns[] = {"col1","col2","col3","col4","col5","col6","col7","col8","col9"};
              @Override
              public int getRowCount(){return 10;}
              @Override
              public int getColumnCount(){return columns.length;}
              @Override
              public Object getValueAt(int row, int col){
                   Integer i = (new Random()).nextInt(100);
                   return i;
              }
              @Override
              public String getColumnName(int col){ return columns[col];}
    
         }                    
    You can see that I filled the cell with varying random number between 0 and 100.

    The table has been created and the number displayed as expected. However, when I click on one of the cells, its data is changed, as well as in other cells, that too. It seems that the data model is reloaded again, and random numbers change dynamically.
    SetValue is called a bit? That really intrigued me.

    Thank you
    Johnny

    You do not fill the model with random values, on the other hand back you a new random value whenever getValueAt() is called. This is called whenever the table will redraw (for example because the editing stops - note that you don't actually saved the value changed, see the AbstractTableModel setValueAt implementation which is empty).

Maybe you are looking for