Adding a KeyListener to JTable - swing

I have added a KeyListener to JTable; but when I double click on a table cell, the KeyListener stops working.
public class MyKeyListener extends KeyAdapter {
#Override
public void keyTyped(KeyEvent ke) {
char i = ke.getKeyChar();
int ib = ((int) i);
if ((ib == 8)) {
if (jt1.isEditing()) {
jt1.getCellEditor().cancelCellEditing();
}
} else {
// my code to do
}
}
}

Don't use a KeyListener; use a Key Binding. More examples are cited here.
Alternatively, implement a custom table cell editor, as shown in the tutorial.

use MouseListener ...
jt1.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
jt1.getCellEditor().cancelCellEditing();
}
}
});
try the same for adding keyListener... in clickcount..

Related

Index of an invalid object within a list

Is there an equivalent to the getPropertyPath method in the Oval validation framework?
The example code below prints the properties of all nested invalid values of an object. I'd like to also print the index of the invalid object within the list but I'm not sure how this can be done in Oval.
With javax.validation, I can call ConstraintViolation#getPropertyPath but there doesn't seem to be an equivalent in Oval. Am I missing something?
The output is
list[].value: example.ValidationDemo$Child.value cannot be null
list[].value: example.ValidationDemo$Child.value cannot be null
Here's the code:
package example;
import java.util.List;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import net.sf.oval.constraint.AssertValid;
import net.sf.oval.constraint.NotNull;
import net.sf.oval.context.FieldContext;
public class ValidationDemo {
public static void main(String[] args) {
Validator validator = new Validator();
validator.validate(new Parent())
.forEach(ValidationDemo::printViolation);
}
private static void printViolation(ConstraintViolation violation) {
printViolation(violation, "");
}
private static void printViolation(ConstraintViolation violation, String property) {
FieldContext fieldContext = (FieldContext) violation.getContext();
if (!property.isEmpty()) {
property += ".";
}
property += fieldContext.getField().getName();
if (List.class.isAssignableFrom(fieldContext.getField().getType())) {
property += "[]"; // How do I find the index of violation.getInvalidValue() within the list?
}
if (violation.getCauses() == null) {
System.out.format("%s: %s\n", property, violation.getMessage());
} else {
for (ConstraintViolation cause : violation.getCauses()) {
printViolation(cause, property);
}
}
}
public static class Parent {
#AssertValid
public final List<Child> list = List.of(new Child("value"),
new Child(null), new Child(null));
}
public static class Child {
#NotNull
public final String value;
public Child(String value) {
this.value = value;
}
}
}
This is currently not possible. This code part would need to be extended to keep track of the index.
ConstraintViolation.getContextPath() was added in 3.1.0

Cocos2dx RegisterTouchDispatcher

I have started using cocos2d-x in iphone. I have created a class which inherits from cclayer. Now when I try to register it with touch dispatcher it crashes.
In .h file:
class BasePage : public cocos2d::CCLayer
And .m file:
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, INT_MIN + 1, true);
And it crashes in ccobject.m file:
void CCObject::retain(void)
{
CCAssert(m_uReference > 0, "reference count should greater than 0");[here is crash]
++m_uReference;
}
Can you please give me some solution?
bool SampleLayer::init()
{
if (!CCLayer::create())
return false;
setTouchEnabled(true);
return true;
}
void SampleLayer::onEnter()
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
CCNode::onEnter();
}
void SampleLayer::onExit()
{
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
CCNode::onExit();
}
bool SampleLayer::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
return true;
}
void SampleLayer::ccTouchMoved(CCTouch* touch, CCEvent* event)
{}
void SampleLayer::ccTouchEnded(CCTouch* touch, CCEvent* event)
{}
You can write only this line in .m(or .cpp) file
CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this, 0);
In fact you don't need to implement your own RegisterTouchDispatcher.
just call the method below in constructor or onEnter
setTouchEnabled(true);
setTouchMode(kCCTouchesOneByOne);
the base class will do all the mess for you .
besides , you should set touch mode to kCCTouchesAllAtOnce if you wanna enable muti-touch
ps: if you override onEnter in your own class ,remenber to call BaseClass::onEnter() in your own onEnter function ,
like
MyLayer::onEnter()
{
CCLayer::onEnter();
// do my own stuff
}

What is the best way to trigger a combo-box cell editor by typing in a JTable cell?

