JLabel in JTable

Hi gurus,
I am new to GUI programming.
I have a JTable with 3 columns and multiple rows.
Is it possible to place the JLable component as an element in
a cell of JTable.
Please clarify me...

Thanks for the reply
I have a table with three columns and number of rows, the first column is the key value. With every key values there is additional data that need to be shown to user.
First I want to show the strings in the first column (key column) as hyperlink, clinking on which should display additional info in a tool tip.
If I can place a HyperlinkLabel that extends JLabel component in cells of JTable first column, I can diplay the additional info regarding that key in a dialog or in a tooltip.
Is this possible....

Similar Messages

  • JLabels into JTable cell

    Hi friends!
    I need to have a JTable with multiple JLabels inside its cells. I wrote a class wich implements TableCellRenderer the code is the following:
    public class JLabelCellRender extends JPanel implements  TableCellRenderer {
        Vector ObJLabelsV=new Vector();
        JLabel teste;
        public JLabelCellRender() {
            super();
        public java.awt.Component getTableCellRendererComponent(JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row, int column) {
            Vector labels=(Vector)value;
           for(int i=0;i<labels.size();i++) {
            add((JLabel)labels.elementAt(i));
            return this;
    }I nedd each cell having a variable number of JLabels, to do this I use a Vector.
    But I need to insert and remove JLabels in the main class. Like using the method setValueAt(ob,row,col) wich modifys the text in the cell I want to modify the text and the number of JLabels.
    The problem is I don't know how to insert and remove JLabels in the cells.
    I ask if I have to re-implement the setValueAt and getValueAt methods..
    Thanks in advance for help.
    Sory for my english.:)

    You need to do something similar to this
    public class JLabelCellRender extends JPanel implements  TableCellRenderer {
        Vector ObJLabelsV=new Vector();
        JLabel teste;
        public JLabelCellRender() {
            super();
        public java.awt.Component getTableCellRendererComponent(JTable table,  Object value, boolean isSelected,
                boolean hasFocus,  int row, int column) {
           // clear all exiting items in the panel
           removeAll();
           // obtain the new information for the
            Vector labels=(Vector)value;
           for(int i=0; i < labels.size(); i++) {
            add((JLabel)labels.elementAt(i));
           // adjust the row height of the current row to display all the labels
           table.setRowHeight(row, getPreferredSize().height);
            return this;
    }Now you just need to ensure that number of labels are different for the different cells you need to display.
    ICE

  • JTable not displaying column Heads

    The following JPanel was constructed using JBuilder 7 (a horrendous piece of software) and is in GridBagLayout. I'm attempting to display the contents of a table using JTable, and whilst it displays the rows it doesn't display the columnHeads! What am I doing wrong?
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    public class BeginTask extends JPanel implements ActionListener{
    private boolean dbupdated;
    private MainFrame main;
    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private JTable jTable1 = new JTable();
    private JButton jButton1 = new JButton();
    private JButton jButton2 = new JButton();
    private GridBagLayout gridBagLayout1 = new GridBagLayout();
    private Connection connection;
    private String url = "jdbc:odbc:bapers";
    private String username = "";
    private String password = "";
    public BeginTask(MainFrame ma) throws SQLException{
    main = ma;
    logon();
    drawTable();
    try {
    jbInit();
    catch(Exception ex) {
    ex.printStackTrace();
    void jbInit() throws Exception {
    jLabel1.setFont(new java.awt.Font("Dialog", 1, 18));
    jLabel1.setText("Begin Task");
    this.setLayout(gridBagLayout1);
    jLabel2.setText("Select Task, and press OK.");
    jButton1.setText("OK");
    jButton2.setText("CANCEL");
    jButton1.addActionListener(this);
    jButton2.addActionListener(this);
    this.add(jButton1, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(12, 117, 14, 0), 94, 8));
    this.add(jButton2, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(19, 43, 7, 119), 62, 8));
    this.add(jTable1, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(12, 25, 0, 22), 522, 281));
    this.add(jLabel2, new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0
    ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 181, 0, 226), 13, 6));
    this.add(jLabel1, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0
    ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(29, 202, 0, 251), 19, 17));
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jButton1) {
    if (dbupdated == true)
    JOptionPane.showMessageDialog(null, "The database has been updated to show that the user has begun the task selected.");
    else if (dbupdated == false)
    JOptionPane.showMessageDialog(null, "The database has not been updated.");
    else if (e.getSource() == jButton2) {
    BapProcMain bpm = new BapProcMain(main);
    main.redisplay(bpm);
    public void logon() {
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    connection = DriverManager.getConnection(url, username, password);
    catch (ClassNotFoundException cnfex) {
    System.err.println("Failed to load the JDBC/ODBC driver.");
    cnfex.printStackTrace();
    System.exit(1);
    catch (SQLException sqlex) {
    System.err.println("Unable to connect (SQL error)");
    sqlex.printStackTrace();
    public void logoff() {
    if (connection == null) return;
    try { connection.close(); }
    catch (SQLException sqlex) {
    System.err.println("Unable to disconnect (SQL error)");
    public void drawTable() {
    Statement stmt;
    ResultSet rset;
    try {
    String query = "SELECT * FROM SpecificTask";
    stmt = connection.createStatement();
    rset = stmt.executeQuery(query);
    displayResultSet(rset);
    stmt.close();
    catch (SQLException sqlex) {
    sqlex.printStackTrace();
    private void displayResultSet(ResultSet rs) throws SQLException {
    // position to first record
    boolean moreRecords = rs.next();
    // if there are no records, display a message
    if (! moreRecords){
    JOptionPane.showMessageDialog (this, "No Specific Tasks to begin.");
    return;
    Vector columnHeads = new Vector();
    Vector rows = new Vector();
    try {
    // get column heads
    ResultSetMetaData rsmd = rs.getMetaData();
    for (int i = 1; i <= rsmd.getColumnCount(); ++i)
    columnHeads.addElement (rsmd.getColumnName(i));
    //get row data
    // System.out.println("Got this far. Check getNextRow(...)");
    do { rows.addElement(getNextRow(rs, rsmd)); }
    while (rs.next());
    // display table with ResultSet contents
    jTable1 = new JTable (rows, columnHeads);
    JScrollPane scroller = new JScrollPane(jTable1);
    // validate();
    catch (SQLException sqlex) {
    sqlex.printStackTrace();
    private Vector getNextRow (ResultSet rs, ResultSetMetaData rsmd) throws SQLException {
    Vector currentRow = new Vector();
    for (int i = 1; i <= rsmd.getColumnCount(); ++ i)
    switch (rsmd.getColumnType(i)) {
    case Types.VARCHAR:
    currentRow.addElement(rs.getString(i));
    break;
    case Types.INTEGER:
    currentRow.addElement(new Long (rs.getLong(i) ) );
    break;
    default: System.out.println ("Type was: " +
    rsmd.getColumnTypeName(i));
    return currentRow;
    }

    The table header is shown automatically when you add the table to a scrollpane and then display the scrollpane in a panel. You use the following code to build the table/scrollpane:
    // display table with ResultSet contents
    jTable1 = new JTable (rows, columnHeads);
    JScrollPane scroller = new JScrollPane(jTable1);
    but, you add the table to your panel NOT the scrollpane:
    this.add(jTable1, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(12, 25, 0, 22), 522, 281));
    You should be adding the scrollpane to you panel.

  • JTABLE INPUT AND OUTPUT...ALMOST WORKING! PLZ HELP!

    Here's my program. Please try it out for yourself first, PLEASE. And do the following when you run it:
    1) Click the modify entries button (the table displays perfectly).
    3) Click the back button.
    4) Click the modify entries button AGAIN.
    5) WHY WON'T THE TABLE SHOW UP?
    PLEASE HELP MY CPT IS DUE TOMORROW!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.util.*;
    import java.io.*;
    public class CPT extends JPanel implements ActionListener
        JButton ModifyEntriesButton, ViewEntriesButton, SearchEntriesButton, SaveButton, BackButton, AddRowButton;
        JLabel SplashLabel;
        JTable contentTable;
        String aLine;
        Vector columnNames = new Vector ();
        Vector data = new Vector ();
        DefaultTableModel model = new DefaultTableModel (data, columnNames);
        public void createTable ()
            try
                FileInputStream fileInput = new FileInputStream ("entries.data");
                BufferedReader DBInput = new BufferedReader (new InputStreamReader (fileInput));
                StringTokenizer st1 = new StringTokenizer (DBInput.readLine (), "|");
                while (st1.hasMoreTokens ())
                    columnNames.addElement (st1.nextToken ());
                while ((aLine = DBInput.readLine ()) != null)
                    StringTokenizer st2 = new StringTokenizer (aLine, "|");
                    Vector row = new Vector ();
                    while (st2.hasMoreTokens ())
                        row.addElement (st2.nextToken ());
                    data.addElement (row);
                DBInput.close ();
            catch (Exception e)
                e.printStackTrace ();
        public CPT ()
            setLayout (null);
            ImageIcon splashimage = createImageIcon ("logo.JPG", "Swisha Computer House");
            SplashLabel = new JLabel ("Image and Text", splashimage, JLabel.CENTER);
            ModifyEntriesButton = new JButton ("Modify Entries");
            ModifyEntriesButton.setVerticalTextPosition (AbstractButton.TOP);
            ModifyEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ModifyEntriesButton.setToolTipText ("Click this button to modify database entries.");
            ModifyEntriesButton.setMnemonic (KeyEvent.VK_M);
            ModifyEntriesButton.setActionCommand ("ModifyEntries");
            ModifyEntriesButton.addActionListener (this);
            ViewEntriesButton = new JButton ("View Entries");
            ViewEntriesButton.setVerticalTextPosition (AbstractButton.CENTER);
            ViewEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ViewEntriesButton.setToolTipText ("Click this button to add view all database entries.");
            ViewEntriesButton.setMnemonic (KeyEvent.VK_V);
            ViewEntriesButton.setActionCommand ("ViewEntries");
            ViewEntriesButton.addActionListener (this);
            SearchEntriesButton = new JButton ("Search Entries");
            SearchEntriesButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            SearchEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            SearchEntriesButton.setToolTipText ("Click this button to search through all database entries.");
            SearchEntriesButton.setMnemonic (KeyEvent.VK_S);
            SearchEntriesButton.setActionCommand ("SearchEntries");
            SearchEntriesButton.addActionListener (this);
            SaveButton = new JButton ("Save");
            SaveButton.setVerticalTextPosition (AbstractButton.TOP);
            SaveButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            SaveButton.setToolTipText ("Click this button to save database entries.");
            SaveButton.setMnemonic (KeyEvent.VK_S);
            SaveButton.setActionCommand ("Save");
            SaveButton.addActionListener (this);
            BackButton = new JButton ("Back");
            BackButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            BackButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            BackButton.setToolTipText ("Click this button to return to the main menu.");
            BackButton.setMnemonic (KeyEvent.VK_B);
            BackButton.setActionCommand ("Back");
            BackButton.addActionListener (this);
            AddRowButton = new JButton ("Add Row");
            AddRowButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            AddRowButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            AddRowButton.setToolTipText ("Click this button to add a row.");
            AddRowButton.setMnemonic (KeyEvent.VK_A);
            AddRowButton.setActionCommand ("AddRow");
            AddRowButton.addActionListener (this);
            SplashLabel.setSize (250, 195);
            SplashLabel.setLocation (20, -25);
            add (SplashLabel);
            ModifyEntriesButton.setSize (250, 30);
            ModifyEntriesButton.setLocation (20, 140);
            add (ModifyEntriesButton);
            ViewEntriesButton.setSize (250, 30);
            ViewEntriesButton.setLocation (20, 170);
            add (ViewEntriesButton);
            SearchEntriesButton.setSize (250, 30);
            SearchEntriesButton.setLocation (20, 200);
            add (SearchEntriesButton);
        public void actionPerformed (ActionEvent e)
            if ("ModifyEntries".equals (e.getActionCommand ()))
                removeAll ();
                createTable ();
                JTable modifyTable = new JTable (model);
                JScrollPane tableScroll = new JScrollPane (modifyTable);
                tableScroll.setSize (250, 120);
                tableScroll.setLocation (20, 20);
                add (tableScroll);
                AddRowButton.setSize (250, 30);
                AddRowButton.setLocation (20, 140);
                add (AddRowButton);
                SaveButton.setSize (250, 30);
                SaveButton.setLocation (20, 170);
                add (SaveButton);
                BackButton.setSize (250, 30);
                BackButton.setLocation (20, 200);
                add (BackButton);
                updateUI ();
            if ("ViewEntries".equals (e.getActionCommand ()))
                removeAll ();
                BackButton.setLocation (20, 200);
                add (BackButton);
                updateUI ();
            if ("SearchEntries".equals (e.getActionCommand ()))
                removeAll ();
                BackButton.setLocation (20, 200);
                add (BackButton);
                updateUI ();
            if ("Back".equals (e.getActionCommand ()))
                removeAll ();
                add (ModifyEntriesButton);
                add (ViewEntriesButton);
                add (SearchEntriesButton);
                add (SplashLabel);
                updateUI ();
            if ("AddRow".equals (e.getActionCommand ()))
                model.addRow (new Vector ());
            if ("Save".equals (e.getActionCommand ()))
        // Creates the GUI and shows it.
        // For thread safety, this method should be invoked from the event-dispatching thread.
        private static void createAndShowGUI ()
            //Window decorations.
            JFrame.setDefaultLookAndFeelDecorated (true);
            //Create and set up the window.
            JFrame frame = new JFrame ("Swisha Computer House");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            frame.setResizable (false);
            //Create and set up the content pane.
            JComponent newContentPane = new CPT ();
            newContentPane.setOpaque (true); //Content panes must be opaque.
            frame.setContentPane (newContentPane);
            //Displays the window.
            frame.pack ();
            frame.setSize (300, 280);
            frame.setVisible (true);
        //Returns either an image icon or null if the path was invalid.
        protected static ImageIcon createImageIcon (String path, String description)
            java.net.URL imgURL = CPT.class.getResource (path);
            if (imgURL != null)
                return new ImageIcon (imgURL, description);
            else
                System.err.println ("Couldn't find file: " + path);
                return null;
        public static void main (String[] args)
            //Schedules a job for the event-dispatching thread.
            //Creates and shows this application's GUI.
            javax.swing.SwingUtilities.invokeLater (new Runnable ()
                public void run ()
                    createAndShowGUI ();
    }

    actually, i got around it by doing the following:
    try
                PrintWriter out2 = new PrintWriter (new FileWriter ("entries.dat"));
                out2.print ("Item Number|Description|Price|");
                out2.println ();
                for (int j = 0 ; j < rows ; j++)
                    for (int k = 0 ; k < columns ; k++)
                        String value = (String) modifyTable.getValueAt (j, k);
                        out2.print (value);
                        out2.print ("|");
                    out2.println ();
                out2.close ();
            catch (IOException ee)
                throw new RuntimeException (ee);
            }so...again, i havent found the code to do it? oh camickr.
    p.s. hell no im not giving u the honour of basking your name beside mine on a sheet of paper.
    the hard part was implementing all this code into the overall program, using my layout which you hate so much for adding and removing components. and i pursued this method because i knew how much youd hate it. yes....heh...yes....
    good game. i win.

  • How to use Jtable cell Editor

    HI,
    Here trying to populate the ImageIcon using JLabel in Jtable cell. For that I used DefaultCellRenderer. For implement the mouseListener to label I used the DefaultCellEditor. I am facing one problem here. After editing the label I selected the second row of the table, the first row image is not displaying. Can any one help on this issue?
    public class LabelCellEditor extends DefaultCellEditor {
    public LabelCellEditor(final JCheckBox checkBox) {
    super(checkBox);
    public Component getTableCellEditorComponent(final JTable table, final Object value,
    final boolean isSelected, final int row, final int column) {
    Color background = null;
    background = ColorManager.SELECTED_ROW_BGCOLOR;
    labelVal = (JLabel) value;
    labelVal.setOpaque(true);
    labelVal.setFont(FontManager.TABLE_DATA_FONT);
    labelVal.setBackground(background);
    labelPanel = new JPanel();
    labelPanel.setOpaque(true);
    labelPanel.setBackground(background);
    labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    labelPanel.setBorder(new EmptyBorder(5, 0, 0, 0));
    labelPanel.add(labelVal);
    return this.labelPanel;
    public Object getCellEditorValue() {
    return this.labelPanel;
    public class LabelCellRenderer extends DefaultTableCellRenderer {
    public LabelCellRenderer(final int alignment) {
    //setHorizontalAlignment(alignment);
    this.align = alignment;
    public Component getTableCellRendererComponent(final JTable table, final Object value,
    final boolean isSelected, final boolean hasFocus, final int row, final int column) {
    if (value != null) {
    if (value instanceof JLabel) {
    labelVal = (JLabel) value;
    labelVal.setOpaque(true);
    labelVal.setFont(FontManager.TABLE_DATA_FONT);
    labelVal.setBackground(background);
    labelVal.setHorizontalAlignment(this.align);
    labelVal.setBorder(new EmptyBorder(0, LRPADD, 0, LRPADD));
    JPanel panel = new JPanel();
    panel.setOpaque(true);
    panel.setBackground(background);
    panel.setLayout(new FlowLayout(FlowLayout.LEFT));
    panel.setBorder(new EmptyBorder(5, 0, 0, 0));
    panel.add(labelVal);
    return panel;
    return this;
    }

    With more than 30 postings you should know by now how to use the "Code" tags when posting code so the code reatains its original formatting and is therefore more readable.
    There is no need to create a custom editor, here is a simple example.

  • The correct approach to intercept TAB key

    Dear Experts,
    I have developed a GUI out of javax.swing. The GUI consists of JFrame, several JPanels and javax components, such as JTextField, JLabel, JComboBox, JTable and many more.
    Now, I want to change the behavior when user presses TAB key. By default TAB key moves focus from a component to another component. How can I disable this?
    I come to two alternatives that I am not sure which one is the correct approach. Could you please advise me?
    Alternative 1.
    Use key binding on GlassPane.
    Alternative 2.
    Use event-handling on GlassPane.
    If those alternatives are not the best one, could you please provide another alternative?
    I have tried the following, but they didn't work...
    Action doNothing = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Tab-key is pressed.");
    cmbPCode.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "doNothing");
    cmbPCode.getActionMap().put("doNothing", doNothing);or
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "doNothing");
    getRootPane().getActionMap().put("doNothing", doNothing);where cmbPCode is a JComboBox that receives focus when the GUI shows up.
    Thanks for your help,
    Patrick
    Edited by: Patrick_Stiady on Mar 31, 2009 6:51 AM

    Thank you for the advice. I am developing an application where the user is not computer literated, so that I have to limit functional key as many as possible and only allow several keys to be active. For example, I don't want TAB key to change the focus, instead I want TAB key to do nothing.
    I have tried keybinding, because I think this is the most relevant, but somehow I failed to recognize which component should be bound with keybinding. I have tried to change the input map of the component that receives the focus when the GUI is displayed (cmbPCode) as can be seen on my first post. I also tried to change the input map of the root pane. Both are not successful.
    Now, I wonder whether
    1. it does not work because the key is not consume()?
    2. Or should I use key listener, which I would only use if keybinding were unable to serve my goal?
    3. Or should I learn how to intercept key on the glass pane?
    4. Is keybinding able to nullify default action, such as changing focus by TAB key? I am asking this, because I'm going to nullify other important key such as ENTER key.
    Thank you for any guidance,
    Patrick

  • GridBagLayout - need to keep components stable

    Is there a way, using GridBagLayout, to keep the components (JTable, JComboBox) from resizing and/or repositioning themselves when the window resizes? I have the following positioned vertically (JLabel-JComboBox-JTable-JLabel):
    GridBagConstraints lgbc = new GridBagConstraints ();
    this.setLayout ( new GridBagLayout() );
    // Title label
    lgbc = new GridBagConstraints();
    lgbc.gridx = 0;
    lgbc.gridy = 0;
    lgbc.weightx = 0.0;
    lgbc.weighty = 0.0;
    lgbc.insets = new Insets ( 4,4,4,4 );
    lgbc.fill = GridBagConstraints.HORIZONTAL;
    lgbc.anchor = GridBagConstraints.NORTHWEST;
    this.add ( jlbTitle, lgbc );
    // Combo box
    lgbc = new GridBagConstraints();
    lgbc.gridy = 1;
    lgbc.weightx = 0.0;
    lgbc.weighty = 0.0;
    lgbc.fill = GridBagConstraints.HORIZONTAL;
    lgbc.insets = new Insets ( 2, 2, 2, 2 );
    lgbc.anchor = GridBagConstraints.NORTHWEST;
    this.add ( jcb, lgbc );
    // Scroll pane
    lgbc = new GridBagConstraints();
    lgbc.gridy = 2;
    lgbc.weightx = 1.0;
    lgbc.weighty = 1.0;
    lgbc.fill = GridBagConstraints.NONE;
    lgbc.anchor = GridBagConstraints.NORTHWEST;
    jsp.setMinimumSize ( jsp.getPreferredSize() );
    this.add ( jsp, lgbc );
    // Message label
    lgbc = new GridBagConstraints();
    lgbc.gridy = 3;
    lgbc.weightx = 0.0;
    lgbc.weighty = 0.0;
    lgbc.fill = GridBagConstraints.HORIZONTAL;
    lgbc.anchor = GridBagConstraints.NORTHWEST;
    this.add ( jlbMsg, lgbc );     
    What's happening is that when the window resizes to a smaller size, the panel containing the above components gets larger, and the components expand (via the fill) to take over the excess horizontal space, which I don't want to happen. However, if I remove the fill, the combobox in particular is not large enough to show its data.
    For this particular panel, everything else is working as desired (i.e. when the window resizes, the components don't move to the center or anything like that). I have at least 2 more panels to add to this window, but wanted to get this one working correctly before adding the other panels.
    Any suggestions on how to make sure the components are the same size when the window resizes?
    Thanks,
    Van Williams

    Thomas,
    thanks for the suggestion. However, the same thing is happening when I add the following code to the original code:
    lgbc = new GridBagConstraints();
    lgbc.gridy = 4;
    lgbc.weightx = 0.0;
    lgbc.weighty = 1.0;
    this.add ( new JPanel(), lgbc );
    I put a border around the object (the JLabels, JComboBox, and JTable combined) to see what's happening. When the window the object is placed on is shrunk vertically to be smaller than the JTable, the panel containing the object expands in size. Consequently, so do the JTable and JComboBox. I'd like for the components within the panel (and all other components I have yet to place on the window) to remain the same size and in the same position during all window resizing. Note... horizontal resizing doesn't seem to affect the component's size/position at all, which is exactly what I want.
    I've tried any number of things, including setting preferred/minimum/maximum sizes, and various combinations of weightx/weighty/fill/anchor, all without success. The way the code stands now is the best bet so far, but by no means the way I would like it to be.
    Thanks for any suggestions anyone may have.
    Thanks,
    Van Williams

  • Different Colors - ColorModel

    I have a Swing GUI on Windows NT with different colors.
    Then I started the same GUI on Solaris.
    If found out that Java does not use the whole RGB range on solaris - only 256 colors are used.
    The difference is that on Windows the DirectColorModel and on Solaris
    the IndexColorModel is used. (Toolkit.geToolkit.getDefaultToolkit().getColorModel())
    Is there a way to show the whole RGB range on Solaris?
    Thanks in advance,
    Anita

    Test thid code and tell me if you can change the display modes :
    * This test generates a table of all available display modes, enters
    * full-screen mode, if available, and allows you to change the display mode.
    * The application should look fine under each enumerated display mode.
    * On UNIX, only a single display mode should be available, and on Win32,
    * display modes should depend on direct draw availability and the type
    * of graphics card.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    class DisplayModeModel extends DefaultTableModel {
        private DisplayMode[] modes;
        public DisplayModeModel(DisplayMode[] modes) {
            this.modes = modes;
        public DisplayMode getDisplayMode(int r) {
            return modes[r];
        public String getColumnName(int c) {
            return DisplayModeTest.COLUMN_NAMES[c];
        public int getColumnCount() {
            return DisplayModeTest.COLUMN_WIDTHS.length;
        public boolean isCellEditable(int r, int c) {
            return false;
        public int getRowCount() {
            if (modes == null) {
                return 0;
            return modes.length;
        public Object getValueAt(int rowIndex, int colIndex) {
            DisplayMode dm = modes[rowIndex];
            switch (colIndex) {
                case DisplayModeTest.INDEX_WIDTH :
                    return Integer.toString(dm.getWidth());
                case DisplayModeTest.INDEX_HEIGHT :
                    return Integer.toString(dm.getHeight());
                case DisplayModeTest.INDEX_BITDEPTH : {
                    int bitDepth = dm.getBitDepth();
                    String ret;
                    if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
                        ret = "Multi";
                    } else {
                        ret = Integer.toString(bitDepth);
                    return ret;
                case DisplayModeTest.INDEX_REFRESHRATE : {
                    int refreshRate = dm.getRefreshRate();
                    String ret;
                    if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
                        ret = "Unknown";
                    } else {
                        ret = Integer.toString(refreshRate);
                    return ret;
            throw new ArrayIndexOutOfBoundsException("Invalid column value");
    public class DisplayModeTest extends JFrame implements ActionListener,
        ListSelectionListener {
         public KeyListener kl;
        private boolean waiting = false;
        private GraphicsDevice device;
        private DisplayMode originalDM;
        private JButton exit = new JButton("Exit");
        private JButton changeDM = new JButton("Set Display");
        private JLabel currentDM = new JLabel();
        private JTable dmList = new JTable();
        private JScrollPane dmPane = new JScrollPane(dmList);
        private boolean isFullScreen = false;
        public static final int INDEX_WIDTH = 0;
        public static final int INDEX_HEIGHT = 1;
        public static final int INDEX_BITDEPTH = 2;
        public static final int INDEX_REFRESHRATE = 3;
        public static final int[] COLUMN_WIDTHS = new int[] {100, 100, 100, 100 };
        public static final String[] COLUMN_NAMES = new String[] {"Width", "Height", "Bit Depth", "Refresh Rate"};
        public DisplayModeTest(GraphicsDevice device) {
            super(device.getDefaultConfiguration());
            this.device = device;
            setTitle("Display Mode Test");
            originalDM = device.getDisplayMode();
            setDMLabel(originalDM);
            setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            // Make sure a DM is always selected in the list
            exit.addActionListener(this);
            changeDM.addActionListener(this);
            changeDM.setEnabled(device.isDisplayChangeSupported());
            setUndecorated(true);
              addWindowListener(new WindowAdapter() {
                   public void windowActivated(WindowEvent e) {
                        changeScreen(true);
                   public void windowDeactivated(WindowEvent e) {
                        changeScreen(false);
        public void actionPerformed(ActionEvent ev) {
            Object source = ev.getSource();
            if (source == exit) {
                device.setDisplayMode(originalDM);
                System.exit(0);
              else { // if (source == changeDM)
                int index = dmList.getSelectionModel().getAnchorSelectionIndex();
                if (index >= 0) {
                    DisplayModeModel model = (DisplayModeModel)dmList.getModel();
                    DisplayMode dm = model.getDisplayMode(index);
                    device.setDisplayMode(dm);
                    setDMLabel(dm);
                    setSize(new Dimension(dm.getWidth(), dm.getHeight()));
                    validate();
        public void valueChanged(ListSelectionEvent ev) {
            changeDM.setEnabled(device.isDisplayChangeSupported());
        private void initComponents(Container c) {
            setContentPane(c);
            c.setLayout(new BorderLayout());
            // Current DM
            JPanel currentPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            c.add(currentPanel, BorderLayout.NORTH);
            JLabel current = new JLabel("Current Display Mode : ");
            currentPanel.add(current);
            currentPanel.add(currentDM);
            // Display Modes
            JPanel modesPanel = new JPanel(new GridLayout(1, 2));
            c.add(modesPanel, BorderLayout.CENTER);
            // List of display modes
            for (int i = 0; i < COLUMN_WIDTHS.length; i++) {
                TableColumn col = new TableColumn(i, COLUMN_WIDTHS);
    col.setIdentifier(COLUMN_NAMES[i]);
    col.setHeaderValue(COLUMN_NAMES[i]);
    dmList.addColumn(col);
    dmList.getSelectionModel().setSelectionMode(
    ListSelectionModel.SINGLE_SELECTION);
    dmList.getSelectionModel().addListSelectionListener(this);
    modesPanel.add(dmPane);
    // Controls
    JPanel controlsPanelA = new JPanel(new BorderLayout());
    modesPanel.add(controlsPanelA);
    JPanel controlsPanelB = new JPanel(new GridLayout(2, 1));
    controlsPanelA.add(controlsPanelB, BorderLayout.NORTH);
    // Exit
    JPanel exitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    controlsPanelB.add(exitPanel);
    exitPanel.add(exit);
    // Change DM
    JPanel changeDMPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    controlsPanelB.add(changeDMPanel);
    changeDMPanel.add(changeDM);
    controlsPanelA.add(new JPanel(), BorderLayout.CENTER);
    public void setVisible(boolean isVis) {
    super.setVisible(isVis);
    if (isVis) {
    dmList.setModel(new DisplayModeModel(device.getDisplayModes()));
    public void setDMLabel(DisplayMode newMode) {
    int bitDepth = newMode.getBitDepth();
    int refreshRate = newMode.getRefreshRate();
    String bd, rr;
    if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
    bd = "Multi";
    } else {
    bd = Integer.toString(bitDepth);
    if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
    rr = "Unknown";
    } else {
    rr = Integer.toString(refreshRate);
    currentDM.setText(
    COLUMN_NAMES[INDEX_WIDTH] + ": " + newMode.getWidth() + " "
    + COLUMN_NAMES[INDEX_HEIGHT] + ": " + newMode.getHeight() + " "
    + COLUMN_NAMES[INDEX_BITDEPTH] + ": " + bd + " "
    + COLUMN_NAMES[INDEX_REFRESHRATE] + ": " + rr
    public void begin() {
    isFullScreen = device.isFullScreenSupported();
    // setUndecorated(isFullScreen);
    // setResizable(!isFullScreen);
    if (isFullScreen) {
    // Full-screen mode
    device.setFullScreenWindow(this);
    validate();
    } else {
    // Windowed mode
    pack();
    setVisible(true);
    public void changeScreen(boolean full) {
    if (full) {
    // Full-screen mode
                   setResizable(!full);
    device.setFullScreenWindow(this);
    validate();
    } else {
    // Windowed mode
    device.setFullScreenWindow(null);
    // setUndecorated(full);
    /* setResizable(!full);
    pack();*/
    public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception ex) {
                   System.out.println(ex);
    GraphicsEnvironment env = GraphicsEnvironment.
    getLocalGraphicsEnvironment();
    GraphicsDevice[] devices = env.getScreenDevices();
    // REMIND : Multi-monitor full-screen mode not yet supported
    for (int i = 0; i < 1 /*devices.length */; i++) {
    DisplayModeTest test = new DisplayModeTest(devices[i]);
    test.initComponents(test.getContentPane());
    test.setVisible(true);
    // test.begin();
              //     test.changeScreen(false);
    Denis

  • How to select JLabel inside a JTable

    hi all,
    I have a Jtable which has own renderer so it can store components in it. I have added a Jlabel one of its cells but when I select that row the label stays upon the selected background color. here is a sample screenshot to decribe my problem clearly [http://www.imagecross.com/06/image-hosting-view-01.php?id=6570label.jpg]
    is there any way to select the label inside selected background color.
    - I have already tried to make the label not opaque but it didnt work -
    thanks...

    I have added bold parts of the code below. if you use other components you can make a type casting and do what you want.
    thanks again..
    class ComponentRenderer *extends JComponent*  implements TableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
        *     JLabel l = (JLabel)value;*
        *     if(isSelected) {*
        *          l.setForeground(Color.BLUE);*
        *          l.setOpaque(true);*
        *          l.setBackground(new Color(184, 207, 229));*
        *     else {*
        *          l.setForeground(Color.BLACK);*
        *          l.setOpaque(true);*
        *          l.setBackground(Color.WHITE);*
            return l;
        /*public ComponentRenderer() {
    }

  • Trying to set a JLabel off of a JTable

    Hi! I am trying to let a user select a row from a Jtable and have those highlighted values displayed below in another panel. Problem is that the gui never seems to refresh. Any ideas?
    public class MainClass{
      public static void main( String[] args ){
        JFrame mainFrame = new JFrame( "Main Class" );
        MyTableModel tableModel = new MyTableModel();
        JTable table = new JTable( tableModel );
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener( new PanelModel() );
        JScrollPane tableScrollPane = new JScrollPane( table );
        tableScrollPane.setPreferredSize( new Dimension( 80, 80 ) );
        PanelView panelView = new PanelView();
        JScrollPane panelScrollPane = new JScrollPane( panelView );
        panelScrollPane.setPreferredSize( new Dimension(80, 80) );
        mainFrame.getContentPane().add( tableScrollPane, BorderLayout.NORTH );
        mainFrame.getContentPane().add( panelScrollPane, BorderLayout.SOUTH );
        mainFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        mainFrame.pack();
        mainFrame.setVisible( true );
    public class PanelModel implements ListSelectionListener{
      private String anything;
      MyTableModel tableModel = new MyTableModel();
      public void valueChanged(ListSelectionEvent lse) {
        if (lse.getValueIsAdjusting()) return;
        ListSelectionModel lsm = (ListSelectionModel)lse.getSource();
        if (lsm.isSelectionEmpty()) {
          //no rows are selected
        } else {
          int selectedRow = lsm.getMinSelectionIndex();
          String rowValue = (String)tableModel.getValueAt(selectedRow, 0);
          this.populate( rowValue );
      public void populate(String something){
        this.setAnything(something);
        PanelView myPanelView = new PanelView();
        myPanelView.RowInfoField.setText(this.getAnything());
        myPanelView.updateUI();
      public String getAnything() {
        return this.anything;
      public void setAnything( String anything ) {
        this.anything = anything;
    public class MyTableModel extends AbstractTableModel{
      private String[] columns = {"Column 1"};
      private String[][] rows = { {"Something"}, {"Anything"} };
      private static int selectedRow;
      public int getColumnCount(){
        return columns.length;
      public int getRowCount(){
        return rows.length;
      public int getSelectedRow(){
        return selectedRow;
      public Object getValueAt(int r, int c){
        if(rows[r] != null && columns[c] != null){
          return rows[r][c];
        return null;
    public class PanelView  extends JPanel{
      MyTableModel tm;
      int rowSelected = 0;
      private String rowInfo;
      JLabel RowInfoField;
      JLabel RowInfoLabel;
      JPanel panelModel;
      public PanelView() {
        panelModel = new JPanel( new GridLayout() );
        tm = new MyTableModel();
        rowSelected = tm.getSelectedRow();
        rowInfo = (String)tm.getValueAt(rowSelected,0);
        JLabel RowInfoLabel = new JLabel( "RowInfo  " );
        RowInfoLabel.setForeground( Color.black );
        RowInfoField = new JLabel(rowInfo);
        RowInfoField.setFont( new Font( "Serif", 1, 11 ) );
        panelModel.add( RowInfoLabel );
        panelModel.add( RowInfoField );
        this.add( panelModel );
        this.setEnabled( true );
    }

    The problem is in the PanelModel.java line 24. Every time you create new PanelView but not add to the Frame. Following is a quick fix.
    PanelModel.java
    ===================================================================
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class PanelModel implements ListSelectionListener{
    private String anything;
    MyTableModel tableModel = new MyTableModel();
    public void valueChanged(ListSelectionEvent lse) {
    if (lse.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)lse.getSource();
    if (lsm.isSelectionEmpty()) {
    //no rows are selected
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    String rowValue = (String)tableModel.getValueAt(selectedRow, 0);
    this.populate( rowValue );
    public void populate(String something){
              System.out.println("something: " + something);
    this.setAnything(something);
              MainClass.panelView.RowInfoField.setText(this.getAnything());
    // PanelView myPanelView = new PanelView();
    // myPanelView.RowInfoField.setText(this.getAnything());
    // myPanelView.updateUI();
    public String getAnything() {
    return this.anything;
    public void setAnything( String anything ) {
    this.anything = anything;
    ===================================================================
    MainClass.java
    ===================================================================
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class MainClass{
    public static PanelView panelView;
    public static void main( String[] args ){
    JFrame mainFrame = new JFrame( "Main Class" );
    MyTableModel tableModel = new MyTableModel();
    JTable table = new JTable( tableModel );
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener( new PanelModel() );
    JScrollPane tableScrollPane = new JScrollPane( table );
    tableScrollPane.setPreferredSize( new Dimension( 80, 80 ) );
    panelView = new PanelView();
    JScrollPane panelScrollPane = new JScrollPane( panelView );
    panelScrollPane.setPreferredSize( new Dimension(80, 80) );
    mainFrame.getContentPane().add( tableScrollPane, BorderLayout.NORTH );
    mainFrame.getContentPane().add( panelScrollPane, BorderLayout.SOUTH );
    mainFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    mainFrame.pack();
    mainFrame.setVisible( true );
    ===================================================================
    MyTableModel.java
    ===================================================================
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class MyTableModel extends AbstractTableModel{
    private String[] columns = {"Column 1"};
    private String[][] rows = { {"Something"}, {"Anything"} };
    private static int selectedRow;
    public int getColumnCount(){
    return columns.length;
    public int getRowCount(){
    return rows.length;
    public int getSelectedRow(){
    return selectedRow;
    public Object getValueAt(int r, int c){
    if(rows[r] != null && columns[c] != null){
    return rows[r][c];
    return null;
    ===================================================================
    PanelView.java
    ===================================================================
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class PanelView extends JPanel{
    MyTableModel tm;
    int rowSelected = 0;
    private String rowInfo;
    JLabel RowInfoField;
    JLabel RowInfoLabel;
    JPanel panelModel;
    public PanelView() {
    panelModel = new JPanel( new GridLayout() );
    tm = new MyTableModel();
    rowSelected = tm.getSelectedRow();
    rowInfo = (String)tm.getValueAt(rowSelected,0);
    JLabel RowInfoLabel = new JLabel( "RowInfo " );
    RowInfoLabel.setForeground( Color.black );
    RowInfoField = new JLabel(rowInfo);
    RowInfoField.setFont( new Font( "Serif", 1, 11 ) );
    panelModel.add( RowInfoLabel );
    panelModel.add( RowInfoField );
    this.add( panelModel );
    this.setEnabled( true );
    ===================================================================

  • Cannot display JLabel text in JTable

    Hi, This is a simple but frustrating little problem
    I am having trouble displaying the label text in a column of a JTable.
    I have hacked up a copy of TableDialogEditDemo.java from the tutorials
    on using JTables. This uses a renderer and editor models to deal with a
    column of colors.
    I have changed it to use JLabels instead. What want is for the label
    text to appear and when the user selects the cell be allowed to launch
    a dialog box (such as the demo program does with colorchooser).
    The dialog launching funcionalty works fine but the label text does not display.
    I end up with the column of JLabels as blank, even though the values
    are properly set. It seems like the TableCellRenderer doesn't display the
    controls text.
    I've spent the better part of two work days trying to get this one to work.
    Compiling and just running the code (without any interaction with the table)
    shows the problem. The second column of items will be blank instead of
    cells with text.
    Help!
    Thanks!
    /Steve McCauley
    Sanera Systems
    [email protected]
    Here is the code:
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JDialog;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JColorChooser;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.awt.*;
    import java.awt.event.*;
    * This is like TableEditDemo, except that it substitutes a
    * Favorite Color column for the Last Name column and specifies
    * a custom cell renderer and editor for the color data.
    public class TableDialogEditDemo extends JFrame {
    private boolean DEBUG = false;
    public TableDialogEditDemo() {
    super("TableDialogEditDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up renderer and editor for the Favorite Color column.
    setUpColorRenderer(table);
    setUpColorEditor(table);
    //Set up real input validation for integer data.
    setUpIntegerEditor(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class ColorRenderer extends JLabel
    implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;
    public ColorRenderer(boolean isBordered) {
    super();
    this.isBordered = isBordered;
    // setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    // setBackground((Color)color);
    setForeground(Color.black);
    setBackground(Color.white);
    System.out.println(" Label: " + ((JLabel)color).getText());
    if (isBordered) {
    if (isSelected) {
    if (selectedBorder == null) {
    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getSelectionBackground());
    setBorder(selectedBorder);
    } else {
    if (unselectedBorder == null) {
    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getBackground());
    setBorder(unselectedBorder);
    return this;
    private void setUpColorRenderer(JTable table) {
    table.setDefaultRenderer(JLabel.class,
    new ColorRenderer(true));
    //Set up the editor for the Color cells.
    private void setUpColorEditor(JTable table) {
    //First, set up the button that brings up the dialog.
    final JButton button = new JButton("") {
    public void setText(String s) {
    //Button never shows text -- only color.
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0,0,0,0));
    //Now create an editor to encapsulate the button, and
    //set it up as the editor for all Color cells.
    final ColorEditor colorEditor = new ColorEditor(button);
    table.setDefaultEditor(JLabel.class, colorEditor);
    //Set up the dialog that the button brings up.
    final JColorChooser colorChooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    colorEditor.currentLabel = new JLabel("xxx");
    final JDialog dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true,
    colorChooser,
    okListener,
    null); //XXXDoublecheck this is OK
    //Here's the code that brings up the dialog.
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // button.setBackground(colorEditor.currentColor);
    // colorChooser.setColor(colorEditor.currentColor);
    //Without the following line, the dialog comes up
    //in the middle of the screen.
    //dialog.setLocationRelativeTo(button);
    dialog.show();
    * The editor button that brings up the dialog.
    * We extend DefaultCellEditor for convenience,
    * even though it mean we have to create a dummy
    * check box. Another approach would be to copy
    * the implementation of TableCellEditor methods
    * from the source code for DefaultCellEditor.
    class ColorEditor extends DefaultCellEditor {
    JLabel currentLabel = null;
    public ColorEditor(JButton b) {
    super(new JCheckBox()); //Unfortunately, the constructor
    //expects a check box, combo box,
    //or text field.
    editorComponent = b;
    setClickCountToStart(1); //This is usually 1 or 2.
    //Must do this so that editing stops when appropriate.
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    protected void fireEditingStopped() {
    super.fireEditingStopped();
    public Object getCellEditorValue() {
    return currentLabel;
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column) {
    ((JButton)editorComponent).setText(value.toString());
    currentLabel = (JLabel)value;
    return editorComponent;
    private void setUpIntegerEditor(JTable table) {
    //Set up the editor for the integer cells.
    final WholeNumberField integerField = new WholeNumberField(0, 5);
    integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
    DefaultCellEditor integerEditor =
    new DefaultCellEditor(integerField) {
    //Override DefaultCellEditor's getCellEditorValue method
    //to return an Integer, not a String:
    public Object getCellEditorValue() {
    return new Integer(integerField.getValue());
    table.setDefaultEditor(Integer.class, integerEditor);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Favorite Color",
    "Sport",
    "# of Years",
    "Vegetarian"};
    // final Object[][] data = {
    // {"Mary", new Color(153, 0, 153),
    // "Snowboarding", new Integer(5), new Boolean(false)},
    // {"Alison", new Color(51, 51, 153),
    // "Rowing", new Integer(3), new Boolean(true)},
    // {"Kathy", new Color(51, 102, 51),
    // "Chasing toddlers", new Integer(2), new Boolean(false)},
    // {"Mark", Color.blue,
    // "Speed reading", new Integer(20), new Boolean(true)},
    // {"Philip", Color.pink,
    // "Pool", new Integer(7), new Boolean(false)}
    final Object[][] data = {
    {"Mary", new JLabel("label-1"),
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", new JLabel("label-2"),
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", new JLabel("label-3"),
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", new JLabel("label-4"),
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", new JLabel("label-5"),
    "Pool", new Integer(7), new Boolean(false)}
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * 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) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 1) {
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    public static void main(String[] args) {
    TableDialogEditDemo frame = new TableDialogEditDemo();
    frame.pack();
    frame.setVisible(true);

    You pretty much hit the nail on the head. Thank!
    Just didn't realize I needed to set the text of the component but with your
    tip and thinking about it, it makes sense.
    Actually I needed to use:
    setText(t_label.getText());
    Using toString got me: "java.swing......" (the components text representation)
    Thanks a bunch!
    /Steve

  • JLabel as cell of JTable

    Hi All,
    I am using JLabel as a cell of a JTable by overriding getTableCellRendererComponent method of the renderer.But I am not able to select/focus on any of the cell by clicking at cells.However If I use any other componenet like JTextArea, I can select any cell I want.
    I have to use JLabel because i want to put multiple color and fonts in a single cell.I dont't want to use JTextPane because it takes more memory as well as It has wraping problem
    Any help would be greatly appreciated

    It's not a good idea to create a NEW Component each and every time getXXXCellRenderer() is called. Object creation is VERY expensive!!!
    Remember, this Component is merely renderered (e.g. painted, or "rubber-stamped") into the Graphics Context of the JTable, after appropriate sizing to fit the cell, of course. So the SAME component can be used to render each and every cell, each and every time each cell needs to be rendered. (Unless different Component classes are used to render different cells, but still, one of each of these Components should be created in the Constructor, not each time a cell is rendered.)
    I have reworked your code to make it much more efficient, and to make it more readable:
    public class MyTableCellRenderer
        implements TableCellRenderer
        JLabel label = new JLabel();
        public MyTableCellRenderer()
            super();
            this.label.setOpaque(true);
        public Component getTableCellRendererComponent( JTable  table,
                                                        Object  value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int     row,
                                                        int     column )
            String st=null;
            st="<HTML><B><FONT Color=Red>" + value.toString() 
               + "</FONT></B></HTML>";
            this.label.setText(st);
            if (isSelected) {
                this.label.setBackground( table.getSelectionBackground());
            } else {
                this.label.setBackground(Color.yellow);
            return this.label;
    }You may find that using HTML as the text of JLabel is much too expensive, especially with a large table. I tried it once, with a table of only moderate size, and gave up. It's much faster to set the font, foreground color, etc., on the JLabel itself instead.
    I was trying to use HTML simply to get HTML Character Entities (like &amp;) to display correctly, and it just didn't work. I wrote my own class to parse strings for HTML Character Entities, replacing them with appropriate Unicode characters, and it worked much better.
    ---Mark

  • Creating a JTable of JLabels presented in a JScrollPane()

    Hi, I want to create an object showing all/some colored labels. I get it presented with 5 columns, but nothing is colored. Her is a part of the logic:
    public MyColorTableModel()
    // String [][] array;
    array = new JLabel [280][10]; //Just for test purposes
    int row=0;
    int col=0;
    String cc;
    JLabel lbl;
    for (r=0; r<256; r++)
    System.out.println("Red number is : " + r);
    for (g=0; g<256; g++)
    System.out.println("Green number is: " + g);
    for (b=0; b<256; b++)
    cc = ("R= "+r+" G= "+g+" B= "+b);
    lbl = new JLabel(cc);
    lbl.setOpaque(true);
    lbl.setBackground(new Color(r, g, b));
    array[row] [col] = lbl; //Is this the problem???
    if (col==4)
    col=-1;
    row++;
    col++;
    r=600; g=600; //Force stop
    Thanks
    tjoge01

    Totally the wrong way of going about it, using exactly what JTable is designed to avoid (ie huge numbers of components).
    Read this,
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer

  • Printing JTable with DefaultTableCellRenderer (or JLabel's)

    Hi there,
    I am trying to print a JTable by having it implement the Printable interface. It works, but it works only because I use the string values from the renderers of the cells. This works fine if its just simple left alligned strings.
    But when you are using formatted text strings for instance (in a DefaultTableCellRenderer extension) or something that represents a boolean (a checkbox), it doesn't look very good. Bad actually. I tried to use the print method on the renderer or cast them first to a JComponent or JLabel and then use the print method. No success so far. Can anybody help me? I am quit desperate right now.
    Kind regards,
    Ren�

    Yes I can. I took the print method from the class in which I implemented it (the JTable is a member of that particular class):
    * Implementing the Printable interface.
    * For printing the same font is used as is used on the screen.
    * So, no special print font is used or can be choosen at this
    * point. Also the font size is taken from the table on screen.
    * The title font is twice the font size of the normal font, but
    * bold. The column headers have the same font as the normal font
    * but also bold like the title.
    * The height we'll be using for a line of text will be 1.5 times
    * the average height in this font, with a minimum of 10.
    * The title font, the table header font and the table content font
    * are all the same (unlike the table) and based on the table font.
    * The table header font is not used.
    * If the table does not fit on paper, one could adjust the orientation
    * of the paper in the paper dialog, or adjust the distance bewtween
    * the columns on the screen as the column width on the screen is
    * taken to the paper.
    public int print(Graphics pg, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (pageIndex >= m_maxNumPage) {
    return NO_SUCH_PAGE;
    // This is for anti aliasing.
    Graphics2D g2d = null;
    if (pg instanceof Graphics2D) {
    g2d = (Graphics2D) pg;
    g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
    g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
    pg.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());
    int wPage = (int) pageFormat.getImageableWidth();
    int hPage = (int) pageFormat.getImageableHeight();
    // This will make sure no printing is
    // done outside the designated area.
    pg.setClip(0, 0, wPage, hPage);
    // Forget this: its a test (works fine though).
    //table.print(g2d);
    //if (true)
    // return PAGE_EXISTS;
    int y = 0;
    // Make the title font size twice the size of the regular font size.
    pg.setFont(this.table.getFont().deriveFont(Font.BOLD, (this.table.getFont().getSize() * 2)));
    pg.setColor(Color.black);
    FontMetrics fm = pg.getFontMetrics();
    y += fm.getAscent();
    // Draw the title, the date and the page number.
    pg.drawString(pageTitle + " " + DateFormat.getDateInstance(DateFormat.MEDIUM, this.locale).format(new Date(System.currentTimeMillis())) + " (" + (pageIndex + 1) + ") ", 0, y);
    //          pg.drawString(pageTitle + " " + DateFormat.getDateInstance().format(new Date(System.currentTimeMillis())) + " (" + (pageIndex + 1) + ") ", 0, y);
    y += 20; // space between title and table headers
    // The font for the table headers.
    Font headerFont = this.table.getTableHeader().getFont();
    pg.setFont(headerFont);
    fm = pg.getFontMetrics();
    TableColumnModel colModel = this.table.getColumnModel();
    int nColumns = colModel.getColumnCount();
    int x[] = new int[nColumns];
    x[0] = 0;
    int h = fm.getAscent();
    // Add ascent of header font because of baseline positioning.
    y += h;
    int nRow, nCol;
    // Draw the COLUMN HEADERS.
    for (nCol = 0; nCol < nColumns; nCol++) {
    TableColumn tk = colModel.getColumn(nCol);
    int width = tk.getWidth();
    String title = (String) tk.getIdentifier();
    // The x offset for each column stored.
    if (nCol + 1 < nColumns) {
    x[nCol + 1] = x[nCol] + width;
    // If this is not the last column header, calculated
    // how many characters can be printed, based on the
    // width of the column being printed.
    if ((nCol < (nColumns - 1)) && title.length() > 0) {
    //if (x[nCol] + width <= wPage) {
    for (int i = title.length(); i >= 0; i--) {
    if ((fm.stringWidth(title.substring(0, i))) <= width) {
    // Adjust the colum header for the space available (the width).
    title = title.substring(0, i);
    break;
    // Draw the column header.
    pg.drawString(title, x[nCol], y);
    pg.setFont(this.table.getFont());
    fm = pg.getFontMetrics();
    int header = y;
    // Gets the standard height of a line of text in this font.
    // This is the distance between the baseline of adjacent lines of text.
    // It is the sum of the leading + ascent + descent. There is no guarantee
    // that lines of text spaced at this distance are disjoint; such lines may
    // overlap if some characters overshoot either the standard ascent or the
    // standard descent metric.
    h = fm.getHeight();
    // Calculate the ACTUAL height we'll be using for a line of text.
    // That would be 1.5 times the average height, with a minimum of 10.
    // Actually, normally, the average height should suffice. But we're
    // not taking any risks here.
    int rowHeight = Math.max((int) (h * 1.5), 10);
    // Calculate how many rows fit on a page.
    int rowPerPage = (hPage - header) / rowHeight;
    m_maxNumPage = Math.max((int) Math.ceil(this.table.getRowCount() / (double) rowPerPage), 1);
    int iniRow = pageIndex * rowPerPage;
    int endRow = Math.min(this.table.getRowCount(), iniRow + rowPerPage);
    String cell = null;
    // Draw every ROW.
    for (nRow = iniRow; nRow < endRow; nRow++) {
    y += rowHeight;
    // Draw each CELL in each ROW.
    for (nCol = 0; nCol < nColumns; nCol++) {
    cell = null;
    int col = this.table.getColumnModel().getColumn(nCol).getModelIndex();
    // Get the cell object. This is the object that needs to be printed.
    Object object = model.getValueAt(nRow, col);
    // RENDERING FOR PRINTING! Here is determined for the printing how the rendering is done.
    // If a special renderer had been set an attempt is made to use that renderer (e.g. get the text).
    // If that is not possible, simple rendering: the toString() value.
    // BE AWARE! The format for numbers, booleans etc. might require better code.
    if (table.getColumnModel().getColumn(nCol).getCellRenderer() != null) {
    if (table.getColumnModel().getColumn(nCol).getCellRenderer().getTableCellRendererComponent(table, object, false, false, nRow, nCol) != null) {
    if (table.getColumnModel().getColumn(nCol).getCellRenderer().getTableCellRendererComponent(table, object, false, false, nRow, nCol) instanceof JLabel) {
    cell = ((JLabel) table.getColumnModel().getColumn(nCol).getCellRenderer().getTableCellRendererComponent(table, object, false, false, nRow, nCol)).getText();
    //table.getCellRenderer(0, nCol).getTableCellRendererComponent(table, object, false, false, 0, nCol).paint(g2d);
    // Object fiets = table.getCellRenderer(0, nCol).getTableCellRendererComponent(table, object, false, false, 0, nCol);
    // if (fiets instanceof DefaultTableCellRenderer) {
    //      System.out.println("DefaultTableCellRenderer!" + nCol);
    //      ((DefaultTableCellRenderer) fiets).print(pg);
    // If the object is a Boolean, print an "X" or an "O".
    if (object instanceof Boolean) {
    cell = (((Boolean) object).equals(new Boolean(true)) ? "X" : "O");
    // Still don't know how to print it? Use the object's toString() method.
    // This is probably used in most cases anyway!
    if (cell == null && object != null) {
    //cell = object.toString();
    if (cell == null) {
    cell = "";
    // If this is not the last column, calculated how many
    // characters can be printed, based on the width of
    // the column being printed.
    if ((nCol < (nColumns - 1)) && cell.length() > 0) {
    int width = colModel.getColumn(nCol).getWidth();
    for (int i = cell.length(); i >= 0; i--) {
    if ((fm.stringWidth(cell.substring(0, i))) <= width) {
    // Adjust the size.
    cell = cell.substring(0, i);
    break;
    // Print the cell.
    pg.drawString(cell, x[nCol], y);
    System.gc();
    return PAGE_EXISTS;
    }

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // Returning the Class of each column will allow different
              // renderers to be used based on Class
              public Class getColumnClass(int column)
                   return getValueAt(0, column).getClass();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

Maybe you are looking for

  • Project file will not open in iMovie

    My son started an Export and stopped it without allowing it to finish and his project file disappeared from iMovie. After using Finder, I'm able to find his project along with the my other projects. But when I do a "right click" and select "Open with

  • Can I change the smtp server with Yahoo push account?

    My yahoo email account will send and receive over EDGE using the default yahoo mail settings. On my home Cox internet WiFi network I can retrieve messages but cannot send. When sending it says it was sent and makes the "swooshing" mail sent sound, bu

  • Color swatch panel

    The color swatch panel is missing from tool bar and will not come up CS6 CS6.

  • Touch sensitivity on iPhone 5. #someone please help me

    Do you guys have any problem with your iPhone 5 touch calibration/sensitivity when it reached between 90%-100% while charging?? Because my iPhone has that such problem. When I'm using my iPhone 5 while it is in charging state between 90%-100%, the to

  • UDF to send Response to RFC

    Hi Experts, We have a scenario where we have to send a response back to RFC from UDF . How can we do this without using RFC lookups ? Regards, Syed