简体   繁体   English

如何在JFrame上显示JTable

[英]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. 我已经花了几个小时上网,如果有人可以用简单或全面的方法来解释为什么以及如何解决此问题,恐怕我还不太清楚如何使我的JTable显示在JFrame上的JButton旁边我真的很感激。

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. 还向我的老师寻求帮助,但她对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 除了没有表外,我所有的代码都按预期运行,我也尝试了很多不起作用的事情,因此基本上是从这里开始的,这样就不会被大量不正确的东西挤满

You have several problems. 你有几个问题。 First, by default a JFrame uses a BorderLayout. 首先,默认情况下,JFrame使用BorderLayout。 Using the default add(component) method places that component in the center. 使用默认的add(component)方法可将该组件置于中心。 Using the same add() method again just replaces the new component at the center. 再次使用相同的add()方法仅替换位于中心的新组件。

Second, do not pack or set the frame visible until AFTER you have created the entire GUI. 其次,在创建完整个GUI之后,不要打包或设置框架可见。

You would do better to create a JPanel and add the components to that panel, then add the panel to the frame. 您最好创建一个JPanel并将组件添加到该面板,然后将该面板添加到框架。 The default layout manager for JPanel is a FlowLayout. JPanel的默认布局管理器是FlowLayout。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM