データベースから JTable を入力しました。しかし、テーブルは表示されません。コードの問題がわかりません。問題がレイアウトにあるのか、それともデータベースからデータを取得するコード ブロックにあるのか理解できません。また、例外メッセージも表示されません。frame.getContentPane().add(scroll, BorderLayout.CENTER);
コードに追加しましたが、まだテーブルを作成できません。添付の画像をご覧ください。
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import controller.DB_con;
public class Jtable {
private JFrame frame;
private JTable table;
String[] columnNames = {"ID", "name", "username", "contact", "GENDER"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Jtable window = new Jtable();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
}
}
});
}
/**
* Create the application.
*/
public Jtable() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
table = new JTable();
frame.getContentPane().add(table, BorderLayout.CENTER);
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
frame.getContentPane().add(scroll, BorderLayout.CENTER);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
try
{
Connection sqlCon = DB_con.getSQLConnection();
PreparedStatement ps = sqlCon.prepareStatement("select id,name,username,contact,gender from temp_tbl");
int i = 0;
ResultSet rs = ps.executeQuery();
while(rs.next())
{
String id = rs.getString("id");
String name = rs.getString("name");
String username = rs.getString("username");
String contact = rs.getString("contact");
String gender = rs.getString("gender");
model.addRow(new Object[]{id, name, username, contact, gender});
i++;
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
をJTable
フレームに追加し、次にそれを に追加しますJScrollPane
がJScrollPane
、何かに追加することはありません...
コンポーネントは単一のコンテナ内にのみ存在できるため、これを行うJScrollPane scroll = new JScrollPane(table);
とJTable
、フレームからを削除することになります。
をframe.getContentPane().add(scroll, BorderLayout.CENTER);
作成した後に追加します。JScrollPane
またTableModel
、JTable
table.setModel(model);
frame.getContentPane().add(scroll, BorderLayout.CENTER);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加