1

我需要帮助从我的数据库中检索表名,然后将其解析为 JCombobox,当单击表名时,将执行 sql 语句,然后在 JTable 中显示表。

我的问题是如何对 selectedItem 进行编码,以便它将执行查询并在 JTable 上显示 IT

这是我的 gui.java 文件

 package Assignment3.Live;

 import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.io.FileOutputStream;
 import java.io.ObjectOutputStream;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.Vector;

 import javax.swing.*;
  import javax.swing.border.TitledBorder;
 import javax.swing.event.TableModelEvent;
 import javax.swing.table.DefaultTableModel;
 import javax.swing.table.JTableHeader;
  import javax.swing.table.TableColumn;
 import javax.swing.table.TableColumnModel;
 import javax.swing.table.TableModel;

import net.proteanit.sql.DbUtils;

   ;

   /**
     * @author jmickey
   * 
   */
   public class GUI extends JFrame {

// Variables
 public Main main;
  DBCon db;
 MakeTable make;

  private JFrame frame = new JFrame();
   private JPanel pNorth, pChooser, pdp, pRC, pSCR, pTab, pSouth, pBtn;

  public ResultSet rseTo = null;// result set
   public PreparedStatement pst = null;
   private ResultSetMetaData meta = null;

 String tableNamesnow = "";
  private JMenuBar jMenuBar;
  private JMenu file, help;

private JComboBox<String> jcmb = new JComboBox<String>();
 ComboBoxModel<?> giveMeTableName = (ComboBoxModel<?>) jcmb
    .getSelectedItem();
 private JTable jT = new JTable();

private JTextArea text;
private JButton search, clear, displayRow, deletRow, addRow, query, save,
    restore;
private JCheckBox rowS = new JCheckBox("Select by Rows", true);
private JCheckBox colS = new JCheckBox("Selcet by Column", false);

     /*
   * private String[] columnNames = {}; private Object [][] rowData = {};
   */

  public GUI() throws SQLException {
GUInterface();
getTableNames();
arrayOfTable();
}

   public void GUInterface() {// constructor
// Menubar
setLayout(new BorderLayout(5, 10));
jcmb.setSelectedItem("");
jMenuBar = new JMenuBar();
file = new JMenu("File");
file.add(new JMenuItem("Start"));
file.add(new JMenuItem("Exit"));
help = new JMenu("Help");
help.add(new JMenuItem("Help"));
jMenuBar.add(file);
jMenuBar.add(help);

// Button
save = new JButton("Save");
clear = new JButton("Clear");
restore = new JButton("Restore");

displayRow = new JButton("Display Row");
deletRow = new JButton("Delet Row");
addRow = new JButton("Add New Row");
query = new JButton("QUERY");

// choose table panel = 1
pChooser = new JPanel();
pChooser.setLayout(new BorderLayout(5, 0));
pChooser.setBorder(new TitledBorder("Tables"));
pChooser.add(new JLabel("Select a table: "), BorderLayout.WEST);
pChooser.add(jcmb, BorderLayout.CENTER);

// Row/Column selection Panel = 2
pRC = new JPanel();
pRC.setLayout(new FlowLayout(FlowLayout.LEFT));
pRC.add(rowS);
pRC.add(colS);

// noth panel holds (pChooser & pRC)
pNorth = new JPanel();
pNorth.setLayout(new GridLayout(2, 1));
pNorth.add(pChooser);
pNorth.add(pRC);

// JTable panel
pTab = new JPanel();
pTab.setLayout(new GridLayout(1, 1));
pTab.add(jT);
pTab.add(new JScrollPane(jT));

// display holds (pNorth & pTab)
pdp = new JPanel();
pdp.setLayout(new BorderLayout(2, 1));
pdp.add(pNorth, BorderLayout.NORTH);
pdp.add(pTab, BorderLayout.SOUTH);

// Save, Clear or restore Panel
pSCR = new JPanel();
pSCR.add(save);
pSCR.add(clear);
pSCR.add(restore);

// Button selection panel
pBtn = new JPanel();
pBtn.setLayout(new GridLayout(2, 2));
pBtn.add(displayRow);
pBtn.add(addRow);
pBtn.add(query);
pBtn.add(deletRow);

// South panel (pSCR & pBtn)
pSouth = new JPanel();
pSouth.setLayout(new BorderLayout(2, 1));
pSouth.add(pBtn, BorderLayout.SOUTH);
pSouth.add(pSCR, BorderLayout.CENTER);

// Table info
jT.setAutoResizeMode(jT.AUTO_RESIZE_OFF);
jT.setGridColor(Color.BLUE);
jT.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jT.setSelectionBackground(Color.BLUE);
jT.setSelectionForeground(Color.WHITE);
jT.setRowSelectionAllowed(true);

/*
 * Task 1. change action to diplay row = create the 2.delete row
 * 3.insert row
 */

frame.setJMenuBar(jMenuBar);
frame.add(pdp, BorderLayout.NORTH);
frame.add(pSouth, BorderLayout.SOUTH);

frame.setTitle("Walters SPJ Directory");
frame.setResizable(true);
frame.setSize(465, 648);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// display rows
displayRow.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // when the search button is clicked
        if (e.getSource() == displayRow) {
            jcmb.setSelectedItem(giveMeTableName);
            for (int i = 0; i < jcmb.getSelectedIndex(); i++)
                displayS();
        }
    }

});

