JButton in JList cell is not clickable - java

In my current swing project I have a JList displaying all active sockets, and each cell has a JButton to close that socket. But the JButton in the cell is not clickable: listener does not get fired.
I have modified the code to minimal as follows.
private class ConnectionListRenderer extends JButton implements ListCellRenderer {
public Component getListCellRendererComponent(JList jlist, Object o, int i, boolean bln, boolean bln1) {
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do something (close the socket in my project)
}
});
return this;
}
}
jList.setCellRenderer(new ConnectionListRenderer());
The list looks fine, but the button on in is not clickable. Am I wrong or JList just does not support JButton in the getting fired?

Here's an example that seems to work, although you don't get the same visual effect of a normal button click. Perhaps someone with better painting skill than me could improve this to simulate the visual pressed button effect.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* A JList of JButtons.
*/
public class JButtonListDemo implements Runnable
{
private JList jlist;
public static void main(String args[])
{
SwingUtilities.invokeLater(new JButtonListDemo());
}
public void run()
{
Object[] items = new ButtonItem[] {
new ButtonItem("Apple"),
new ButtonItem("Banana"),
new ButtonItem("Carrot"),
new ButtonItem("Date"),
new ButtonItem("Eggplant"),
new ButtonItem("Fig"),
new ButtonItem("Guava"),
};
jlist = new JList(items);
jlist.setCellRenderer(new ButtonListRenderer());
jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jlist.setVisibleRowCount(5);
jlist.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent event)
{
clickButtonAt(event.getPoint());
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(jlist));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void clickButtonAt(Point point)
{
int index = jlist.locationToIndex(point);
ButtonItem item = (ButtonItem) jlist.getModel().getElementAt(index);
item.getButton().doClick();
// jlist.repaint(jlist.getCellBounds(index, index));
}
public class ButtonItem
{
private JButton button;
public ButtonItem(String name)
{
this.button = new JButton(name);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println(button.getText() + " was clicked.");
}
});
}
public JButton getButton()
{
return button;
}
#Override
public String toString()
{
return button.getText();
}
}
class ButtonListRenderer extends JButton implements ListCellRenderer
{
public Component getListCellRendererComponent(JList comp, Object value, int index,
boolean isSelected, boolean hasFocus)
{
setEnabled(comp.isEnabled());
setFont(comp.getFont());
setText(value.toString());
if (isSelected)
{
setBackground(comp.getSelectionBackground());
setForeground(comp.getSelectionForeground());
}
else
{
setBackground(comp.getBackground());
setForeground(comp.getForeground());
}
return this;
}
}
}
Alternatively, you could always layout your JButtons vertically on a JPanel (using a new GridLayout(0,1) perhaps) and then put your JPanel in a JScrollPane, thus mocking a JList of JButtons.

Render's are not "real" components, they are "rubber stamps" painted onto the surface of the parent component. They have no "physical" presence.
A JList will have only one instance of the render and this is used to "stamp" each of the items from the list model onto the view.
Out of the box, JList is not editable.

Another solution would be to use two lists next to each other. The first one renders the actual list content, while the second renders buttons, you can add the two lists to a JPanel and layout them with BorderLayout (Borderlayout.CENTER and BorderLayout.EAST). Add this JPanel to the viewport of a JScrollPane.

Related

Why is the focus never lost from my component when I press the JFrame?

