2

i am new to Stack overflow and looking for some help on a java app i have been working on at college.

My questions is, how do I insert an integer from a Jtextfield (in external class) into a Jtable using a button action listener event.

My code is:

External class Button Code to insert a jtextfield integer to the table

   package banknew;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;



public class CheckingAccount extends BANKNEW
{

final JButton DepositAmount = new JButton("Deposit");  
final JTextField tAmount = new JTextField();

    public void CheckingAccount() {
        String title = "Checking Account";
        JFrame checkingAccount = new JFrame(title);

        checkingAccount.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        checkingAccount.setSize(400, 200);
        checkingAccount.setLocation(checkingAccount.getHeight() / 2, checkingAccount.getWidth() / 2);

        final JLabel error = new JLabel("");
        checkingAccount.add(error, BorderLayout.SOUTH);
        error.setVisible(true);
        error.setLocation(5, 600);


        JMenuItem file1 = new JMenuItem("Checking Account");
        JMenuItem file2 = new JMenuItem("Checking Accounts");
        JMenuItem file3 = new JMenuItem("Checking Accounts");
        JMenuItem file4 = new JMenuItem("Bank Account");
        JMenuItem file5 = new JMenuItem("Close");



        JMenu filemenu = new JMenu("File");
        filemenu.add(file1);
        filemenu.add(file2);
        filemenu.add(file3);
        filemenu.addSeparator();
        filemenu.add(file4);
        filemenu.addSeparator();
        filemenu.add(file5);

        JMenuBar menubar = new JMenuBar();
        menubar.add(filemenu);
        checkingAccount.setJMenuBar(menubar);
        BorderLayout border = new BorderLayout();
        filemenu.setLayout(border);
        checkingAccount.setVisible(true);





        /**
         * ****************************************
         * Create Second JPanel - Buttons & ComboBox .
 *****************************************
         */
        JPanel abuttons1 = new JPanel();
        checkingAccount.add(abuttons1);
        //abuttons1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        abuttons1.setBorder(BorderFactory.createTitledBorder(""));

        JButton Withdraw = new JButton("Withdraw");
        JLabel transBankName1 = new JLabel("Account Name:");
        JLabel transAmount = new JLabel("Amount:");


        final JTextField tBankName1 = new JTextField(20);
        final JComboBox AccountName = new JComboBox();
        AccountName.setEditable(false);
        AccountName.setMaximumSize(new java.awt.Dimension(100, 20));
        AccountName.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        transBankName1.setMaximumSize(new java.awt.Dimension(100, 20));
        transAmount.setMaximumSize(new java.awt.Dimension(100, 20));
        tAmount.setMaximumSize(new java.awt.Dimension(100, 20));
        tBankName1.setMaximumSize(new java.awt.Dimension(00, 20));

        abuttons1.setLayout(new GridLayout(5, 1, 5, 5));
        abuttons1.add(transBankName1);
        abuttons1.add(AccountName);
        abuttons1.add(transAmount);
        abuttons1.add(tAmount);

        abuttons1.add(Withdraw);
        abuttons1.add(DepositAmount);
        abuttons1.setLocation(0, 0);
        abuttons1.setSize(300,200);

         DepositAmount.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (table.getSelectedRow() > -1) {
                    // assuming from your code that you want to set the
                    // textfield's value at the table's selected row
                    try {
                        Integer amount = Integer.parseInt(tAmount.getText());
                        table.getModel().setValueAt(amount, table.getSelectedRow(), 4);
                    } catch (NumberFormatException nfe) {
                        // User did not provide a number.
                        // do nothing? show dialog? you name it!
                    }
                }
            }
        });
    }


    }
  • The External class has a GUI with the Textfield and 'Deposit' Button.
  • The Main Class has a GUI with a 5 column JTable

All i want to be able to do is have an external extended class with a Button, and on button click insert amount from local textfield into the main Jtable as shown in the code with the 'abc' table model.

I have searched google and stack overflow but most posts are related to SQL or database linkage.

If anyone can point me in the right direction, i would be very grateful.

Thanks

EDIT 2: Copy and paste the code and ill try and upload the main class, let me know once you have copied it...

kleopatra
  • 51,061
  • 28
  • 99
  • 211
AlpaxJ1
  • 125
  • 3
  • 12
  • Try to adhere to the Java Coding conventions, in particular the [naming conventions](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367), it makes your code easier to read. – flup Jan 30 '13 at 10:49
  • Putting the selection listener on table is not the way to go, it is how you'd listen to changes that others/the user make on the table. Here, you wish to programmatically make changes to the table. This can be done through the tablemodel `abc`. – flup Jan 30 '13 at 10:54
  • Thanks for your quick reply, is the extends BANKNEW wrong as well? Would i need to implement a TableModel in the class. What would the best way to insert into the table from the external class? – AlpaxJ1 Jan 30 '13 at 11:05
  • You need not do that, you can fetch its model using `table.getModel()`. – flup Jan 30 '13 at 11:06
  • DepositAmount.addActionListener(new ActionListener() { int row; public void actionPerformed(ActionEvent e) { TableModel abc1 = table.getModel(); row = table.getSelectedRow(); abc1.setValueAt(123, row,4); } }); *** How about this, It throws an Error message Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1 and its the abc1.setValueAt command that throws it? – AlpaxJ1 Jan 30 '13 at 11:11

2 Answers2

3

Am a bit unsure of the more global setup of your classes. But if the CheckingAccount is supposed to write to the table, it'll need to be provided a reference to the table in its constructor.

public class CheckingAccount {
    final JButton depositAmount = new JButton("Deposit");  
    final JTextField tAmount = new JTextField();

