日期:2014-05-20  浏览次数:20887 次

如在在布局管理器里 并排显示两个JTable
package cn.java.print1;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.*;
import javax.swing.table.TableModel;

public class Test {
static JFrame frame = new JFrame();

//表格中第一行所要显示的内容存放在字符串数组columnNames中
  final static String[] columnNames = {"First Name",
  "Position",
  "Telephone",
  "MonthlyPay",
  "Married"};
  //表格中各行的内容保存在二维数组data中
  final static Object[][] data = {
  {"Wang Yi", "Executive",
  "01068790231", new Integer(5000), new Boolean(false)},
  {"Li Si", "Secretary",
  "01069785321", new Integer(3500), new Boolean(true)},
  {"Li Wu", "Manager",
  "01065498732", new Integer(4500), new Boolean(false)},
  {"Zhao Liu", "Safeguard",
  "01062796879", new Integer(2000), new Boolean(true)},
  {"Chen Qi", "Salesman",
  "01063541298", new Integer(4000), new Boolean(false)}
  };

static JTable table1 = new JTable(data,columnNames);
static JTable table2 = new JTable(data,columnNames);
  static Container c = frame.getContentPane();

public static void addComponentsToPane(Container pane) {
pane.setLayout(new FlowLayout());
pane.add(new JTable((TableModel) table1));
pane.add(new JTable((TableModel) table2));
pane.add(new JButton("Button 3"));
pane.add(new JButton("Long-Named Button 4"));
pane.add(new JButton("5"));
}

public Test(){

frame.setTitle("打印预览");
frame.setSize(1400, 600);
frame.setLocation(100, 100);

frame.pack();
// f.show();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args){
Test test = new Test();
test.addComponentsToPane(c);
}
}

报错:Exception in thread "main" java.lang.ClassCastException: javax.swing.JTable cannot be cast to javax.swing.table.TableModel
at cn.java.print1.Test.addComponentsToPane(Test.java:40)
at cn.java.print1.Test.main(Test.java:65)

其实我本来的目的是想在JFrame里面并排显示两个JTable的表格,但是写了两天也没有实现,现在就想在布局管理器里面写俩个表格,但是实现不了,怎么办呀。。。


请各位大虾帮忙。。。求教,

QQ:1182664505,请指教

------解决方案--------------------
楼主什么情况,被楼主急的……
改起来很简单:
Java code

pane.add(new JTable((TableModel) table1));
pane.add(new JTable((TableModel) table2));

改为:

pane.add(table1);
pane.add(table2);