how to insert Image a row in DefaultTableModel? - java

public static void table2() {
Object num[] = new Object[1];
for (int q = 0; q < MyDto.userList.size(); q++) {
try {
//ImageIcon i2 = new ImageIcon(new ImageIcon(MyDto.userList.get(q).getMyImg()).getImage()
// .getScaledInstance(150, 120, Image.SCALE_SMOOTH));
ImageIcon i2 = new ImageIcon("/Users/junseok/Desktop/1.png");
JLabel lbImage1 = new JLabel(i2);
lbImage1.setIcon(i2);
num[0] = lbImage1;
model2.addRow(num);
System.out.println(num[0].toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
why doesnt show image? why write only toString()??

why write only toString()??
The default renderer just invokes the toString() method of the object in the TableModel.
why doesnt show image?
You need to add an Icon to the TableModel (not a JLabel). Then you need to tell the table the Icon is stored in the column so the table can choose the appropriate renderer to paint the Icon.
This is done by overriding the getColumnClass(...) method of the TableModel:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JPanel
{
public TableIcon()
{
Icon aboutIcon = new ImageIcon("about16.gif");
Icon addIcon = new ImageIcon("add16.gif");
Icon copyIcon = new ImageIcon("copy16.gif");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "About"},
{addIcon, "Add"},
{copyIcon, "Copy"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
#Override
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable( model );
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Table Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TableIcon());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

Related

how to insert an image into a column table using DefaultTableCellRenderer in java

I write this code for inserting an image into a column
LessonTable.setDefaultRenderer(Object.class, new SimpleTableCellRenderer());
class SimpleTableCellRenderer extends DefaultTableCellRenderer {
ImageIcon image = new ImageIcon(getClass().getResource("imagefolder/this.png"));
JLabel lbl = new JLabel();
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (column == 1) {// i want to set image only for this column
lbl.setHorizontalAlignment(SwingConstants.LEFT);
lbl.setIcon(image);
}
else {
lbl.setHorizontalAlignment(SwingConstants.CENTER);
}
return lbl;
}
}
but this code inserts the image for all columns except second column.
what's wrong here?
Don't create a custom renderer. JTable already supports a renderer for Icons.
Instead what you need to do is override the getColumnClass(...) method of your table model to return Icon.class and the table will use the proper renderer.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JPanel
{
public TableIcon()
{
Icon aboutIcon = new ImageIcon("about16.gif");
Icon addIcon = new ImageIcon("add16.gif");
Icon copyIcon = new ImageIcon("copy16.gif");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "About"},
{addIcon, "Add"},
{copyIcon, "Copy"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
// 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();
}
};
JTable table = new JTable( model );
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Table Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TableIcon());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

Removing combobox as the cell editor of a jtable cell

I have made a combobox as cell editor of a column. I want when i create a new row the cell in that column should not have the combobox as the cell editor and should retain JTextField as the cell editor. Here is what i have done so far.
addRow(mainWindow.salesTable);
final TableColumn items = mainWindow.salesTable.getColumnModel().getColumn(0);
final JTextField tfield = new JTextField();
DefaultCellEditor editorqty = new DefaultCellEditor(tfield);
items.setCellEditor(editorqty);
private static void addRow(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
Vector row = new Vector();
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
model.addRow(row);
}
Overriding the getCellEditor(...) method of JTble is one approach:
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableComboBoxByRow extends JPanel
{
List<String[]> editorData = new ArrayList<String[]>(3);
public TableComboBoxByRow()
{
setLayout( new BorderLayout() );
// Create the editorData to be used for each row
editorData.add( new String[]{ "Red", "Blue", "Green" } );
editorData.add( new String[]{ "Circle", "Square", "Triangle" } );
editorData.add( new String[]{ "Apple", "Orange", "Banana" } );
// Create the table with default data
Object[][] data =
{
{"Color", "Red"},
{"Shape", "Square"},
{"Fruit", "Banana"},
{"Plain", "Text"}
};
String[] columnNames = {"Type","Value"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model)
{
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
if (modelColumn == 1 && row < 3)
{
JComboBox<String> comboBox1 = new JComboBox<String>( editorData.get(row));
return new DefaultCellEditor( comboBox1 );
}
else
return super.getCellEditor(row, column);
}
};
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Table Combo Box by Row");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableComboBoxByRow() );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Java Eclipse Jtable Cell / Column

for Java Kepler Eclipse and Jtable, I am trying to make it so as when a specific table cell is selected, that cell will work as an editorPane; or have the whole column work as editorPane. When I click a cell on column COMMENTS it enlargens the row but I cant get it to work as an editorPane. My project is actualy very different but I wrote this mini one with the table so you can copy, paste and run it to see exactly what the problem is when you click on a COMMENTS cell.
I tried to make the column an editorPane to begin with like I made the column DONE with checkBox, but it doesnt work or I am doing it wrong. I also tried cellRenderer but I couldnt make that work either.
Whether the whole column works as an editorPane or just the selected cell it doesnt matter, whatever is easier and as long as it works
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class JavaTestOne {
JFrame frmApp;
private JTable table;
private JCheckBox checkbox;
DefaultTableModel model;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaTestOne window = new JavaTestOne();
window.frmApp.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public JavaTestOne() {
initialize();
}
private void initialize() {
frmApp = new JFrame();
frmApp.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 13));
frmApp.setBounds(50, 10, 1050, 650);
frmApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmApp.getContentPane().setLayout(new CardLayout(0, 0));
frmApp.setTitle("App");
{
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 42, 984, 484);
frmApp.add(scrollPane);
{
table = new JTable();
table.setFillsViewportHeight(true);
Object[][] data = {
{"I01", "Tom",new Boolean(false), ""},
{"I02", "Jerry",new Boolean(false), ""},
{"I03", "Ann",new Boolean(false), ""}};
String[] cols = {"ID","NAME","DONE","COMMENTS"};
model = new DefaultTableModel(data, cols) {
private static final long serialVersionUID = -7158928637468625935L;
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table.setModel(model);
table.setRowHeight(20);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = table.rowAtPoint(evt.getPoint());
int col = table.columnAtPoint(evt.getPoint());
table.setRowHeight(20);
if(col==3){
table.setRowHeight(row, 100);
//this is where I need it to work as an editorPane if it is only for the selected cell
}
}
});
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
scrollPane.setViewportView(table);
checkbox = new JCheckBox("OK");
checkbox.setHorizontalAlignment(SwingConstants.CENTER);
checkbox.setBounds(360, 63, 97, 23);
}
}
}
}
Another alternative is to display a popup window to edit the cell:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
/*
* The editor button that brings up the dialog.
*/
//public class TablePopupEditor extends AbstractCellEditor
public class TablePopupEditor extends DefaultCellEditor
implements TableCellEditor
{
private PopupDialog popup;
private String currentText = "";
private JButton editorComponent;
public TablePopupEditor()
{
super(new JTextField());
setClickCountToStart(1);
// Use a JButton as the editor component
editorComponent = new JButton();
editorComponent.setBackground(Color.white);
editorComponent.setBorderPainted(false);
editorComponent.setContentAreaFilled( false );
// Make sure focus goes back to the table when the dialog is closed
editorComponent.setFocusable( false );
// Set up the dialog where we do the actual editing
popup = new PopupDialog();
}
public Object getCellEditorValue()
{
return currentText;
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
popup.setText( currentText );
// popup.setLocationRelativeTo( editorComponent );
Point p = editorComponent.getLocationOnScreen();
popup.setLocation(p.x, p.y + editorComponent.getSize().height);
popup.show();
fireEditingStopped();
}
});
currentText = value.toString();
editorComponent.setText( currentText );
return editorComponent;
}
/*
* Simple dialog containing the actual editing component
*/
class PopupDialog extends JDialog implements ActionListener
{
private JTextArea textArea;
public PopupDialog()
{
super((Frame)null, "Change Description", true);
textArea = new JTextArea(5, 20);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
textArea.getInputMap().put(keyStroke, "none");
JScrollPane scrollPane = new JScrollPane( textArea );
getContentPane().add( scrollPane );
JButton cancel = new JButton("Cancel");
cancel.addActionListener( this );
JButton ok = new JButton("Ok");
ok.setPreferredSize( cancel.getPreferredSize() );
ok.addActionListener( this );
JPanel buttons = new JPanel();
buttons.add( ok );
buttons.add( cancel );
getContentPane().add(buttons, BorderLayout.SOUTH);
pack();
getRootPane().setDefaultButton( ok );
}
public void setText(String text)
{
textArea.setText( text );
}
/*
* Save the changed text before hiding the popup
*/
public void actionPerformed(ActionEvent e)
{
if ("Ok".equals( e.getActionCommand() ) )
{
currentText = textArea.getText();
}
textArea.requestFocusInWindow();
setVisible( false );
}
}
private static void createAndShowUI()
{
String[] columnNames = {"Item", "Description"};
Object[][] data =
{
{"Item 1", "Description of Item 1"},
{"Item 2", "Description of Item 2"},
{"Item 3", "Description of Item 3"}
};
JTable table = new JTable(data, columnNames);
table.getColumnModel().getColumn(1).setPreferredWidth(300);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
// Use the popup editor on the second column
TablePopupEditor popupEditor = new TablePopupEditor();
table.getColumnModel().getColumn(1).setCellEditor( popupEditor );
JFrame frame = new JFrame("Popup Editor Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTextField(), BorderLayout.NORTH);
frame.add( scrollPane );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Using this approach you don't continually manipulate the row size. You could even customize the code to make the dialog fit the width of the cell and appear below the cell.
Seems you need to implement your own TableCellEditor, read more in tutorial.
For example like that:
private class CustomEditor extends AbstractCellEditor implements TableCellEditor{
private JTextPane pane = new JTextPane();
private JScrollPane scroll = new JScrollPane(pane);
private int row = -1;
#Override
public Object getCellEditorValue() {
return pane.getText();
}
#Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
if(this.row != -1)
table.setRowHeight(this.row, 20);
this.row = row;
table.setRowHeight(row, 100);
pane.setText(value == null ? "" : value.toString());
return scroll;
}
}
and then set it as column editor: table.getColumn("COMMENTS").setCellEditor(new CustomEditor());

JTable, JComboBox - problems in showing JComboBox in second column

I have written this simple program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class JcomboboxJtableDemo extends JPanel
implements ActionListener {
private DefaultTableModel tableModel;
JTable table = new JTable (tableModel);
private JScrollPane scrollpaneTable = new JScrollPane( table );
private JPanel PaneBottoniTabella = new JPanel( );
public JcomboboxJtableDemo() {
super(new BorderLayout());
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setSelectedIndex(4);
tableModel = CreateTableModel();
tableModel.insertRow( 0, new Object[] {"Header col1", ""} );
tableModel.insertRow( 0, new Object[] {petStrings[0], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[1], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[2], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[3], ""} );
tableModel.setValueAt("Header col2", 0, 1);
DefaultCellEditor editor = new DefaultCellEditor(comboBox);
table.getColumnModel().getColumn(0).setCellEditor(editor);
table.getColumnModel().getColumn(1).setCellEditor(editor);
//Lay out the demo.
add(comboBox, BorderLayout.PAGE_START);
add(table, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
private final DefaultTableModel CreateTableModel () {
DefaultTableModel modello = new DefaultTableModel( new Object[] { "Col1","Col2" }, 0 ) {
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
table.setModel(modello);
return modello;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new JcomboboxJtableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I you try to run it you will see that there is a problem in showing correctly the JComboBox components in the second column, in the first column the are correctly shown and you can see each selected item as set in the code, instead in the second column there are some problems: none on the relative cell.
Could you tell me why? How can I solve the problem?
Thanks
You're using the same JComboBox component for both ColumnModel columns which in turn share the same ComboBoxModel. Any change in the selected item from one column will be reflected in the other column. Create a second combobox
JComboBox comboBox2 = new JComboBox(petStrings);
...
table.getColumnModel().getColumn(1).setCellEditor(editor2);
so that any changes can occur independently in either column.

Spacing JTable header

I know spacing JTable cells are pretty straight forward as shown below;
int gapWidth = 10;
int gapHeight = 5;
table.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
Spacing like this doesn't seems to affect the tables header. Is there a way to space the header with the same dimension?
Easiest way could be to set EmptyBorders to the JTableHeader inside the TableCellRenderer
The code above does my spacing, but the alignment of header and the actual row cell values looks slighly off - as a result of spacing only placed on cells but not the header.
I added a SSCCE (3mins 27seconds inc. uploading here)
from code
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class IntercellSpacingTableHeader {
private JFrame frame = new JFrame("Table Demo");
private String[] columnNames = {"String", "Integer", "Float", "Double"};
private Object[][] data = {
{"aaa", new Integer(12), new Float(12.15), new Double(100.05)},
{"bbb", new Integer(5), new Float(7.154), new Double(6.1555)},
{"CCC", new Integer(92), new Float(0.1135), new Double(3.1455)},
{"ddd", new Integer(12), new Float(31.15), new Double(10.05)},
{"eee", new Integer(5), new Float(5.154), new Double(16.1555)},
{"fff", new Integer(92), new Float(4.1135), new Double(31.1455)}};
private TableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
private JTable table = new JTable(model);
public IntercellSpacingTableHeader() {
int gapWidth = 10;
int gapHeight = 5;
table.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
table.setRowHeight(20);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scroll = new JScrollPane(table);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scroll);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new IntercellSpacingTableHeader();
}
});
}
}

Categories

Resources