Scrolling inside a JTable cell in Swing - java

I have a table each cell contains a image. if the image size is more than row height, I have added JScrollPane. Now when I run the application, scroll is visible in each cell but I'm not able to scroll it.
How can I do it?
Below is the code I'm using to add scroll pane.
Any sample code will be appreciated.
private final JTable table = new JTable(model)
{
#Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column)
{
Component c = super.prepareRenderer(tcr, row, column);
if(isRowSelected(row))
{
c.setForeground(getSelectionForeground());
c.setBackground(getSelectionBackground());
}
else{
c.setForeground(getForeground());
c.setBackground((row%2==0)?evenColor:getBackground());
}
JScrollPane _pane=new JScrollPane(c);
table.setRowHeight(100);
return _pane;
}
};

Right click on your jscrollpane
Properties
HOrizontal scrollbarpolicy = always
Vertical scrollbarpolicy = always
To be able to scroll
Right Click on Jtable
Autocreatecolumnfrommodel =false(deactivaded)

In order to be able to set the focus on the cell (so you can use the inside scroll pane), you can get it through "edit mode":
Create a custom cell editor:
public class MyCustomCellEditor extends AbstractCellEditor implements TableCellEditor{
#Override
public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
JScrollPane your_custom_panel=new JScrollPane();
return your_custom_panel; // your _pane
}
#Override
public Object getCellEditorValue() {
return null;
}
Set it on your table:
table.setDefaultEditor(MyCustomCellValueType.class,new MyCustomCellEditor());
Now you only need to manage how to enter in "edit mode" and you should be able to scroll inside the cell.

Related

Set Jtable cell editable ONLY upon selection

I have a JTable and I added a DefaultTabelModel to it. I created a popup menu that appears when users right click on a cell in the table. One of the items in the menu is "Rename." How can I make the selected cell editable when the Rename item is clicked? I have set up all the elements and the only missing piece here is making THE selected cell editable.
The isCellEditable(row, col) method in the DefaultTableModel is not helpful here because it sets a cell's editability based on its position (i.e. row and column) in the table, not the selection status of a cell.
I suspect that I will need TableCellEditor, but I am not sure how to use it. I would really appreciate a sample code on how to make this happen and/or explanations of how to use TableCellEditor for this purpose. Thank you in advance!!
Relevant pieces of my code:
class DataListTable extends JTable
mouseReleased():
int row = this.getSelectedRow();
popupmenu.show(this, event.getX(), event.getY());
class RenameDataMenuItem
actionPerformed():
//want to get the (row, col) of the selected cell here and make it editable
How can I make the selected cell editable when the Rename item is clicked?
The isCellEditable(...) method will determine if the cell can be edited via the table editor.
You can still change the data in the model by using the setValueAt(..) method of the JTable or the TableModel.
So what you can do is in your rename menu item you can display a JOptionPane to prompt for the new value. Then you just manually save the value using either of the above methods.
Try something along the lines of this:
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
JComponent component = new JTextField();
#Override
public Object getCellEditorValue() {
return ((JTextField)component).getText();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(isSelected) {
((JTextField)component).setText((String)value);
}
return component;
}
}

JAVA - How to change JTable row color after clicking on it?

I 'm a Java beginner.
I create an application with a JTable which is populated with a database.
In my database I have some 'news'. In my JTable I display titles of 'news' and when an user click on a row, it display a popup with the right contents of the news.
But I want to colorize the cell which are 'read' when the user clicked on it.
I use my own TableModel.
I hope I'm clear...
If I need to put some code, tell me what please...
public class JTableTest extends JFrame {
private JTable table;
private int col;
private int rowz;
/**
* Create the frame.
*/
public JTableTest() {
initComponents();
}
private void initComponents() {
/** any other components */
table = new JTable();//create the table
table.setDefaultRenderer(Object.class, new CustomModel());
table.addMouseListener(new CustomListener());
}
public class CustomListener extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent arg0) {
super.mouseClicked(arg0);
//get the clicked cell's row and column
rowz = table.getSelectedRow();
col = table.getSelectedColumn();
// Repaints JTable
table.repaint();
}
}
public class CustomModel extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Color c = Color.WHITE;//define the color you want
if (isSelected && row == rowz & column == col)
c = Color.GREEN;
label.setBackground(c);
return label;
}
}
}
Found this example of how to get the table cell on mouseClick: http://codeprogress.com/java/showSamples.php?index=52&key=JTableValueofSelectedCell
You can use this to get the selected row and column.
Then you need to create a custom TableCellRenderer, possibly as an inner class so that it can use the selected row and column data and set the background of the cell to your highlighted color

Table Cell Editor issue

