Hello Everyone
I have an Internal frame in my application which has a JTable populated with values from a database and a JButton which performs some operation when a row is selected from the JTable.When the user does not select a row from the JTable and clicks the JButton, I would like to show a message asking the user to select a row from the table first.I have tried a few things but none seemed to work.Could someone point me in the right direction please.Any help would be greatly appreciated.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 */
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;

public class Intake extends JInternalFrame {
    static int openFrameCount = 1;
    static final int xOffset = 100, yOffset = 30;
    File f=new File("");
    String path = f.getAbsolutePath()+"/src/reports/";
    AnyPlatformAppPDF app = new AnyPlatformAppPDF();
    StockIntakeRevEng srv=new StockIntakeRevEng();
    JTable table;
    Intake intake;

    public Intake() {
      super("Goods In" , 
              true, //resizable
              true, //closable
              true, //maximizable
              true);//iconifiable

     setLocation(xOffset*openFrameCount++, yOffset*openFrameCount++);

        JPanel panel = new JPanel();
        Vector data = new Vector();
        Vector col = new Vector();
        final Object obj="Goods In";
        try {
            //  Connect to  Database

            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/test";
            String userid = "root";
            String password = "killer";

            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, userid, password);

            //  Read data from a table

            String sql = "Select * from transfers where name like '%WS4%'";
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names

            for (int i = 1; i <= columns; i++) {
                col.addElement(md.getColumnName(i));
            }

            //  Get row data

            while (rs.next()) {
                Vector row = new Vector(columns);

                for (int i = 1; i <= columns; i++) {
                    row.addElement(rs.getObject(i));
                }

                data.addElement(row);
            }

            rs.close();
            stmt.close();
            connection.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        DefaultTableModel model = new DefaultTableModel(data, col);
        table = new JTable(model) {

            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false; //Disallow the editing of any cell
            }
        };
        JPanel p=new JPanel(new GridBagLayout());
        final JButton b = new JButton("Receive");          // Create ui
        JScrollPane scroll = new JScrollPane(table);
        JTableHeader header = table.getTableHeader();
        header.setBackground(Color.darkGray);
        b.setPreferredSize(new Dimension(80, 30));
        GridBagConstraints gbc=new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        p.add(b);
        p.add(scroll,gbc);
        getContentPane().add(p);
        setVisible(true);
        setSize(500, 250);
        pack();
        
              
       
        
  // implement table mouse listener
          table.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent e) {
                int[] selRows;
                final Object value;
                TableModel tm = table.getModel();
                selRows = table.getSelectedRows();  
                value=tm.getValueAt(selRows[0], 1);
                 
               if( SwingUtilities.isRightMouseButton(e))
               {
          JOptionPane.showMessageDialog(null, "Right Click is not allowed");
                }  
              if (e.getClickCount() == 2) {
                    
                    app.openFile(path+value+".pdf");

                }
               b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                 if(table.getSelectedRow()<0) // help required to implement this logic!!
                 {
                  JOptionPane.showInternalMessageDialog(rootPane, "Please select a row  from the table first!");
                 }
                 else{
                    try {
                        srv.doParse(obj,value.toString());
                    } catch (IOException ex) {
                        Logger.getLogger(Intake.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (SQLException ex) {
                        Logger.getLogger(Intake.class.getName()).log(Level.SEVERE, null, ex);
                    }
                 }
                 
                
            }
        });

               
            }
        });

  
    }}

Thanks
Kalyan

b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(table.getSelectedRow()<0) // help required to implement this logic!!
{
JOptionPane.showInternalMessageDialog(rootPane, "Please select a row from the table first!");
...

At a quick look what you've got seems OK. What exactly is the problem with the code you posted?

commented: +1 showInternalMessageDialog +11
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(table.getSelectedRow()<0) // help required to implement this logic!!
{
JOptionPane.showInternalMessageDialog(rootPane, "Please select a row from the table first!");
...

At a quick look what you've got seems OK. What exactly is the problem with the code you posted?

Thanks for getting back.The code compiles and runs fine,but clicking the button without selecting a row does not bring up the dialog.Tried quite a few variations but nothing seems to work.

Time for some debugging:
Add a print statement at the start of your actionPerformed to see if its being called.
Print table.getSelectedRow() just before the if, to see if it's what you expected.

from a quick look id say the problem is that you are adding the annonymous internal mouseListenner to JButton "b" INSIDE the JTable's mouse clicked event.
So when you click the button before selecting a row, nothing happens because no listenner have been added to it yet.

^ yes! Well spotted! Yet another demo of why correct indentation is essential.

agreed, what kind of life would we have if everyline started at the left margin! :O

Hi
Thanks for nailing it.That did the trick.Coming to the indentation part I'll keep that in mind for the future.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.