I have a problem with the focus listener implemented by CustomTextField class. The focus listener is only called when another Swing component is getting the focus. But If I move the JFrame istelf by dragging it with the mouse, the focusLost() method is never called (in other words, it doesn´t seem that the focus is shifting from CustomTextField to JFrame).
EDIT: The solution of my question is below:
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
public class ScrollFocus extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ScrollFocus();
}
});
}
public ScrollFocus() {
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> values = new Vector<>();
values.add("a");
values.add("b");
values.add("c");
values.add("d");
values.add("e");
JComboBox<String> comboBox = new JComboBox<>(values);
JScrollPane scrollPane = new JScrollPane(comboBox);
this.add(scrollPane, BorderLayout.NORTH);
CustomTextField customTextField = new CustomTextField();
this.add(customTextField, BorderLayout.CENTER);
JButton button = new JButton("press");
final JPopupMenu menu = new JPopupMenu("Menu");
menu.add(new JMenuItem("Test"));
button.setComponentPopupMenu(menu);
this.add(button, BorderLayout.SOUTH);
pack();
setVisible(true);
}
class CustomTextField extends JTextField implements FocusListener {
private CustomPopup customPopup = new CustomPopup();
public CustomTextField() {
this.addFocusListener(this);
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "VK_UP");
this.getActionMap().put("VK_UP", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
setPopupSize();
customPopup.show(CustomTextField.this, CustomTextField.this.getX(), CustomTextField.this.getY() + CustomTextField.this.getHeight());
customPopup.setSelectedIndex(0);
}
});
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "VK_DOWN");
this.getActionMap().put("VK_DOWN", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
setPopupSize();
customPopup.show(CustomTextField.this, CustomTextField.this.getX(), CustomTextField.this.getY() + CustomTextField.this.getHeight());
customPopup.setSelectedIndex(0);
}
});
}
public void setPopupSize() {
customPopup.setPopupSize(new Dimension(this.getWidth(), 110));
}
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
}
class CustomPopup extends JPopupMenu {
String[] values = new String[]{"Value1", "Value2", "Value3", "Value4", "Value5", "Value6", "Value7",
"Value8","Value9", "Value10", "Value11", "Value12", "Value13", "Value14", "Value15", "Value16",};
JList<String> list = new JList<>(values);
JScrollPane scrollPane = new JScrollPane(list);
public int index = 0;
public CustomPopup() {
this.setLayout(new GridLayout(0,1));
this.add(scrollPane);
this.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
if(customPopup.index > 0)
customPopup.setSelectedIndex(--customPopup.index);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){
if(customPopup.index < customPopup.getListSize()-1)
customPopup.setSelectedIndex(++customPopup.index);
}
}
});
this.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
index=0;
}
});
pack();
}
public void setSelectedIndex(int index) {
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
requestFocus();
}
public int getListSize() {
return values.length;
}
}
}
}
//customPopup.setVisible(true);
customPopup.show((JComponent)e.getSource(), 0, 20);
You should be using the show(...) method to show the popup. This must add some listeners to the popup so you will no longer need the FocusListener on the text field.
However, now this is a different problem. The text field loses focus so the Action never get invoked. That would be ok, but the JList never gains focus so it doesn't respond to the up/down keys unless you click on the list box first. I'm not sure what the problem is here.
Maybe you can try to make the popup, scrollpane and list all non-focusable so that focus remains on the text field?
'Focus', which is admittedly a slightly ambiguous term, generally applies to a component, not to an entire window. We think of the "window with focus", but I think what we really mean is "the current window, the one which contains the focus." I would not expect focus_lost to be called if I moved the window (aka JFrame) itself.
Another way to think of it; if I had a text field, clicked in it, and typed a letter or two, I would see those letters in that text field. If I then moved the window slightly and typed another letter or two, I would still expect those letters to appear in that field. It still has focus, and never lost it.

Accessing a JTextField in JTableHeader

