0

The code I have currently works but only displays the table. I'm trying to add a text field below it but I'm not sure how I would do it. I'm also trying to set a listener on the text field and I'm not too sure how to do that either. Sorry if this is a dumb question, I'm not experienced in Java forms

public class table extends JFrame {
    JTable TestDB;
    public table(){
        setLayout(new FlowLayout());

        String[] columnNames={"First Name","Last Name","Address"};
        Object[][] data={{"Bob","Hazel","HelpMeDr"},{"Yo","Whattup","ezpz"}};

        TestDB=new JTable(data,columnNames);
        TestDB.setPreferredScrollableViewportSize(new Dimension(500,50));
        TestDB.setFillsViewportHeight(true);

        JScrollPane scrollPane=new JScrollPane(TestDB);
        add(scrollPane);
    }
}
Nikolai
  • 37
  • 5

2 Answers2

2

You can add a text field using the next code

textField = new JTextField(20);

//add a listener 
textField.addActionListener(this);

Now for make something happend after interact with the text field you need to make a method

public void actionPerformed(ActionEvent evt) {
    //do this when action performed at the textfield
}

I recommend you to visit the next website for more information https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

P. Dev
  • 107
  • 7
0

fist of all

last thing , in simple words , the FlowLayout is meant to be used only when you are aligning your components in horizontally as if it's a text in lines .

instead use another layout like BoxLayout like this

    public Table() {
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        String[] columnNames = {"First Name", "Last Name", "Address"};
        Object[][] data = {{"Bob", "Hazel", "HelpMeDr"}, {"Yo", "Whattup", "ezpz"}};

        TestDB = new JTable(data, columnNames);
        TestDB.setPreferredScrollableViewportSize(new Dimension(500, 50));
        TestDB.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(TestDB);
        getContentPane().add(scrollPane);
        JTextField textField = new JTextField();
        getContentPane().add(textField);
    }

and one last thing is that text components have not less than 10 types of listener you have to use the one that fit your needs,our friend' answer(which i upvoted ) suggested that you will use ActionListener which it will be invoked every time the user hit 'Enter' in the text field . see How to Use BoxLayout for better understanding of the layout matter and happy coding ^-^.

OverLoadedBurden
  • 606
  • 1
  • 5
  • 14