Enable Jbutton from selection in Jtable and remove the initial focus from the table

Asked

Viewed 900 times

1

I have a window with a JTable, where only an entire row is valid, not just one field. The point is that the window already opens with the first line selected, and I’d like to disable that.

In that very window I have one JButton which is already disabled at the time of its creation, but I would like to activate it as soon as the user selects any line from JTable ...

Summarizing : How I disable automatic line selection JTable at the moment the window opens ? How to activate a button when the user selects any row from it JTable ?

2 answers

2


To avoid automatic selection, you need to change the focus of the table when opening the window.

If your class has inherited from JFrame:

this.requestFocus();

If you have started a window from a variable:

meuFrame.requestFocus();

The requestFocus() will change the focus to your main window, thus preventing the JTable already appears with the first line selected.

To activate the button only when there is a selection, try the below:

this.tabela.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                //altera os botoes para ativados somente se houver linha selecionada
                myButton.setEnabled(!lsm.isSelectionEmpty());
            }
        });

This way the activation of the button depends on whether or not there is a field/row selected in the table.

  • @Danielsantos the solution managed to solve his problem?

  • Sorry it took so long to answer ! It solved half of my haha problems. The section that deals with activating the button worked perfectly. The problem is in the requestFocus()... I put him in the builder’s JFrame, and it wasn’t, then I made that same command in the window controller (which is the class that is "called") that way : gridCliente.requestFocus(); and it didn’t work either !

  • @Danielsantos how did it not work? You are not removing the initial focus from the table?

  • Exactly ! The window keeps selecting the first line of the JTable at the beginning ...

  • Could you show us the code of your window? Post on Pastebin.com

  • http://pastebin.com/zdP39qAA is there, the same command in both classes !

  • @Danielsantos You built this entire screen per line of code only or used some screen builder, such as Windows in Eclipse or Netbeans?

  • I built it all, line by line in the eclipse ...

  • @Danielsantos test with the change I made here http://pastebin.com/T6UKmZzj

  • Not expensive, these objects are of the package awt, right ?

  • 1

    @Danielsantos actually just added a Thinker to change his focus. Look honestly, without testing all the code it is difficult to figure out the real problem, I did several tests here and in all the focus was changed. As a last attempt, try adding this right after you create your table: suaTable.getSelectionModel().clearSelection();

  • It wasn’t expensive either, but I appreciate your effort !

Show 7 more comments

0

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

class SelectTableExample
        extends     JFrame
        implements  ListSelectionListener
{
    // Instance attributes used in this example
   private  JPanel      topPanel;
   private  JTable      table;
   private  JScrollPane scrollPane;
   private  JButton     button;

    // Constructor of main frame
   public SelectTableExample()
   {
    // Set the frame characteristics
      setTitle( "Simple Table Application" );
      setSize( 300, 200 );
      setBackground( Color.gray );

    // Create a panel to hold all other components
      topPanel = new JPanel();
      topPanel.setLayout( new BorderLayout() );
      getContentPane().add( topPanel );

    // Create columns names
      String columnNames[] = { "Column 1", "Column 2", "Column 3" };

    // Create some data
      String dataValues[][] =
         {
         { "12", "234", "67" },
         { "-123", "43", "853" },
         { "93", "89.2", "109" },
         { "279", "9033", "3092" }
         };

    // Create a new table instance
      table = new JTable( dataValues, columnNames );

      // Block cell edition
      table.setModel(
            new DefaultTableModel(dataValues, columnNames) {
               public boolean isCellEditable(int row, int column) { 
                  return false;
               }
            });

        // Handle the listener
      ListSelectionModel selectionModel = table.getSelectionModel();
      selectionModel.addListSelectionListener( this );

    // Add the table to a scrolling pane
      scrollPane = new JScrollPane( table );
      topPanel.add( scrollPane, BorderLayout.CENTER );

      button = new JButton("continuar");
      button.setEnabled(false);
      topPanel.add( button, BorderLayout.SOUTH );
   }

    // Enable button for list selection changes
   public void valueChanged( ListSelectionEvent event )
   {
    // See if this is a valid table selection
      if( event.getSource() == table.getSelectionModel()
                    && event.getFirstIndex() >= 0 )
      {
         button.setEnabled(true);
      }
   }

    // Main entry point for this example
   public static void main( String args[] )
   {
    // Create an instance of the test application
      SelectTableExample mainFrame  = new SelectTableExample();
      mainFrame.setVisible( true );
   }
}
  • Although your answer has the solution, answers like this, playing a random and unexplained code are not good answers. Remember that those who ask may not always know what you need to do.

  • @Diegof I’m so sorry, I didn’t realize it. My intention was to help. I also apologize to Daniel Santos.

  • 1

    Ingrid yes, outside me question this, but often the person who asks may not be able to identify the solution, alias, another person who falls for this answer, may not understand anything. It is important to explain briefly (no need to write an article) how the person solves the solution, think that your answer will now be helping the AP, but in the future, many other people who read on the site :)

  • @Diegof is true, you are absolutely right =) In the next answers I can help I will also make a brief explanation. Thank you for the information!

  • 1

    @Ingridfarabulini I even understood your answer, but it’s like Diego said, a more "inexperienced" person can look for a long time at your answer and not find the solution, but you’re forgiven! It’s the thought that counts !

  • @Danielsantos thank you Daniel for your understanding, my intention really was to help. I will try to improve my answers, I’m sorry.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.