I have made a TableHeader renderer that will create a JTextfield under the Label of the header in a JTable.
The problem i got now, i never get focus/access to this JTextfield in the header.
I found out that a TableHeader renderer only draws the component and dont do the rest, like focus and stuff.
I have tryed to make a array of JTextfield that will set on the header, so i can access them on code base. Unlucky that didnt workout, i was wondering if its possible to get access to this JTextField in the header and what is the best way to do this.
Tableheader renderer:
public class TextFieldTableHeaderRenderer extends AbstractCellEditor implements TableCellRenderer {
private MyPanel component;
public TextFieldTableHeaderRenderer(){
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
component = new MyPanel(column);
((MyPanel)component).setLabelText(value.toString());
return component;
}
#Override
public Object getCellEditorValue() {
return ((MyPanel)component).getTextField();
}
MyPanel:
public class MyPanel extends JPanel {
private javax.swing.JLabel label;
private javax.swing.JTextField textField;
public MyPanel(int column) {
super();
setLayout(new java.awt.BorderLayout());
label = new javax.swing.JLabel();
textField = new javax.swing.JTextField();
setBorder(javax.swing.BorderFactory.createEtchedBorder());
label.setHorizontalAlignment(SwingConstants.CENTER);
//textField.setText("Column "+column);
add(textField, java.awt.BorderLayout.PAGE_END);
add(label, java.awt.BorderLayout.CENTER);
}
public void setLabelText( String text ){
label.setText(text);
}
public void setTextFieldText(String text){
getTextField().setText(text);
}
public javax.swing.JTextField getTextField() {
return textField;
}
/**
* #param textField the textField to set
*/
public void setTextField(javax.swing.JTextField textField) {
this.textField = textField;
}
Install on header:
for( int i=0; i < this.getxColumnModel().getColumnCount(); i++){
this.getxColumnModel().getColumn(i, true).setHeaderRenderer( new TextFieldTableHeaderRenderer() );
}
I have try to use the "EditableHeader" example from the i-net, but it makes a new JTextfield when clicking on the header.
I like to see that the user get focus on the JTextfield, enters a text and then it will filter the column.
Filtering wont be a problem, cause i have made that already.
Hopefully im clear to you guys/girls and love to hear you solution
Here's a simple approach for making editable headers:
EDIT: oops - I meant to post this in another thread. I guess I'll keep it here anyway.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class JTableEditableHeaderDemo implements Runnable
{
private JTable table;
private JTableHeader header;
private JPopupMenu renamePopup;
private JTextField text;
private TableColumn column;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new JTableEditableHeaderDemo());
}
public JTableEditableHeaderDemo()
{
table = new JTable(10, 5);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
header = table.getTableHeader();
header.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent event)
{
if (event.getClickCount() == 2)
{
editColumnAt(event.getPoint());
}
}
});
text = new JTextField();
text.setBorder(null);
text.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
renameColumn();
}
});
renamePopup = new JPopupMenu();
renamePopup.setBorder(new MatteBorder(0, 1, 1, 1, Color.DARK_GRAY));
renamePopup.add(text);
}
public void run()
{
JFrame f = new JFrame("Double-click header to edit");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(table));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private void editColumnAt(Point p)
{
int columnIndex = header.columnAtPoint(p);
if (columnIndex != -1)
{
column = header.getColumnModel().getColumn(columnIndex);
Rectangle columnRectangle = header.getHeaderRect(columnIndex);
text.setText(column.getHeaderValue().toString());
renamePopup.setPreferredSize(
new Dimension(columnRectangle.width, columnRectangle.height - 1));
renamePopup.show(header, columnRectangle.x, 0);
text.requestFocusInWindow();
text.selectAll();
}
}
private void renameColumn()
{
column.setHeaderValue(text.getText());
renamePopup.setVisible(false);
header.repaint();
}
}
TableColumn supports setting a TableCellRenderer via setHeaderRenderer(), as shown in this example; it has no provision for setHeaderEditor(), which would be required for editing. Alternatives might include these:
Write a custom JTableHeader.
Add a row of text fields in an adjacent, conformal layout.
Use a particular row in the TableModel, as suggested in FixedRowExample.
Consider a commercial alternative; several are listed here.

JXTitledPanels in a JPanel a user needs to be able to choose one and click a remove button

