An application i am working on requires the use of a JList where each ListItem is a Label followed by a Button.
What i did is i created a Class having a String member for the Text field and added the Class Objects to the Jlist.
Now for the Button,i implemented a Custom List Cell Renderer which is as :
public renderer()
{
text=new JLabel();
button=new JButton("Track");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Hey");
}
});
}
public Component getListCellRendererComponent(JList list, Object value, int index,boolean isSelected, boolean cellHasFocus)
{
it=(item)list.getModel().getElementAt(index);
text.setText(it.tex);
return this;
}
public void paintComponent(Graphics g)
{
this.add(text);
this.add(button);
this.setVisible(true);
}
public Dimension getpreferredSize(){
Font font=UIManager.getDefaults().getFont("JLabel.Font");
Graphics g=getGraphics();
FontMetrics fm=g.getFontMetrics(font);
return new Dimension(fm.stringWidth(it.tex)+button.getWidth(),fm.getHeight()>button.getWidth()?fm.getHeight():button.getWidth());
}
}
But the button is non responsive when i Click it.What did i miss?
Thanks
Why to go into so much trouble with JList, renderers and editors, when you can simply create a JPanel with box layout, put all the labels and buttons inside and then display this panel in a scroll pane. Code will be short and there wont be any troubles with behaviour.
Generally speaking, putting other components is components such as JTable and JList is almost always more trouble than it is worth.
You should create a custom List Cell Editor too, wich reuses code from ListCellRenderer for looks, but implements action listener on button. The cell renderers are used just to stamp graphic images in list. For using controls in JList you should use cell editors.
@Jakub Zaverka I agree, i already use this, and it work fine. @nikel I recommend you to use a GridBagLayout and a GridBagConstraint to manage your component.
Renderer
is only about to dispaying and formattingJComponets
insideJList
,JComboBox
orJTable
, basically everything is described inJList
andJTable
tutorials, then by usingJList
you can you can onlyJList
you can't returnsJButtons
is clicked or anotherJButton's events
, only by the selection in theJList
, sure by this event you can generating awaiting event to the GUI, but only fromJList
selection, not fromJButton
code
you have got implements own
Editor
, never tried inJList
, because there are missed importand methods in compare withJTable
,replace
JList
withJTable
, createJTable
withoutTableHeader
and with only oneColumn
follows only!!! with code by @camickr,
.
.
EDIT (@Jakub Zaverka)
.
.