您好我是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);
}
谢谢你的帮助!
答案 0 :(得分:1)
您的代码会生成堆栈跟踪
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" },
};