I have a JPanel with n number of JXTitledPanels. The user should be able to click the JXTitledPanel and hit a remove button to remove it.
My question is how do I know what JXTitlePanel the user has selected.
here is a screen from my program basically I want a user to click "Hospitals", click remove and the Hospitals Table will disappear.
I'd probably add a "remove" control into the right decoration position. This way you could pass a reference to the control of the JXTiltedPane
titledPane.addRightDecoration(new MyRemoveControl(titkedPane));
Or such
#madprogrammer probably has the simplest answer, but if you don't want to change the look of the application, you could combine your button's actionListener with a mouseListener for the panels.
The mouseListener portion saves the last panel clicked, and the actionListener just removes the panel that was registered by the mouseListener.
Here's a quick sample I cooked up - it doesn't use JXTitledPane but that shouldn't matter because they're all in the same hierarchy.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TempProject extends JFrame{
public TempProject(){
Box mainContent = Box.createVerticalBox();
//Create Button
JButton removePanel = new JButton("RemovePanel");
RemoveListener listener = new RemoveListener(mainContent);
removePanel.addActionListener(listener);
mainContent.add(removePanel);
//Create Panels
mainContent.add(getPanel(Color.red, listener));
mainContent.add(getPanel(Color.orange, listener));
mainContent.add(getPanel(Color.pink, listener));
mainContent.add(getPanel(Color.magenta, listener));
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setContentPane(mainContent);
pack();
setVisible(true);
}
public JPanel getPanel(Color color, RemoveListener l){
JPanel result = new JPanel();
result.setBackground(color);
result.add(new JLabel(color.toString()));
result.addMouseListener(l);
return result;
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new TempProject();
}
});
}
public static class RemoveListener extends MouseAdapter implements ActionListener{
Component lastSelectedComponent = null;
Container master; //The panel containing the ones being listened to
public RemoveListener(Container master){
this.master = master;
}
#Override
public void mouseClicked(MouseEvent arg0) {
lastSelectedComponent = (Component)arg0.getSource();
}
#Override
public void actionPerformed(ActionEvent e) {
if(lastSelectedComponent != null){
master.remove(lastSelectedComponent);
master.repaint();
}
}
}
}

java delete a component

