jueves, 15 marzo 2007

Remove JTable's Enter Key behavior

When you press the Enter key while in a JTable, you'll notice how the row selection changes to the next row or to the first row if the former row selected was the last row in the model. You can change this playing with the traversal key policy, but this is quite complicated.

The easy way is to consume the event if the enter key has been pressed. You can accomplish this doing the following:

JTable jMyTable = new JTable();
jMyTable.addKeyListener(new java.awt.event.KeyAdapter() {
     public void keyPressed(java.awt.event.KeyEvent evt) {
         jMyTableKeyPressed(evt);
     }
});
private void jMyTableKeyPressed(java.awt.event.KeyEvent evt) {
     if(evt.getKeyCode() == evt.VK_ENTER){
         evt.consume();
     }
}

It's very important to consume the event during the keyPressed event and not during the other possible keyEvents not doing so will mean that you will consume the event once it's been triggered, so the Enter key will continue advancing one row.

Technorati Tags:

Posted by admin at 2:38 PM in Java

JTable Alternate Row Background

Java tables are great but complex. The good thing about them is that you can do with them whatever you want. Even more, the view is completely separated from the model so you can even play more.

JTables in brief (bad thing) are just a bunch of components put together. So anything you can de to a Component you can do in a JTable.

To make a JTable render each row in a different color, you just have to extend the JTable's prepareRender method.

JTable table = new JTable(){
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
        Component returnComp = super.prepareRenderer(renderer, row, column);
        Color alternateColor = new Color(252,242,206);
        Color whiteColor = Color.WHITE;
        if (!returnComp.getBackground().equals(getSelectionBackground())){
            Color bg = (row % 2 == 0 ? alternateColor : whiteColor);
            returnComp .setBackground(bg);
            bg = null;
        }
        return returnComp;
};

JTableAlteranteRowColor

The above code simply gets the component that was going to be rendered and changes its background so that it fits the user needs. Here we've just set the background using two alternate colors, but there are many more things you can do, just use your imagination. Try using getModel(row, column) to get the values of what the cell contains and make the component behave depending on the values it contains.

Technorati Tags:

Posted by admin at 10:24 AM in Java

Google
 
« March »
SunMonTueWedThuFriSat
    123
45678910
11121314151617
18192021222324
25262728293031