-2

I have been trying to add a table rows' info to JTextField components after clicking with the mouse however it doesn't work. I have used the DefaultTableModel and JTable as shown below.

Here is the code I have been using.

package scrCode;

import java.util.*;
import java.sql.*;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import net.proteanit.sql.DbUtils;

import javax.swing.JTable;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComboBox;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class BorrowABook extends JFrame {

    private JPanel contentPane;
    private JTable table;
    private JButton button;
    private JLabel lblBookId;
    private JTextField textFieldBookID;
    private JLabel lblMemberId;
    private JTextField textFieldMemberID;


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    BorrowABook frame = new BorrowABook();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public BorrowABook() {
        setTitle("Library system");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 971, 594);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        String data [][]=null;
        String column []=null;
        DefaultTableModel model = new DefaultTableModel();
        try {
            //code to receive data from the database 
            Connection con=DB.login();
            PreparedStatement ps=con.prepareStatement("select * from book",ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            ResultSet rs=ps.executeQuery();

            ResultSetMetaData rsmd=rs.getMetaData();
            int cols=rsmd.getColumnCount();
            column=new String[cols];
            for(int i=1;i<=cols;i++){
                column[i-1]=rsmd.getColumnName(i);
            }

            rs.last();
            int rows=rs.getRow();
            rs.beforeFirst();

            data=new String[rows][cols];
            int count=0;
            while(rs.next()){
                for(int i=1;i<=cols;i++){
                    data[count][i-1]=rs.getString(i);
                }
                count++;
            }
            con.close();


        }catch (Exception e){
            System.out.println(e);
        }
        contentPane.setLayout(null);

        table = new JTable(data,column);
        JScrollPane sp = new JScrollPane(table);
        sp.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                int selectedRowIndex = table.getSelectedRow();              
                textFieldBookID.setText(model.getValueAt(selectedRowIndex, 0).toString());
                textFieldMemberID.setText(model.getValueAt(selectedRowIndex, 1).toString());



            }
        });
        sp.setBounds(5, 5, 936, 402);
        contentPane.add(sp);

        button = new JButton("Back");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                UserSection.main(new String [] {});
                dispose();
            }
        });
        button.setForeground(Color.BLACK);
        button.setBackground(SystemColor.info);
        button.setBounds(856, 509, 85, 25);
        contentPane.add(button);

        lblBookId = new JLabel("Book ID:");
        lblBookId.setHorizontalAlignment(SwingConstants.RIGHT);
        lblBookId.setFont(new Font("Sitka Display", Font.BOLD, 22));
        lblBookId.setBounds(28, 420, 141, 29);
        contentPane.add(lblBookId);

        textFieldBookID = new JTextField();
        textFieldBookID.setColumns(10);
        textFieldBookID.setBounds(181, 420, 257, 29);
        contentPane.add(textFieldBookID);

        lblMemberId = new JLabel("Memeber ID:");
        lblMemberId.setHorizontalAlignment(SwingConstants.RIGHT);
        lblMemberId.setFont(new Font("Sitka Display", Font.BOLD, 22));
        lblMemberId.setBounds(28, 469, 141, 29);
        contentPane.add(lblMemberId);

        textFieldMemberID = new JTextField();
        textFieldMemberID.setColumns(10);
        textFieldMemberID.setBounds(181, 469, 257, 29);
        contentPane.add(textFieldMemberID);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    Define "doesn't work", in a **precise** way. – JB Nizet Dec 25 '17 at 13:18
  • 2
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). Hard code date to replace the DB. 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 3) This has nothing to do with the IDE. Don't add the tag. – Andrew Thompson Dec 25 '17 at 13:20
  • First of all, I'd never add a MouseListener to the JScrollPane but rather to the JTable itself. – DontKnowMuchBut Getting Better Dec 25 '17 at 13:23
  • What exacly is the code supposed to do? – titou10 Dec 25 '17 at 13:23
  • Doesn't work as that it is not adding the information to the jTestFields – Naief Jobsen Dec 25 '17 at 13:50

1 Answers1

1

Suggestions:

  • Add your MouseListener to your JTable, not to the JScrollPane. You need notification for when the table has been clicked.
  • You're using the wrong model in your listener as you never fill the DefaultTableModel with data. Be safe and get the model in the listener via table.getModel()
  • No null layouts. While this is not causing your current problem, it forces you to code against the library rather than with it.

For example (database code removed for simplicity, null layout removed as well, and posted a MCVE):

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

public class BorrowABook extends JFrame {

    private JPanel contentPane;
    private JTable table;
    private JButton button;
    private JLabel lblBookId;
    private JTextField textFieldBookID;
    private JLabel lblMemberId;
    private JTextField textFieldMemberID;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    BorrowABook frame = new BorrowABook();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public BorrowABook() {
        setTitle("Library system");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 971, 594);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        String data[][] = {{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}};
        String column[] = {"One", "Two", "Three" };
        DefaultTableModel model = new DefaultTableModel();
        // !! contentPane.setLayout(null);
        contentPane.setLayout(new BorderLayout());

        table = new JTable(data, column);
        JScrollPane sp = new JScrollPane(table);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {

                int selectedRowIndex = table.getSelectedRow();
                textFieldBookID.setText(table.getModel().getValueAt(selectedRowIndex, 0).toString());
                textFieldMemberID.setText(table.getModel().getValueAt(selectedRowIndex, 1).toString());
            }
        });
        //!! sp.setBounds(5, 5, 936, 402);
        contentPane.add(sp);

        JPanel bottomPanel = new JPanel();

        lblBookId = new JLabel("Book ID:");
        lblBookId.setHorizontalAlignment(SwingConstants.RIGHT);
        lblBookId.setFont(new Font("Sitka Display", Font.BOLD, 22));
        bottomPanel.add(lblBookId);

        textFieldBookID = new JTextField();
        textFieldBookID.setColumns(10);
        textFieldBookID.setBounds(181, 420, 257, 29);
        bottomPanel.add(textFieldBookID);

        lblMemberId = new JLabel("Memeber ID:");
        lblMemberId.setHorizontalAlignment(SwingConstants.RIGHT);
        lblMemberId.setFont(new Font("Sitka Display", Font.BOLD, 22));
        lblMemberId.setBounds(28, 469, 141, 29);
        bottomPanel.add(lblMemberId);

        textFieldMemberID = new JTextField();
        textFieldMemberID.setColumns(10);
        textFieldMemberID.setBounds(181, 469, 257, 29);
        bottomPanel.add(textFieldMemberID);

        contentPane.add(bottomPanel, BorderLayout.PAGE_END);
    }
}