// Checkbos ActionListener
rowS.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        jT.setRowSelectionAllowed(rowS.isSelected());
    }
});
colS.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        jT.setRowSelectionAllowed(colS.isSelected());
    }
});

// Clear ActionListener
clear.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        TableModel myData = DbUtils.resultSetToTableModel(rseTo);
        jT.tableChanged(null);
    }
});

    }

     // get tableNames
      public void getTableNames() throws SQLException {
        rseTo = null;
  java.sql.DatabaseMetaData meta = DBCon.con.getMetaData();
   rseTo = meta.getTables(null, null, "%", new String[] { "TABLE" });

    while (rseTo.next()) {
    String nameOfTables = rseTo.getString(3);
    String tableCatalog = rseTo.getString(1);
    String tableSchema = rseTo.getString(2);

    System.out.printf("%s - %s - %s%n", tableCatalog, tableSchema,
            nameOfTables);
}

db.stm.close();

}

         // get table name to JCombobox
           public void arrayOfTable() throws SQLException {
            rseTo = db.con.getMetaData().getTables(null, null, "%",
        new String[] { "TABLE" });

           while (rseTo.next()) {
    String giveMeTableName = (rseTo.getString(3));

    jcmb.addItem(giveMeTableName);

    System.out.println(giveMeTableName);
            }

jcmb.setBounds(130, 30, 190, 30);
jcmb.setEditable(false);
jcmb.getSelectedIndex();

return;

 }

          /*
          * Table selection method
          */
          public void displayS() {
        try {
    String sql = "SELECT DISTINCT * FROM " + giveMeTableName;
    pst = DBCon.con.prepareStatement(sql);
    rseTo = pst.executeQuery();
    TableModel myData = DbUtils.resultSetToTableModel(rseTo);
    jT.setModel(myData);
        } catch (Exception ex) {
    JOptionPane.showMessageDialog(null, ex);
        }
      }

     public void displayP() {
        try {
    String sql = "SELECT DISTINCT * FROM P";
    pst = DBCon.con.prepareStatement(sql);
    rseTo = pst.executeQuery();
    jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
    JOptionPane.showMessageDialog(null, ex);
}

     }

         public void displayJ() {
            try {
    String sql = "SELECT DISTINCT * FROM " + make.tableName;
    pst = DBCon.con.prepareStatement(sql);
    rseTo = pst.executeQuery();
    jT.setModel(DbUtils.resultSetToTableModel(rseTo));
        } catch (Exception ex) {
    JOptionPane.showMessageDialog(null, ex);
   }

       }

          public void displaySPJ() {
        try {
    String sql = "SELECT DISTINCT * FROM SPJ";
        pst = DBCon.con.prepareStatement(sql);
        rseTo = pst.executeQuery();
        jT.setModel(DbUtils.resultSetToTableModel(rseTo));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex);
        }

                }

             }
4

1 回答 1

0

对于这样的任务,您需要意识到您正在开发一种新的(简单的)编程语言。这意味着输入不再是自由形式,而是必须遵守某些规则。例如:

Table name: S
...
Table name: 

P

不好。编辑文件的人应该坚持一种方式来指定表名;否则你的解析器会很快变得复杂。

作为此类任务的一般准则:

  1. 逐行读取输入。
  2. 忽略空行
  3. 修剪线条以消除过多的空白
  4. 使用类似Table name:的模式line.startsWith()来找出你语言的下一个“块”是什么意思。
  5. 读取每个块的值并进行处理。line.split("\\s", -1)是将输入拆分为单词的朋友。

当您创建一些简单的测试用例并使用单元测试来确保您的解析器在内存中构建正确的数据结构时,正确的做法会变得更容易。

于 2013-11-06T08:35:01.990 回答