没有列名的 DefaultTableModel

发布于 2024-12-13 04:24:19 字数 5963 浏览 0 评论 0原文

此类与我的数据库通信,检索数据并将它们投影到 JTable。我使用了 DefaultTableModel,但列名称不会出现。我在另一个类中实例化此类,在其中通过 getTable( ) 检索包含数据的表。

package jtable;

import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;

public class ControlDatabase
{  
   private JTable table;
   private Statement stmt;
   private DefaultTableModel model;
   private String all = "SELECT * FROM Players ORDER BY id ASC";


public ControlDatabase( ) 
{
        String dbUsername = "root";
        String dbPassword = "*****";
        String dbHost = "localhost";
        String dbPort = "3306";
        String dbName = "oop_project_database";
        String url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName; 
    try {
        Connection con = DriverManager.getConnection(url, dbUsername, dbPassword);

        model = new DefaultTableModel();
        model.addColumn("Id");
        model.addColumn("Onoma");
        model.addColumn("Epwnimo");
        model.addColumn("Age");
        model.addColumn("Nickname");
        table = new JTable(model); 

        stmt = con.createStatement();
        updateStatement( all );

    } catch (SQLException ex) {
        ex.printStackTrace(System.out);
    }

}

public void addStatement(String name,String surname,Integer age,String nickname )
{
  String query = "INSERT INTO Players (name,surname,age,nickname) VALUES ('"
                + name +
                "','"
                + surname +
                "',"
                + age +
                ",'"
               + nickname +
               "')";
  try {
        int x = stmt.executeUpdate( query );
        if (x > 0) {
            lastStatement(all);
               // updateStatement(all , true );
        }
      } catch (SQLException e)  {
        e.printStackTrace();
    }
}

public Boolean deleteStatement(String id , int row )
{
  String query = "DELETE FROM Players WHERE id = " + id ;
  try {
        int x = stmt.executeUpdate( query );
        if (x > 0) {
            model.removeRow(row);
            return true;
        }
        return false;

      } catch (SQLException e)  {
        e.printStackTrace();
        return false;
    }
}

public void updateStatement(String query , Boolean flag )
{
    try {
      ResultSet rs = stmt.executeQuery(  query );
        while (rs.next()) {
            int currentId = rs.getInt("id");
            String currentName = rs.getString("name");
            String currentSurname = rs.getString("surname");
            int currentAge = rs.getInt("age");
            String currentNick = rs.getString("nickname");

            Object[] currentRow = { currentId ,currentName, currentSurname, currentAge, currentNick };
            model.addRow(currentRow);
        }
    } catch (SQLException ex) {
        ex.printStackTrace(System.out);
    }
}

public void updateStatement(String query) {
    updateStatement(query , false );
}

public void lastStatement(String query )
{
    try {
      ResultSet rs = stmt.executeQuery(  query );

            rs.last();
            int currentId = rs.getInt("id");
            String currentName = rs.getString("name");
            String currentSurname = rs.getString("surname");
            int currentAge = rs.getInt("age");
            String currentNick = rs.getString("nickname");
            Object[] currentRow = { currentId ,currentName, currentSurname, currentAge, currentNick };
            model.addRow(currentRow);
    } catch (SQLException ex) {
        ex.printStackTrace(System.out);
    }
}

public JTable getTable( ) {
    return table;
}

}  

主要班级

