gpt4 book ai didi

java - JTable/JScroll 隐藏行和 JTable

转载 作者:行者123 更新时间:2023-12-01 13:58:12 27 4
gpt4 key购买 nike

您好,我是 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

关于java - JTable/JScroll 隐藏行和 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19501131/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com