我有一个2D数组。 2D阵列已包含数据。我需要将它填入JTable并显示它。以下是我的编码,
import arraypackage.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class form extends JFrame implements ActionListener,WindowListener
{
JButton b1; //processing takes place after button click
JTable table;
form()
{
setLayout(null);
b1 = new JButton("Process");
table = new JTable();
table.setBounds(350,200,100,300);
b1.setBounds(450,93,100,30);
add(b1);
b1.addActionListener(this);
setSize(1000,1000);
show();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
data d = new data();
String resultfile[][]=d.dis();
for(int i=1;i<=resultfile.length;i++)
{
for(int j=1;j<=4;j++)
{
rows[i][j]=resultfile[i][j];
}
}
Object[] title = {"A","B","C","D"};
table = new JTable(rows, title);
add(table);
}
}
public void windowActivated(WindowEvent e1)
{
}
public void windowClosed(WindowEvent e2)
{
}
public void windowClosing(WindowEvent e3)
{
dispose();
}
public void windowDeactivated(WindowEvent e4)
{
}
public void windowDeiconified(WindowEvent e5)
{
}
public void windowIconified(WindowEvent e6)
{
}
public void windowOpened(WindowEvent e7)
{
}
public static void main(String s[])
{
form f = new form();
}
}
处理发生但不显示表格。 在上面的编码中,Arraypackage是我自己的包,它包含一个名为data的类,它包含一个名为dis的方法。 dis是一种返回2D String数组的方法。它已成功返回,resultfile包含正确的2D数组值。显示JTable时出现错误,即单击按钮后不显示表格。请在这件事上给予我帮助。
答案 0 :(得分:1)
问题是你是为jtable设置边界,但是你创建了一个新表并添加而没有给出边界。
form() {
setLayout(null); // very bad
b1 = new JButton("Process");
table = new JTable(); //completely unnecessary
table.setBounds(350, 200, 100, 300); // set bounds for table
然后你只需添加全新的表而不指定边界。
public void actionPerformed(ActionEvent e) {
table = new JTable() ; assign new table
add(table); // add //incorrect adding where is the bounds for new table ?
正确的方法/使用布局 [我使用了边框布局。你应该为你使用合适的一个]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class form extends JFrame implements ActionListener, WindowListener {
JButton b1; //processing takes place after button click
JTable table;
form() {
b1 = new JButton("Process");
add(b1, BorderLayout.NORTH);
b1.addActionListener(this);
setSize(1000, 1000);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
data d = new data();
String resultfile[][] = d.dis();
for (int i = 1; i <= resultfile.length; i++) {
for (int j = 1; j <= 4; j++) {
rows[i][j] = resultfile[i][j];
}
}
Object[] title = {"A", "B", "C", "D"};
table = new JTable(rows, title);
add(table);
this.revalidate();
this.repaint();
}
}
public void windowActivated(WindowEvent e1) {
}
public void windowClosed(WindowEvent e2) {
}
public void windowClosing(WindowEvent e3) {
dispose();
}
public void windowDeactivated(WindowEvent e4) {
}
public void windowDeiconified(WindowEvent e5) {
}
public void windowIconified(WindowEvent e6) {
}
public void windowOpened(WindowEvent e7) {
}
public static void main(String s[]) {
form f = new form();
}
}