JComboBox as a Cell Renderer in a table column question

N

noident

Greetings!
I am trying to use a JComboBox as a Cell Renderer for a JTable column.
The combo box displays, but I can't open it, with either mouse or
keyboard.
Below is a piece of code that compiles and demonstrates the problem,
creating a 1x1 table.
I'm not really a Java Programmer, I'm a sysadmin, but my users refuse
to use vi so I'm writing a GUI for them. Please help :)

//========== ComboTest.java ==========
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;

class ComboTest extends JFrame
{
static final int windowHeight = 100;
static final int leftWidth = 100;
static final int rightWidth = 100;
static final int windowWidth = leftWidth + rightWidth;

JTable table;

public ComboTest()
{
super("ComboTest");
// Create a one-row, one-column table - very simple
table = new JTable(1,1);

// Set our JComboBox as the renderer
TableColumn column = table.getColumnModel().getColumn(0);
column.setCellRenderer(new ComboRenderer());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {System.exit(0);}
});

pack();

getContentPane().add(new JScrollPane(table));

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = windowWidth + 10;
int h = windowHeight + 10;
setLocation(screenSize.width/3 - w/2, screenSize.height/2 - h/2);
setSize(w, h);
setVisible(true);
}


public static void main(String[] args)
{
new ComboTest();
}
}


class ComboRenderer extends JComboBox implements TableCellRenderer
{

public ComboRenderer()
{
addItem("aaa");
addItem("bbb");
}

public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column)
{
System.err.println("popup: " + (isPopupVisible() ? "visible" :
"invisible"));
return this;
}
}
//========end ComboTest.java============
 
V

Vova Reznik

Changing item means editing a table.
You need to implement custom editor.

Simple fix will be:
after line
column.setCellRenderer(new ComboRenderer());
add line
column.setCellEditor(new DefaultCellEditor(new ComboRenderer()));

and
setSelectedItem(value);
in method getTableCellRendererComponent
 
N

noident

Vova, thank you very much for your reply. That fixes my problem!
I wouldn't have been able to work it out on my own, not with my level
of Java/GUI experience.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,836
Messages
2,569,747
Members
45,545
Latest member
rapter____0

Latest Threads

Top