我是Java-Newbie,我正在尝试构建我的第一个应用程序。我阅读了很多教程和演示,并搜索了我的问题的具体答案,但没有找到有用的东西。 为了测试,我编写了这个类,它将访问数据库与JTable连接起来。现在我想在主应用程序中添加此类,但因此我必须将我的现有类更改为JPanel。我测试了一些更改,但我的app中没有输出JTable了。任何人都可以解释我改变班级的方式吗?非常感谢!
package de.test.gui;
import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
class Projekt {
private int Platz;
private String ProjektName;
private String StimmZahl;
public Projekt(int platz, String projektName, String stimmZahl) {
this.Platz = platz;
this.ProjektName = projektName;
this.StimmZahl = stimmZahl;
}
public int getPlatz(){
return this.Platz;
}
public String getProjektName() {
return this.ProjektName;
}
public String getStimmZahl(){
return this.StimmZahl;
}
}
public class TabelleProjekt extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public TabelleProjekt() {
super();
setLocationRelativeTo(null);
setSize(500,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:ucanaccess://C:/Projekt/testdb.accdb");
} catch (SQLException ex) {
// TODO Auto-generated catch block
Logger.getLogger(TabelleProjekt.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
static ArrayList<Projekt> getProjekt() {
ArrayList<Projekt> projekt = new ArrayList<Projekt>();
Connection con = getConnection();
Statement st;
ResultSet rs;
Projekt p;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM TESTTABLE");
while(rs.next()){
p = new Projekt(
rs.getInt("KBOE"),
rs.getString("NAME"),
rs.getString("VORNAME")
);
projekt.add(p);
}
} catch (SQLException ex) {
// TODO Auto-generated catch block
Logger.getLogger(TabelleProjekt.class.getName()).log(Level.SEVERE, null, ex);
}
return projekt;
}
public static void main(String[] args) {
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
Object[] columnsName = new Object [3];
columnsName[0] = "Platz";
columnsName[1] = "Projektname";
columnsName[2] = "Stimmzahl";
model.setColumnIdentifiers(columnsName);
Object[] rowData = new Object[3];
for (int i = 0; i < getProjekt().size(); i++) {
rowData[0] = getProjekt().get(i).getPlatz();
rowData[1] = getProjekt().get(i).getProjektName();
rowData[2] = getProjekt().get(i).getStimmZahl();
model.addRow(rowData);
}
table.setModel(model);
System.out.println(getProjekt().size());
TabelleProjekt window = new TabelleProjekt();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JScrollPane pane = new JScrollPane(table);
panel.add(pane,BorderLayout.CENTER);
window.setContentPane(panel);
window.setVisible(true);
}
}
如果我将其更改为
public class TabelleProjekt extends JPanel {
我在这里遇到问题:
public TabelleProjekt() {
super();
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setContentPane(panel);
现在我尝试使用camickrs建议并在SimpleTableDemo中使用我的逻辑。不知怎的,它仍然不起作用。
package de.test.gui;
/*
* SimpleTableDemo.java requires no other files.
*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SimpleTableDemo extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean DEBUG = false;
static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:ucanaccess://C:/Projekt/testdb.accdb");
} catch (SQLException ex) {
// TODO Auto-generated catch block
Logger.getLogger(TabelleProjekt.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
class Projekt {
private int Platz;
private String ProjektName;
private String StimmZahl;
public Projekt(int platz, String projektName, String stimmZahl) {
this.Platz = platz;
this.ProjektName = projektName;
this.StimmZahl = stimmZahl;
}
public int getPlatz() {
return this.Platz;
}
public String getProjektName() {
return this.ProjektName;
}
public String getStimmZahl() {
return this.StimmZahl;
}
ArrayList<Projekt> getProjekt() {
ArrayList<Projekt> projekt = new ArrayList<Projekt>();
Connection con = getConnection();
Statement st;
ResultSet rs;
Projekt p;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM JK_850_All_for_Vest_Future_T");
while (rs.next()) {
p = new Projekt(rs.getInt("KBOE"), rs.getString("NAME"), rs.getString("VORNAME"));
projekt.add(p);
}
} catch (SQLException ex) {
// TODO Auto-generated catch block
Logger.getLogger(TabelleProjekt.class.getName()).log(Level.SEVERE, null, ex);
}
return projekt;
}
public void SimpleTableDemo() {
/*
* super(new GridLayout(1,0));
*/
DefaultTableModel model = new DefaultTableModel();
Object[] columnsName = new Object[3];
columnsName[0] = "Platz";
columnsName[1] = "Projektname";
columnsName[2] = "Stimmzahl";
model.setColumnIdentifiers(columnsName);
Object[] rowData = new Object[3];
for (int i = 0; i < getProjekt().size(); i++) {
rowData[0] = getProjekt().get(i).getPlatz();
rowData[1] = getProjekt().get(i).getProjektName();
rowData[2] = getProjekt().get(i).getStimmZahl();
model.addRow(rowData);
final JTable table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(500, 370));
table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
// Add the scroll pane to this panel.
add(scrollPane);
}
}
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i = 0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j = 0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
frame.setPreferredSize(new Dimension(500, 370));
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
我只是得到一个空窗口
答案 0 :(得分:0)
与框架相关的代码不能成为扩展JPanel的类的一部分。该代码应该是创建GUI的类的main()方法的一部分。
阅读How to Use Tables上的Swing教程中的部分。
SimpleTableDemo
显示了构建代码的一种方法,以便重要的逻辑是扩展JPanel的类的一部分。
编辑:
我有两个从数据库返回列名和数据的对象....说我的对象未定义?!
如果遇到编译错误,代码结构就错了。
一种简单的方法是创建一个返回TableModel的方法:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
SSCCE()
{
JTable table = new JTable( getTableModel() );
JScrollPane scrollPane = new JScrollPane( table );
setLayout( new BorderLayout() );
add(scrollPane, BorderLayout.CENTER);
}
private TableModel getTableModel()
{
DefaultTableModel model = new DefaultTableModel(5, 3);
return model;
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
我给出了getTableModel()
方法的简单实现。
现在您需要修改该方法以从数据库中获取数据。所以你需要:
请注意,如果您要将每个字段分别存储在TableModel中,则不需要Projekt
类。因此,首先要使用这种简单的方法。
一旦您获得上述建议,您可能需要考虑将Projekt
对象存储在TableModel中。在这种情况下,您需要创建一个自定义TableModel。结帐Row Table Model以获取为特定对象创建自定义TableModel的示例。
TableModel的目的是存储数据。不应该有ArrayList。那就是你不想在两个地方存储数据。因此,ResultSet中的数据应直接加载到TableModel。