I'm building a custom table cell editor so it adjusts row height during editing. I have this code, but instead of resizing the cell it seams to resize the whole panel, or the frame. When I try to enter a character in a cell the main frame width narrows down to a couple of pixels.
Can anyone see the problem?
class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
MyTextpane component = new MyTextpane();
MyTable table;
private int row;
private int col;
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int rowIndex, int vColIndex) {
((MyTextpane) component).setText((String) value);
component.addKeyListener(new KeyListener1());
this.table =(MyTable) table;
this.row = rowIndex;
this.col = vColIndex;
return component;
}
public Object getCellEditorValue() {
return ((MyTextpane) component).getText();
}
public class KeyListener1 implements KeyListener {
#Override
public void keyTyped(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
}
#Override
public void keyReleased(KeyEvent ke) {
adjustRowHeight(table, row, col);
}
private java.util.List<java.util.List<Integer>> rowColHeight = new ArrayList<java.util.List<Integer>>();
private void adjustRowHeight(JTable table, int row, int column) {
//The trick to get this to work properly is to set the width of the column to the
//textarea. The reason for this is that getPreferredSize(), without a width tries
//to place all the text in one line. By setting the size with the with of the column,
//getPreferredSize() returnes the proper height which the row should have in
//order to make room for the text.
int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth();
setSize(new Dimension(cWidth, 1000));
int prefH = getPreferredSize().height;
while (rowColHeight.size() <= row) {
rowColHeight.add(new ArrayList<Integer>(column));
}
java.util.List<Integer> colHeights = rowColHeight.get(row);
while (colHeights.size() <= column) {
colHeights.add(0);
}
colHeights.set(column, prefH);
int maxH = prefH;
for (Integer colHeight : colHeights) {
if (colHeight > maxH) {
maxH = colHeight;
}
}
if (table.getRowHeight(row) != maxH) {
table.setRowHeight(row, maxH);
}
}
}
}
have look at
my answer about doLayout(could be fired from CellEditor)
or (more than confortable way to use TextUtils) comment by #kleopatra about getPreferredSize
this could (very) confusing the users,
because I miss JScrollPane, there have to override MaxSize, max size is height & weight for JScrollPane, otherwise part of CellEditor can going outside of screeens bounds .........,
don't do that, put there JScrollPane with JTextComponents, override PreferredSize for CellEditor,
everything are wrong, my view,
create applications modal popup window (based only on JDialog, becasue JWindow doesn't alloved input to the JTextComponent) with JTextComponent, implements there KeyBindings for ESC key, the same for lost Fucus for JDialog, then could be undecorated without any issue
put there Save JButton
output from Save Button reditect to the selected cell, you can't lost focus from application modal inside JTable
contents should be formatted, filtered, modified one JDialog for all cells from JTable
As an alternative to resizing the row while editing, consider TablePopupEditor, which uses JTextArea.

Add Image in JTable without using renderer

I need to add image in Jtable cell without using TableCellRenderer.If i Use the following code means it display the name (string) in that particular cell instead of image.how to do this?.
ImageIcon Icon= new ImageIcon("Blank.gif");
table.setValueAt(Icon,1,0);
using renderer
class FRM_FLXD_ICON_ASSGN extends DefaultTableCellRenderer {
ImageIcon Icon;
public Component getTableCellRendererComponent(
JTable table, Object value, boolean selected, boolean focus,
int row, int col) {
if(selected == true){
Icon=new ImageIcon(getClass().getResource("Pointer.gif"));
}
else{
Icon=new ImageIcon(getClass().getResource("Blank.gif"));
}
this.setIcon(Icon);
return this;
}
}
JTable know Icon/ImageIcon Object, then you can add Icon/ImageIcon directly to the JTable, example

Pass events in custom JTable

Hi I have a class called ColorChooser (in the net.java.dev.colorchooser.ColorChooser package)
This is a custom component used to select colors. What I want is to display a JTable with ColorChoosers in the second column. So I created my own TableCellRenderer and it works:
#SuppressWarnings("serial")
class ColorChooserTableRenderer extends DefaultTableCellRenderer {
public static List<ColorChooser> colors;
public ColorChooserTableRenderer(int rows) {
colors = new ArrayList<ColorChooser>(rows);
for (int i = 0; i<rows ; i ++) {
colors.add(new ColorChooser());
}
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return colors.get(row);
}
}
I register this in my table :
JTable t = new JTable(5,3);
t.getColumn(t.getColumnName(1)).setCellRenderer(new ColorChooserTableRenderer(5));
The display is good. It even displays the tool tip of the ColorChoosers when i hover my mouse over one of them. The problem is that the ColorChoosers do not receive MouseEvents.
Normally when you press and hold the mouse on a ColorChooser, you get a pop up window that you can use to select a color. When in the JTable the ColorChooser component does not receive the mouse event.
Any solutions?
Edit: The question can be easily modified to this:
Can you please give me a small example of a table containing JButtons in the second column that actually work? You know, buttons that can be pressed?
This sounds vaguely familiar as I have been using table cell renderers for other purposes.
My understanding is that TableCellRenderer is only used to render the component; a component does not actually exist at each of the cells.
So you'd probably have to somehow forward mouse events from the JTable itself to the ColorChooser.
edit: p.s., see my question -- also for custom table cell rendering, you only need 1 instance of the component itself for the entire column, if the column is rendered with the same logic. Don't store persistent state in the TableCellRenderer, store it in the TableModel instead, and use that state immediately prior to rendering when you handle the call to getTableCellRendererComponent().
A renderer only paints the component on the screen and does not allow for interaction. What you need is to also implement a TableCellEditor. It is recommend that you inherit the AbstractCellEditor and you'll save some work. Check out the java tutorial for tables.
Example:
public class MyTableCellRenderer implements TableCellRenderer
{
private JButton button = new JButton("Press Me");
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
return button;
}
}
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor
{
private JButton button;
public MyTableCellEditor()
{
button = new JButton("Press Me");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("buttonPressed");
}
});
}
public Object getCellEditorValue() {
return null;
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return button;
}
}

Categories

Resources