简体   繁体   English

将扩展JFrame的类更改为扩展JPanel的类

[英]Change class that extends JFrame to class that extends JPanel

I'm a Java-Newbie an I'm trying to build my first app. 我是Java新手,我正在尝试构建我的第一个应用程序。 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. 为了测试,我编写了此类,该类将访问数据库与JTable连接起来。 Now I want to add this Class in a main app but therefore i have to change my exisiting class to JPanel. 现在,我想在一个主应用程序中添加该类,但是因此我必须将现有的类更改为JPanel。 I tested some changes, but I don't get an output JTable inside my app anymore. 我测试了一些更改,但是我的应用程序中再也没有输出JTable了。 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);


    } 


}

If I change it to 如果我将其更改为

public class TabelleProjekt extends JPanel {

I get problems here: 我在这里遇到问题:

public TabelleProjekt() {
    super();
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

window.setContentPane(panel);

Now I tried to use camickrs advice and use my logic in a SimpleTableDemo. 现在,我尝试使用camickrs建议,并在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();
            }
        });
    }
}

I just get an empty window 我只是一个空的窗口

The code relating to the frame can't be part of the class that extend the JPanel. 与框架有关的代码不能成为扩展JPanel的类的一部分。 That code should be part of the main() method of your class that creates the GUI. 该代码应该是创建GUI的类的main()方法的一部分。

Read the section from the Swing tutorial on How to Use Tables . 阅读Swing教程中有关如何使用表的部分

The SimpleTableDemo shows one way to structure your code so that the important logic is part of the class extending the JPanel. SimpleTableDemo显示了一种构造代码的方法,因此重要的逻辑是扩展JPanel的类的一部分。

Edit: 编辑:

I have two objects that return columnnames and data from the database.... says my objects are undefined?! 我有两个对象,它们从数据库返回列名和数据。...说我的对象未定义?!

Well the structure of your code is wrong if you are getting a compile error. 如果您遇到编译错误,那么代码的结构是错误的。

A simple way is to create a method to return the TableModel: 一种简单的方法是创建一个返回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();
            }
        });
*/
    }
}

I gave a simple implementation of the getTableModel() method. 我给出了getTableModel()方法的简单实现。

Now you need to modify that method to get the data from your data base. 现在,您需要修改该方法以从数据库中获取数据。 So you need to: 因此,您需要:

  1. build the SQL 建立SQL
  2. get the ResultSet 获取结果集
  3. get the column names from the ResultSet 从ResultSet获取列名
  4. get the rows of data from the ResultSet 从ResultSet获取数据行
  5. create the DefaultTableModel using the column names and data 使用列名称和数据创建DefaultTableModel
  6. return the DefaultTableModel 返回DefaultTableModel

Note there is no need for the Projekt class if you are just going to store each field separately in the TableModel. 请注意,如果仅要将每个字段分别存储在TableModel中,则不需要Projekt类。 So get this simple approach working first. 因此,请首先使用此简单方法。

Once you get the above suggestion working you may want to consider store the Projekt object in the TableModel. 获得上述建议后,您可能需要考虑将Projekt对象存储在TableModel中。 In this case you will need to create a custom TableModel. 在这种情况下,您将需要创建一个自定义TableModel。 Checkout Row Table Model for an example of creating a custom TableModel for a specific object. 出行表模型 ,以了解为特定对象创建自定义TableModel的示例。

The purpose of the TableModel is to store the data. TableModel的目的是存储数据。 There should be no need for the ArrayList. 不需要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. 因此,应将ResultSet中的数据直接加载到TableModel中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM