问题描述
我是Java新手,我正在尝试构建我的第一个应用程序.我阅读了许多教程和演示,并搜索了我的问题的具体答案,但没有找到有帮助的东西.为了测试,我编写了此类,该类将访问数据库与JTable连接起来.现在,我想在一个主应用程序中添加该类,但是因此我必须将现有的类更改为JPanel.我测试了一些更改,但是我的应用程序中再也没有输出JTable了.谁能解释我改变班级的方式?非常感谢!
I'm a Java-Newbie an I'm trying to build my first app. I read lots of tutorials and demos and searched for concrete answers to my question but haven't found something that helps.For testing I wrote this class, that connects an access database with a JTable. Now I want to add this Class in a main app but therefore i have to change my exisiting class to JPanel. I tested some changes, but I don't get an output JTable inside my app anymore. Can anybody explain the way I have to change my class? Thanks a lot!
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中使用我的逻辑.不知何故它仍然行不通.
Now I tried to use camickrs advice and use my logic in a SimpleTableDemo. Somehow it still doesn't work.
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();
}
});
}
}
我刚得到一个空窗口
推荐答案
与框架相关的代码不能成为扩展JPanel的类的一部分.该代码应该是创建GUI的类的main()方法的一部分.
The code relating to the frame can't be part of the class that extend the JPanel. That code should be part of the main() method of your class that creates the GUI.
SimpleTableDemo
显示了一种构造代码的方法,因此重要的逻辑是扩展JPanel的类的一部分.
The SimpleTableDemo
shows one way to structure your code so that the important logic is part of the class extending the JPanel.
如果遇到编译错误,代码结构错误.
Well the structure of your code is wrong if you are getting a compile error.
一种简单的方法是创建一个返回TableModel的方法:
A simple way is to create a method to return the 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()
方法的简单实现.
I gave a simple implementation of the getTableModel()
method.
现在,您需要修改该方法以从数据库中获取数据.因此,您需要:
Now you need to modify that method to get the data from your data base. So you need to:
- 构建SQL
- 获取结果集
- 从ResultSet中获取列名
- 从ResultSet中获取数据行
- 使用列名和数据创建DefaultTableModel
- 返回DefaultTableModel
请注意,如果仅要将每个字段分别存储在TableModel中,则不需要Projekt
类.因此,请首先使用此简单方法.
Note there is no need for the Projekt
class if you are just going to store each field separately in the TableModel. So get this simple approach working first.
一旦获得上述建议,您可能需要考虑将Projekt
对象存储在TableModel中.在这种情况下,您将需要创建一个自定义TableModel.检出行表模型,以创建自定义示例特定对象的TableModel.
Once you get the above suggestion working you may want to consider store the Projekt
object in the TableModel. In this case you will need to create a custom TableModel. Checkout Row Table Model for an example of creating a custom TableModel for a specific object.
TableModel的目的是存储数据.不需要ArrayList.那就是您不想在两个地方存储数据.因此,应将ResultSet中的数据直接加载到TableModel中.
The purpose of the TableModel is to store the data. There should be no need for the ArrayList. That is you don't want to store data in two places. So the data from the ResultSet should be loaded directly to the TableModel.
这篇关于将扩展JFrame的类更改为扩展JPanel的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!