    //Provide the JTable to the CheckingAccount when you construct it!
    public CheckingAccount(final JTable table) {
        depositAmountButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (table.getSelectedRow() > -1) {
                    // assuming from your code that you want to set the
                    // textfield's value at the table's selected row
                    try {
                        Integer amount = Integer.parseInt(textField.getText());
                        table.getModel().setValueAt(amount, table.getSelectedRow(), 4);
                    } catch (NumberFormatException nfe) {
                        // User did not provide a number.
                        // do nothing? show dialog? you name it!
                    }
                }
            }
        });
    }
}

To learn a bit more about how to use Swing, take a look at the Oracle tutorials

flup
  • 26,937
  • 7
  • 52
  • 74
  • That code is exactly what i want and compiles fine with no error message. The table however in the main class does not insert the actual value, in other words its not updated to the table?? The Table field is stored in the Main class not in the Checking Account Class. Could this be the problem? – AlpaxJ1 Jan 30 '13 at 11:18
  • Have you selected a row before you pressed the button? – flup Jan 30 '13 at 11:32
  • Yes, the row is selected, the code should work, no syntax errors etc. – AlpaxJ1 Jan 30 '13 at 11:34
  • I had accidentally left the `void` keyword in place in front of the constructor. It has to go! (I updated the answer). Have tested it now, works over here. – flup Jan 30 '13 at 11:38
  • I thanks, but it is still not working, ill put up my whole code for you to see, Its messy but if you can work out the problem, ill be quite amazed. Try it out as well... – AlpaxJ1 Jan 30 '13 at 11:41
  • The CheckingAccount needs to know where the table is. So provide it to the constructor: `CheckingAccount ca = new CheckingAccount(table)` I have updated the snippet since I now know the button and textfield are fields of the CheckingAccount class. – flup Jan 30 '13 at 11:56
  • THANK YOU SO MUCH IT WORKED WITH A LITTLE EDITING!!, It inserts the amount without adding it on but thats fine i can edit that, However when i click a button on the main class it reopens the whole bank account -- CheckingAccount.main(null); ----Thanks for your help m8:) ill see if i can fix the other problem now lol:) – AlpaxJ1 Jan 30 '13 at 12:02
  • No worries sorted- added the CheckingAccount.getClass(); instead of the other code, works fine now:) – AlpaxJ1 Jan 30 '13 at 12:04
  • Yes i can do, ::: I added these lines too add the amount rather than insert == Integer amount1 = (Integer) table.getModel().getValueAt(table.getSelectedRow(),4); int sum = amount1 + amount; ** works like a treat, THANKS AGAIN FOR YOUR HELP FLUP, Keep up the good work! – AlpaxJ1 Jan 30 '13 at 12:10
  • There's a lot of info to be found on how to split your classes between a logical model, a presentation layer, and the swing view. See http://martinfowler.com/eaaDev/PresentationModel.html http://www.martinfowler.com/eaaDev/uiArchs.html – flup Jan 30 '13 at 12:21
0

Thank you flup, your code has certainly given us a direction and it is of the most value indeed.

I have made this code to work as components. The key is in the:

final static

enter image description here

Table components and button component

IMPORTANT: I have been successful at adding new rows when add button is clicked. but the adding does not start at 1/0, it started at 2nd row

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class AmendingTable {
    final static JButton        addData         = new JButton("Add");

    static String a;
    static String b;
                                                                //Don't introduce row here otherwise it will add 1 empty row at start
    final static DefaultTableModel model = new DefaultTableModel(null, new String [] {"Products", "Prices" });
    final static JTable table = new JTable(model);

    public static Component table() {
        model.setRowCount(0);
        table.setRowHeight(30);
        return table;
    }
    //ORGINAL
    public static Component addingRowse(final JTable table) {   
        addData.addActionListener(new ActionListener() {
            @Override
                public void actionPerformed(ActionEvent e) {


                            a = String.valueOf(TextFields.jtfProdName.getText());
                            b = String.valueOf(TextFields.jtfProdPrice.getText());

                            String [] row = {a, b};             

                            model.addRow(row);

                }
        });

        return addData;
    }
}

How I called them in my Java Panels. Table called in here

public static Component orderLister() {
    jpOrderLister = new JPanel();

    jpOrderLister.setBounds(5, 105, 450, 300);
    jpOrderLister.setBackground(Color.GREEN);
    jpOrderLister.setLayout(new GridLayout(1,1,0,0)); //Border : Top / Left / Bottom / Right / Colour
    jpOrderLister.setBorder(BorderFactory.createMatteBorder(1, 5, 1, 5, Color.LIGHT_GRAY));

    //
    JScrollPane sPane = new JScrollPane();
    sPane.setPreferredSize(new Dimension(200, 150));
    sPane.getViewport().add(AmendingTable.table);
    sPane.setBackground(Color.white);

    jpOrderLister.add(sPane);

    return jpOrderLister;
}

Button called like this in Java Panel

public static Component buttons() {
    jpButtons = new JPanel();
    jpButtons.setBounds(200, 410, 100, 50);
    jpButtons.setLayout(new GridLayout(1,1,0,0));
    jpButtons.setBackground(Color.GRAY);

    jpButtons.add(AmendingTable.addingRowse(AddingRowsToJTable.table));

    return jpButtons;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Zabi Sidiqkhil
  • 154
  • 1
  • 8
  • Please remove the dropbox link from this and add the code back in. I (or someone else) can help you format it if you get stuck. Formatting does really work here! – halfer Feb 17 '19 at 13:01
  • i know it worked, but no matter how much i say its code {} it goes back to red and wont let me post the answer, the only reason why I posted the file instead – Zabi Sidiqkhil Feb 17 '19 at 22:48
  • I've added the files in the Dropbox text file. – halfer Feb 17 '19 at 22:52