package jtable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class MainD extends JFrame{

   private JPanel p;
   //private JPanel pa;
   private JScrollPane pa; //<-- change
   private JSplitPane splitPane;
   private JButton b,ba;
   private JLabel ln,ls,la,lc;
   private JTextField txs,txn,txa,txc;
   private ControlDatabase data;
   private JTable table;

   public MainD()
   {
     super("Split");
p = new JPanel(new GridLayout(5,2));
//pa = new JPanel(new GridLayout(1,1));
pa = new JScrollPane( ); //<--
ln = new JLabel("Name");
txn = new JTextField();
ls = new JLabel("Surname");
txs = new JTextField();
la = new JLabel("Age");
txa = new JTextField();
ba = new JButton("Add");
lc = new JLabel("Nickname");
txc = new JTextField();
ba.addActionListener(new ActionListener() { //Add
    public void actionPerformed(ActionEvent e){
        String name = txn.getText();
        String surname = txs.getText();
        String sage = txa.getText();

        String nickname = txc.getText();
        if (!( name.isEmpty() || surname.isEmpty() || nickname.isEmpty() || sage.isEmpty() )) {
            try {
                Integer age = Integer.parseInt( sage );
                data.addStatement(name,surname,age,nickname);
                txn.setText("");
                txs.setText("");
                txa.setText("");
                txc.setText("");
            }catch(NumberFormatException ex){
                System.out.println("Age must be an Integer");
            }

        }
        else{
            System.out.println("Empty Fields");
        }
    }
}
);
b = new JButton("Remove");
data = new ControlDatabase();
table = data.getTable();
pa.add(table);
b.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e){
        int row = table.getSelectedRow();
        String value = String.valueOf( table.getValueAt( row ,0 ) );
        data.deleteStatement( value , row );
    }
}
);
p.add(ln);
p.add(txn);
p.add(ls);
p.add(txs);
p.add(la);
p.add(txa);
p.add(lc);
p.add(txc);
p.add(ba);
p.add(b);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p, pa);
splitPane.setDividerLocation(280);
add(splitPane);
setBounds(200,200,800,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
   }

public static void main(String[] args) {
       new MainD();
}

}

This class communicates with my database retrieves data and project them to a JTable.I used the DefaultTableModel but the column names won't appear.I instantiate this class in another class where i retrieve the table with the data through getTable( ).

package jtable;

import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;

public class ControlDatabase
{  
   private JTable table;
   private Statement stmt;
   private DefaultTableModel model;
   private String all = "SELECT * FROM Players ORDER BY id ASC";


public ControlDatabase( ) 
{
        String dbUsername = "root";
        String dbPassword = "*****";
        String dbHost = "localhost";
        String dbPort = "3306";
        String dbName = "oop_project_database";
        String url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName; 
    try {
        Connection con = DriverManager.getConnection(url, dbUsername, dbPassword);

        model = new DefaultTableModel();
        model.addColumn("Id");
        model.addColumn("Onoma");
        model.addColumn("Epwnimo");
        model.addColumn("Age");
        model.addColumn("Nickname");
        table = new JTable(model); 

        stmt = con.createStatement();
        updateStatement( all );

    } catch (SQLException ex) {
        ex.printStackTrace(System.out);
    }

}

public void addStatement(String name,String surname,Integer age,String nickname )
{
  String query = "INSERT INTO Players (name,surname,age,nickname) VALUES ('"
                + name +
                "','"
                + surname +
                "',"
                + age +
                ",'"
               + nickname +
               "')";
  try {
        int x = stmt.executeUpdate( query );
        if (x > 0) {
            lastStatement(all);
               // updateStatement(all , true );
        }
      } catch (SQLException e)  {
        e.printStackTrace();
    }
}

public Boolean deleteStatement(String id , int row )
{
  String query = "DELETE FROM Players WHERE id = " + id ;
  try {
        int x = stmt.executeUpdate( query );
        if (x > 0) {
            model.removeRow(row);
            return true;
        }
        return false;

      } catch (SQLException e)  {
        e.printStackTrace();
        return false;
    }
}

public void updateStatement(String query , Boolean flag )
{
    try {
      ResultSet rs = stmt.executeQuery(  query );
        while (rs.next()) {
            int currentId = rs.getInt("id");
            String currentName = rs.getString("name");
            String currentSurname = rs.getString("surname");
            int currentAge = rs.getInt("age");
            String currentNick = rs.getString("nickname");

            Object[] currentRow = { currentId ,currentName, currentSurname, currentAge, currentNick };
            model.addRow(currentRow);
        }
    } catch (SQLException ex) {
        ex.printStackTrace(System.out);
    }
}

public void updateStatement(String query) {
    updateStatement(query , false );
}

public void lastStatement(String query )
{
    try {
      ResultSet rs = stmt.executeQuery(  query );

            rs.last();
            int currentId = rs.getInt("id");
            String currentName = rs.getString("name");
            String currentSurname = rs.getString("surname");
            int currentAge = rs.getInt("age");
            String currentNick = rs.getString("nickname");
            Object[] currentRow = { currentId ,currentName, currentSurname, currentAge, currentNick };
            model.addRow(currentRow);
    } catch (SQLException ex) {
        ex.printStackTrace(System.out);
    }
}

public JTable getTable( ) {
    return table;
}

}  