Current I can add a bunch of customed component objects to the JPanel by pressing "add" JButton. I also got a "delete" JButton which I wish to do the opposite of "add".
My intention is that I can select a component with a mouse and click the delete button and pressto!, the component is gone.
I hook a MouseListener to the panel, and use MouseEvent, e.getComponent() to get w/e current component the mouse clicks on. So if it returns a custom component then a variable "private myComponent current" (already set to null) will point to that component. Then I can just click on "delete" button to remove it. An actionListener already added in "delete" button and in the body it calls this.remove(current) (if current is not null).
However, this doesn't work as I can't remove a component! Any pointer?
If there is an elegant way to managing add/remove components please suggest!
public class MainDisplayPanel extends JPanel implements ActionListener, MouseListener{
private JButton newClassButton;
private JButton deleteButton;
private Resizable current;
private Resizable resizer;
public MainDisplayPanel(LayoutManager layout) {
super(layout);
newClassButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addResizer();
}
});
deleteButton = new JButton("Delete");
deleteButton.addActionListener(this);
this.addMouseListener(this);
this.add(newClassButton);
this.add(deleteButton);
}
public void addResizer() {
//JPanel panel = new JPanel();
//panel.setBackground(Color.white);
resizer = new Resizable( new ClassBox());
this.add(resizer);
this.revalidate();
this.repaint();
}
public void actionPerformed(ActionEvent e) {
if(current!=null)
{
this.remove(current);
this.revalidate();
this.repaint();
}
}
public void mouseClicked(MouseEvent e) {
System.out.println(e);
Component component = e.getComponent();
if(component instanceof Resizable)
current= (Resizable) e.getComponent();
}
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.add(new MainDisplayPanel(null));
jframe.setSize(new Dimension(600,400));
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Doh!
Now, in the addResizer() method. Every time I press the add button to add a new Resizable object, what'd happen to the previously added objects? I'm certain that they become null because resizer variable no longer referring to it them??? Even if this is the case, they are still displayed on the panel...And if I pressed delete only the newly added Resizable object gets removed. So am I on the right track here?
Edit: to sum up my problem, I hooked the MouseListener to wrong object. It should be Resizable object instead of the panel. Therefore, variable current is always null.
Your problem is your MouseLisetener. You are listening to the MainDisplayPanel, and so when you click on the JPanel, the MouseEvent#getComponent method returned by, e, in your mousePressed method will return the MainDisplayPanel instance since that is what is being listened to, not the Resizable instance that is under the mouse.
Solutions include:
creating one MouseListener object and adding this same object to each Resizable as a MouseListener for the Resizable, or
using your current set up, but hold your Resizable's in an ArrayList and then iterating through the array list in the mousePressed method to see if any Resizable has been clicked by using the componentAt(...) method.
Note that I had to create my own SSCCE to solve this. Again in the future, please do us all a favor and do this for us as it really is in your and our best interest, and shows that you respect our time and our help.
Edit 1
My SSCCE:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class MainDisplayPanel extends JPanel {
private static final int RESIZABLE_COUNT = 40;
private JButton deleteButton;
private Resizable current;
private Resizable resizer;
private List<Resizable> resizableList = new ArrayList<Resizable>();
public MainDisplayPanel(LayoutManager layout) {
super(layout);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
deleteButtonActionPerformed(e);
}
});
this.addMouseListener(new MyMouseAdapter());
this.add(deleteButton);
for (int i = 0; i < RESIZABLE_COUNT; i++) {
addResizer();
}
}
private void deleteButtonActionPerformed(ActionEvent e) {
if (current != null) {
this.remove(current);
resizableList.remove(current);
current = null;
this.revalidate();
this.repaint();
}
}
public void addResizer() {
resizer = new Resizable();
this.add(resizer);
resizableList.add(resizer);
this.revalidate();
this.repaint();
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
current = null;
Component c = getComponentAt(e.getPoint());
for (Resizable resizable : resizableList) {
if (resizable == c) {
current = resizable;
resizable.setFill(true);
} else {
resizable.setFill(false);
}
}
}
}
public static void main(String[] args) {
JFrame jframe = new JFrame();
// !! jframe.add(new MainDisplayPanel(null));
jframe.add(new MainDisplayPanel(new FlowLayout()));
jframe.setSize(new Dimension(600, 400));
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
#SuppressWarnings("serial")
class Resizable extends JPanel {
private static final int RESIZE_WIDTH = 50;
private static final int RESIZE_HEIGHT = 40;
private static final int THICKNESS = 5;
private static final Color FILL_COLOR = Color.pink;
public Resizable() {
Random rand = new Random();
// different color border so we can see that it was the clicked one that was deleted.
Color color = new Color(
rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255));
setBorder(BorderFactory.createLineBorder(color, THICKNESS));
}
#Override // so we can see it
public Dimension getPreferredSize() {
return new Dimension(RESIZE_WIDTH, RESIZE_HEIGHT);
}
public void setFill(boolean fill) {
Color fillColor = fill ? FILL_COLOR : null;
setBackground(fillColor);
repaint();
}
}
it very crazy idea, but everything is possible, but
1) in case that you Layed JComponent by using some of LayoutManager you can remove JComponents from Container, and thenafter you must/have to call revalidate() + repaint(), but this actions has side effect -> ReLayout Container and then Container's contents could be look very ***
2) in case that you layed Container with AbsoluteLayout, that should be maybe nicest but question is what with emtpy space inside Container
there is very easy way how to do it, you need to add JPopupMenu to the Container,
on RightMouseClick you have to finding JComponent under the MouseCursor
then call Container#remove(myComponent), thenafter you have to call revalidate() + repaint() for refresh GUI
or is same for me
call myComponent.setVisible(false), no re-layout, no revalidate + repaint, JComponent waiting on same place for (eventually) reusing
excelent thread about how to LayoutManagers add/remove JComponents + revalidate + repaint
I believe the problem is you need to force Swing to layout the components again after removing one. After you remove(current), call revalidate().

Losing first character in JTable panel based cell editor

