Tripp
Tripp

Reputation: 1

How can I display a JTable on a JFrame

I've spent hours online and I'm afraid I can't quite figure out how to make my JTable show up next to my JButton on a JFrame, if anyone has a simple or comprehensive way to explain why and how to fix the problem Id really appreciate it.

Extensive online research including downloading samples and applying various suggestions; also reached out to my teacher for help but she doesn't have much experience with java.

public class canvas extends JTable{
    static void displayJFrame(){
        //set variables
        int i = 0;
        String[][] strArray = new String[3][i];
        String[] labelArray = new String[3];
        labelArray[0] = "Name: ";
        labelArray[1] = "Subject: ";
        labelArray[2] = "Average: ";
        //create JFrame
        JFrame f = new JFrame("Test Average");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setBackground(Color.WHITE);
        f.setPreferredSize(new Dimension(600, 600));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        //create JButton
        JButton button=new JButton("Enter New Grade");  
        button.setBounds(450,15,140, 40);
        button.addActionListener(e -> average(strArray, i));//gets info from user and adds to strArray
        button.addActionListener(e -> count(i));//increases counter
        f.add(button);
        //create JTable
        JTable j = new JTable(strArray, labelArray);
        JScrollPane scrollPane = new JScrollPane(j);
        j.setBounds(30, 40, 200, 300);
        j.setSize(500, 200); 
        j.setVisible(true);
    }
}

all of my code runs as expected except there is no table, I've also tried so many things that didn't work so this basically where I started so that its not crowded by tons of incorrect stuff

Upvotes: 0

Views: 84

Answers (1)

FredK
FredK

Reputation: 4084

You have several problems. First, by default a JFrame uses a BorderLayout. Using the default add(component) method places that component in the center. Using the same add() method again just replaces the new component at the center.

Second, do not pack or set the frame visible until AFTER you have created the entire GUI.

You would do better to create a JPanel and add the components to that panel, then add the panel to the frame. The default layout manager for JPanel is a FlowLayout.

Upvotes: 1

Related Questions