The main class

package jtable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class MainD extends JFrame{

   private JPanel p;
   //private JPanel pa;
   private JScrollPane pa; //<-- change
   private JSplitPane splitPane;
   private JButton b,ba;
   private JLabel ln,ls,la,lc;
   private JTextField txs,txn,txa,txc;
   private ControlDatabase data;
   private JTable table;

   public MainD()
   {
     super("Split");
p = new JPanel(new GridLayout(5,2));
//pa = new JPanel(new GridLayout(1,1));
pa = new JScrollPane( ); //<--
ln = new JLabel("Name");
txn = new JTextField();
ls = new JLabel("Surname");
txs = new JTextField();
la = new JLabel("Age");
txa = new JTextField();
ba = new JButton("Add");
lc = new JLabel("Nickname");
txc = new JTextField();
ba.addActionListener(new ActionListener() { //Add
    public void actionPerformed(ActionEvent e){
        String name = txn.getText();
        String surname = txs.getText();
        String sage = txa.getText();

        String nickname = txc.getText();
        if (!( name.isEmpty() || surname.isEmpty() || nickname.isEmpty() || sage.isEmpty() )) {
            try {
                Integer age = Integer.parseInt( sage );
                data.addStatement(name,surname,age,nickname);
                txn.setText("");
                txs.setText("");
                txa.setText("");
                txc.setText("");
            }catch(NumberFormatException ex){
                System.out.println("Age must be an Integer");
            }

        }
        else{
            System.out.println("Empty Fields");
        }
    }
}
);
b = new JButton("Remove");
data = new ControlDatabase();
table = data.getTable();
pa.add(table);
b.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e){
        int row = table.getSelectedRow();
        String value = String.valueOf( table.getValueAt( row ,0 ) );
        data.deleteStatement( value , row );
    }
}
);
p.add(ln);
p.add(txn);
p.add(ls);
p.add(txs);
p.add(la);
p.add(txa);
p.add(lc);
p.add(txc);
p.add(ba);
p.add(b);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p, pa);
splitPane.setDividerLocation(280);
add(splitPane);
setBounds(200,200,800,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
   }

public static void main(String[] args) {
       new MainD();
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

饮湿 2024-12-20 04:24:19

您可能没有将表格放入 JScrollPane 中,这就是它不绘制标题的原因。或者调用getTableHeader()并单独添加。引用自 JTable javadoc:

请注意,如果您希望在独立视图中使用 JTable(在
JScrollPane)并希望显示标题,您可以使用它来获取它
getTableHeader() 并单独显示。

编辑:要将组件添加到 JScrollPane 中,可以将该组件提供给 JScrollPane 的构造函数,或者调用 JScrollPane.setViewportView(component)

You probably didn't put the table in a JScrollPane, which is why it does not draw the header. Or call getTableHeader() and add it separately. Quoting from JTable javadoc:

Note that if you wish to use a JTable in a standalone view (outside of
a JScrollPane) and want the header displayed, you can get it using
getTableHeader() and display it separately.

EDIT: To add a component to a JScrollPane either give the component to the constructor of the JScrollPane, or call JScrollPane.setViewportView(component)

和影子一齐双人舞 2024-12-20 04:24:19

您需要将组件添加到 JScrollPane 的视口,而不是滚动窗格本身。

因此,将: 更改

pa.add(table);

为:

pa.getViewport().add(table);

看看会发生什么。

You need to add a component to a JScrollPane's viewport, not the scrollpane itself.

So change:

pa.add(table);

to:

pa.getViewport().add(table);

And see what happens.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文