In other words, I want JTable to drop-down a combo-box whenever user types in a cell that has a JComboBox (or any other JComboBox-based cell-editor) editor associated to it.
Basically, you have to install an appropriate listener on the combo and open the popup explicitly. First candidate for "appropriate" is an AncestorListener, which invokes showing the popup in its ancestorAdded method.
Unfortunately that doesn't seem to be the whole story: works if the table's surrenderFocus property is false. If it is true works only for not-editable combos. After some digging, the reason for the not-working part turns out to be an internal focustransfer (from the combo to the textfield) after the popup is opened by the ancestorListener. In that case, we need a second listener which opens the popup once the editor's editingComponent got the focus permanently.
Multiple listeners routinely step onto each other's feet, so best to not install both permanently but do it on each call to getEditorComp, and let them uninstall themselves once they showed the popup. Below is a working example of how-to do it, just beware: it's not formally tested!
public static class DefaultCellEditorX extends DefaultCellEditor {
private AncestorListener ancestorListener;
private PropertyChangeListener focusPropertyListener;
public DefaultCellEditorX(JComboBox comboBox) {
super(comboBox);
}
/**
* Overridden to install an appriate listener which opens the
* popup when actually starting an edit.
*
* #inherited <p>
*/
#Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
super.getTableCellEditorComponent(table, value, isSelected, row, column);
installListener(table);
return getComponent();
}
/**
* Shows popup.
*/
protected void showPopup() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
getComponent().setPopupVisible(true);
}
});
}
/**
* Dynamically install self-uninstalling listener, depending on JComboBox
* and JTable state.
* #param table
*/
private void installListener(JTable table) {
if (getComponent().isEditable() && table.getSurrendersFocusOnKeystroke()) {
installKeyboardFocusListener();
} else {
installAncestorListener();
}
}
private void installAncestorListener() {
if (ancestorListener == null) {
ancestorListener = new AncestorListener() {
#Override
public void ancestorAdded(AncestorEvent event) {
getComponent().removeAncestorListener(ancestorListener);
showPopup();
}
#Override
public void ancestorRemoved(AncestorEvent event) {
}
#Override
public void ancestorMoved(AncestorEvent event) {
}
};
}
getComponent().addAncestorListener(ancestorListener);
}
private void installKeyboardFocusListener() {
if (focusPropertyListener == null) {
focusPropertyListener = new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
LOG.info("property: " + evt.getPropertyName());
if (focusManager().getPermanentFocusOwner() !=
getComponent().getEditor().getEditorComponent()) return;
focusManager()
.removePropertyChangeListener("permanentFocusOwner", focusPropertyListener);
showPopup();
}
};
}
focusManager().addPropertyChangeListener("permanentFocusOwner", focusPropertyListener);
}
/**
* Convience for less typing.
* #return
*/
protected KeyboardFocusManager focusManager() {
return KeyboardFocusManager.getCurrentKeyboardFocusManager();
}
/**
* Convenience for type cast.
* #inherited <p>
*/
#Override
public JComboBox getComponent() {
return (JComboBox) super.getComponent();
}
}
JTable table = new JTable(data, columns);
table.putClientProperty("terminateEditOnFocusLost", true);
JScrollPane scrollPane = new JScrollPane(table);
final JXComboBox editorComboBox = new JXComboBox(array);
editorComboBox.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
//make sure combobox handles key events
editorComboBox.requestFocusInWindow();
}
public void ancestorMoved(AncestorEvent event) {}
public void ancestorRemoved(AncestorEvent event) {}
});
AutoCompleteDecorator.decorate(editorComboBox);
TableColumn column = table.getColumnModel().getColumn(0);
column.setCellEditor(new ComboBoxCellEditor(editorComboBox));

FEST: Assert that JButton is showing a certain Icon

In my FEST-Test I try to assert, that a JButton has a certain ImageIcon. I didn't find a corresponding method on org.fest.swing.fixture.JButtonFixture
You can write an own ButtonFixture Wrapper which provide a method for that.
IconButtonFixture iconButtonFixture = new IconButtonFixture(buttonFixture.robot, buttonFixture.target);
iconButtonFixture.requireIcon(new ImageIcon( "file:/C:/Users/admin/workspace/Project/bin/image/icon.gif" ));
The IconButtonFixture class:
import static org.fest.swing.edt.GuiActionRunner.execute;
public class IconButtonFixture extends JButtonFixture {
private IconButtonDriver driver;
public IconButtonFixture(Robot robot, JButton target) {
super(robot, target);
driver = new IconButtonDriver(robot);
}
public JButtonFixture requireIcon(Icon icon) {
driver.requireIcon(target, icon);
return this;
}
private class IconButtonDriver extends AbstractButtonDriver {
public IconButtonDriver( Robot robot ) {
super( robot );
}
public void requireIcon(final JButton button, Icon icon) {
Icon buttonIcon = execute(new GuiQuery<Icon>() {
protected Icon executeInEDT() {
return button.getIcon();
}
});
if(!icon.toString().equals( buttonIcon.toString() )) {
Assert.failNotEquals( "The Button has not the expected Icon.", icon, button.getIcon() );
}
}
}
}
what about using target?
Assert.assertNotNull( jButtonFixture.target.getIcon() );

Adding an ActionListener to a JList

I have a JList with an array of strings. Basically it displays a restaurant menu.
right next to the JList i have another JList which is empty. Whenever a user double clicks on a string in the first JList (where the menu is displayed) I want it to show up on the next JList which is right next to it.
how do i do that?
You can try
final JList list = new JList(dataModel);
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
String selectedItem = (String) list.getSelectedValue();
// add selectedItem to your second list.
DefaultListModel model = (DefaultListModel) list2.getModel();
if(model == null)
{
model = new DefaultListModel();
list2.setModel(model);
}
model.addElement(selectedItem);
}
}
};
list.addMouseListener(mouseListener);
You may also want to do it with the Enter key pressed by adding a KeyListener:
jlist.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ENTER){
//do what you want to do
}
}
});
I know that this is not for a double click but some people want to do it with the Enter button instead as I wanted to do.
I have done it already in your code in the other question?
[link] I want to add an action listener from one JList to another JList and how can a JList appear with out any text inside?
The only think you must do there is to put it into the #Bala R's if statement doing the check of number of clicks:
if (e.getClickCount() == 2) {
//your code
}
Actually you would be better to use addElement(selectedItem); method, as in the #Bala R's code instead of
add(orderList.getModel().getSize(), selectedItem); in my code. Both add the item to the end but addElement looks nicer and you do not need to retrieve the model's size.
Oi, Boro.
public void addActionListener(final ActionListener al) {
jList.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
al.actionPerformed(new ActionEvent(e.getSource(), e.getID(), "ENTER"));
}
}
});
jList().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
al.actionPerformed(new ActionEvent(e.getSource(), e.getID(), "ENTER"));
}
}
});
}