您好,我是JAVA的新手,在学习时可以打开GUI。我用ScrollPane和JTable创建了一个JFrame。当我将列增加到2以上时,不会显示第一行以下的数据。

同样,当我的JFram出现时,在我重新调整窗口大小之前,屏幕为空白。

import javax.swing.*;
import javax.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.Border;
import javax.swing.JTable;
import javax.swing.JScrollPane;


public class Swing {

public static void main (String[] args){
//ADD FRAME
    Color LBlue = new Color(83,141,213);//RGB Light BLUE

    JFrame frame = new JFrame("COLA");
    frame.setSize(950,350);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //CLOSE
    frame.getContentPane().setBackground(LBlue); //COLOR
    frame.setLocationRelativeTo(null); //Center JFrame in the middle of screen

//MENU Work
    JMenuBar menubar = new JMenuBar();
    frame.setJMenuBar(menubar);
    JMenu file = new JMenu ("File");
    menubar.add(file);
    JMenuItem exit = new JMenuItem("Exit");
    file.add(exit);

    class exitaction implements ActionListener{ //Action to call menu bar to close
        public void actionPerformed (ActionEvent o){
            System.exit(0);
        }
    }
    exit.addActionListener(new exitaction());
//GRID WORK

    JPanel panel = new JPanel(new GridBagLayout());
    frame.getContentPane().add(panel, BorderLayout.NORTH);
    GridBagConstraints c = new GridBagConstraints();
    panel.setBackground(LBlue); //Set Background of Panel
    panel.setVisible(true);


    String data[][] = {{"HEADER 1", "ABC"}, {"HEADER 1", "HEADER 1"}, {"HEADER     1", "GHI" },     {"HEADER 1", "GHI" }};
    String col[] = {"", "NAMES", "NAMES", };
    JTable table = new JTable(data, col);
    table.setBackground(Color.GRAY);
    table.setFont(new Font("Arial", Font.BOLD, 12));
    table.setVisible(true);

    JScrollPane scroll =new JScrollPane(table);
    c.gridx = 1;
    c.gridy = 1;
    scroll.setPreferredSize(new Dimension( 900,115));
    panel.add(scroll);

    table.revalidate();
    table.validate();
    table.repaint();
    table.setVisible(true);

    scroll.invalidate();
    scroll.validate();
    scroll.repaint();
    table.setVisible(true);

    frame.setVisible(true);

}


感谢您的任何帮助!

最佳答案

您的代码产生一个堆栈跟踪

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2
    at javax.swing.JTable$1.getValueAt(JTable.java:689)
    at javax.swing.JTable.getValueAt(JTable.java:2720)


这很好地说明了问题。这意味着数据列的数量需要与列标识符的数量匹配。添加缺少的数据:

String data[][] = {
    { "NEWDATA", "HEADER 1", "ABC" }, { "NEWDATA", "HEADER 1", "HEADER 1" },
    { "NEWDATA", "HEADER     1", "GHI" }, { "NEWDATA", "HEADER 1", "GHI" },
};


读取:How to Use Tables

10-07 23:27