I have a cell editor that contains a little button and then a textfield that can be used to edit the value inline
I use setSurrendersFocusOnKeystroke(true) and a focus listener in order to allow a user to start editing immediately from the keyboard, but the trouble is the fisrt key pressed seems to get consumed rather being added to the text field, how can I prevent this ?
Full self contained example below
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class PanelTableEditorTest extends JFrame {
private JTable table;
public PanelTableEditorTest() {
this.setLayout(new BorderLayout());
table = new JTable(10, 10);
table.getSelectionModel().setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(true);
table.setDefaultEditor(Object.class, new SimpleMultiRowCellEditor());
table.setSurrendersFocusOnKeystroke(true);
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0),
"none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER, 0),
"startEditing");
this.add(table.getTableHeader(), BorderLayout.NORTH);
this.add(table, BorderLayout.CENTER);
pack();
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new PanelTableEditorTest();
}
});
}
public class SimpleMultiRowCellEditor extends DefaultCellEditor {
final JPanel panel;
private final JButton rowCount;
public SimpleMultiRowCellEditor() {
super(new JTextField());
this.setClickCountToStart(1);
rowCount = new JButton();
rowCount.setVisible(true);
panel = new JPanel();
panel.setOpaque(false);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(rowCount);
panel.add(editorComponent);
panel.addFocusListener(new PanelFocusListener());
}
public Component getTableCellEditorComponent(
final JTable table,final Object val, final boolean isSelected,
final int row, final int column) {
rowCount.setText("1");
delegate.setValue(val);
editorComponent.requestFocusInWindow();
return panel;
}
class PanelFocusListener implements FocusListener {
public void focusGained(FocusEvent e) {
editorComponent.requestFocusInWindow();
}
public void focusLost(FocusEvent e) {
}
}
}
}
So I have found a solution, thanks to this article http://jroller.com/santhosh/entry/keyboard_handling_in_tablecelleditor , and some useful discussion abou this and how it can be applied to other components at http://forums.java.net/jive/thread.jspa?messageID=482236&#482236
Don't fully understand the solution this whole area seems to be rather a minefield
I've also added this solution Get correct editing behaviour in JTable using java DefaultCellEditor into this so that when you start editing a field using the keyboard the existing value is replaced, but not when you double click o the field.
My one confusion is that I'm not receiving a Key Event as I'd expect but just null so I've had to account for that.
Ive gone back from using setSurrenderKeystrokes(true) because this causes problems with others editors such as the straightforward textfieldeditor
import javax.swing.*;
import javax.swing.text.Caret;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.EventObject;
public class PanelTableEditorTest extends JFrame
{
private JTable table;
public PanelTableEditorTest()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
}
this.setLayout(new BorderLayout());
table = new JTable(4, 4);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(true);
table.setSurrendersFocusOnKeystroke(false);
table.setDefaultEditor(Object.class,new SimpleMultiRowCellEditor());
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(java.awt.event.
KeyEvent.VK_F2, 0), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(java.awt.event.
KeyEvent.VK_ENTER, 0), "startEditing");
this.add(table.getTableHeader(), BorderLayout.NORTH);
this.add(table, BorderLayout.CENTER);
pack();
setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new PanelTableEditorTest();
}
});
}
public class SimpleMultiRowCellEditor extends DefaultCellEditor
{
private EventObject event;
final JPanel panel;
private final JButton rowCount;
public SimpleMultiRowCellEditor()
{
super(new JTextField());
this.setClickCountToStart(1);
rowCount = new JButton();
rowCount.setVisible(true);
panel = new TableEditorPanel();
panel.setRequestFocusEnabled(true);
panel.setOpaque(false);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(rowCount);
panel.add(editorComponent);
}
public boolean isCellEditable(EventObject anEvent)
{
event=anEvent;
return super.isCellEditable(anEvent);
}
public Component getTableCellEditorComponent(final JTable table, final Object val, final boolean isSelected, final int row, final int column)
{
rowCount.setText("1");
delegate.setValue(val);
if(event instanceof KeyEvent || event==null)
{
final Caret caret = ((JTextField)editorComponent).getCaret();
caret.setDot(0);
((JTextField)editorComponent).setText("");
}
return panel;
}
class TableEditorPanel extends JPanel
{
public void addNotify(){
super.addNotify();
editorComponent.requestFocus();
}
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed){
InputMap map = editorComponent.getInputMap(condition);
ActionMap am = editorComponent.getActionMap();
if(map!=null && am!=null && isEnabled()){
Object binding = map.get(ks);
Action action = (binding==null) ? null : am.get(binding);
if(action!=null){
return SwingUtilities.notifyAction(action, ks, e, editorComponent,
e.getModifiers());
}
}
return false;
}
}
}
}
add a
rowCount.setFocusable(false);
in the SimpleMultiRowCellEditor constructor, to prevent the button to retrieve focus, so that the JTextfield is the only how can have the focus on cell edition

Categories

Resources