views:

98

answers:

4

I have a JFrame in which there are 2 textfields and 1 JButton. Users need to enter some string in the textbox. When user clicks the button in the JFrame then these strings get displayed in a JTable. I am not getting what code shall i write with button clicking. Please help me.

Thanks.

+2  A: 

Look at the Method void addActionListener(ActionListener l). The Javadoc of the specific class often helps too: Java API

boutta
A: 

you need to add actionlistener to the button. try searching on google. for now you can look into this link Jbutton example

harshit
+2  A: 

Your description is a bit too vague for a good answer, but I suspect the step you are missing is adding an action listener to the button. This is described e.g. in Sun's Swing tutorials. I personally don't like their style and prefer anonymous inner classes myself:

myButton.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent e) {
    callMyMethod();
  }
}

Either way works, I prefer the anonymous inner classes since they keep things local and avoid the massive switch method you otherwise get.

Peter Becker
The important thing here "CallMyMethod()". Don't write the logic inside the action listener, but call a method where you define your logic (possibly even in some other controller class).
Juri
I actually had that extra comment written in the original answer but then decided for brevity :-) Maybe I shouldn't have. I tend to keep the contents of the actionPerformed down to roughly one line (one line in >90%, the occasional "get X from event, then call method" creeps in).
Peter Becker
A: 

For learning purposes:

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.AbstractTableModel;

public class NameGUI extends JFrame {
    class NamePair {
        String firstName;
        String lastName;
    }

    class NameModel extends AbstractTableModel {
        List<NamePair> names = new ArrayList<NamePair>();

        @Override
        public String getColumnName(int column) {
            switch (column) {
            case 0:
                return "First name";
            case 1:
                return "Last name";
            }
            return "";
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public int getRowCount() {
            return names.size();
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
            case 0:
                return names.get(rowIndex).firstName;
            case 1:
                return names.get(rowIndex).lastName;
            }
            return null;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }

        @Override
        public void setValueAt(Object value, int rowIndex, int columnIndex) {
            switch (columnIndex) {
            case 0:
                names.get(rowIndex).firstName = String.valueOf(value);
                break;
            case 1:
                names.get(rowIndex).lastName = String.valueOf(value);
                break;
            }
        }

    }

    JTextField firstName;
    JTextField lastName;
    JButton addName;
    JTable nameTable;
    NameModel nameModel;

    public NameGUI() {
        super("My GUI");
        Container c = getContentPane();
        GroupLayout gl = new GroupLayout(c);
        c.setLayout(gl);
        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);
        firstName = new JTextField(20);
        lastName = new JTextField(20);
        addName = new JButton("Add name");
        // MAGIC STARTS *********************
        addName.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onButtonClick();
            }
        });
        // MAGIC ENDS ***********************
        nameModel = new NameModel();
        nameTable = new JTable(nameModel);
        JScrollPane nameTableScroll = new JScrollPane(nameTable);

        gl.setHorizontalGroup(
            gl.createParallelGroup()
            .addGroup(
                gl.createSequentialGroup()
                .addComponent(firstName)
                .addComponent(lastName)
                .addComponent(addName)
            )
            .addComponent(nameTableScroll)
        );
        gl.setVerticalGroup(
            gl.createSequentialGroup()
            .addGroup(
                gl.createParallelGroup(Alignment.BASELINE)
                .addComponent(firstName)
                .addComponent(lastName)
                .addComponent(addName)
            )
            .addComponent(nameTableScroll)
        );

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
    }

    private void onButtonClick() {
        NamePair np = new NamePair();
        np.firstName = firstName.getText();
        np.lastName = lastName.getText();
        nameModel.names.add(np);
        nameModel.fireTableDataChanged();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new NameGUI().setVisible(true);
            }
        });
    }

}
kd304