2015-10-08 69 views
-2

我目前正在學習關於swing和數據庫的所有信息。我只是想嘗試一些代碼,所以我創建了一個程序,要求用戶輸入他/她的名字,姓氏,性別,生日和年齡。然後,輸入將被存儲到數據庫。現在,我想用代碼做三件事,但我無法弄清楚如何去做。如何在java中使用GUI?

  1. 我製作了三個月份,日期和年份的組合框。我希望日期的組合框根據我要選擇的月份進行調整。例如,如果我選擇二月,日期應該只能達到28.

  2. 接下來,當我點擊添加項目時,您可以輸入所有信息。一切工作正常,但我注意到,當你點擊按鈕出口,它會關閉一切。我想要退出按鈕只關閉添加項目部分,而整個菜單仍然可見。

  3. 最後,當我點擊查看項目時,它會單獨顯示錶格。我希望桌子在菜單中,就像添加物品一樣。

這裏是我的代碼:

PART1:

package PersonalInfo; 

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

public class TableFormatter extends JFrame{ 
private final int WIDTH = 600; 
private final int HEIGHT = 400; 
public TableFormatter(Object[][]data,Object[]colNames){ 
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
    JTable table = new JTable(data,colNames); 
    JScrollPane scrollPane = new JScrollPane(table); 
    add(scrollPane,BorderLayout.CENTER); 
    setSize(WIDTH,HEIGHT); 
    setVisible(true); 
} 
} 

PART2:

package PersonalInfo; 
import java.sql.*; 
public class ConnectDBQuery { 
public final String DB_URL="jdbc:derby://localhost:1527/InformationDB;"; 
private Connection conn; 
private String[][]tableData; 
private String[]colNames; 
public ConnectDBQuery(){ 
    getDatabaseConnection(); 
    try{ 
     Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
          ResultSet.CONCUR_READ_ONLY); 
     ResultSet resultSet = stmt.executeQuery("SELECT * FROM PersonalInfo"); 
     resultSet.last(); 
     int numRows = resultSet.getRow(); 
     resultSet.first(); 

     ResultSetMetaData meta = resultSet.getMetaData(); 
     colNames = new String[meta.getColumnCount()]; 
     for(int i = 0;i < meta.getColumnCount();i++){ 
      colNames[i]=meta.getColumnLabel(i+1); 
     } 

     tableData = new String[numRows][meta.getColumnCount()]; 
     for(int row = 0;row < numRows;row++){ 
      for(int col = 0;col < meta.getColumnCount();col++){ 
       tableData[row][col]=resultSet.getString(col+1); 
      } 
      resultSet.next(); 
     } 
     stmt.close(); 
     conn.close(); 
    }catch(Exception ex){ 
     ex.printStackTrace(); 
    } 
} 

private void getDatabaseConnection(){ 
    try{ 
     conn = DriverManager.getConnection(DB_URL); 
    }catch(Exception ex){ 
     ex.printStackTrace(); 
     System.exit(0); 
    } 
} 

public String[]getColumnNames(){ 
    return colNames; 
} 

public String[][]getTableData(){ 
    return tableData; 
} 
} 

PART3:

package PersonalInfo; 

import java.sql.*; 

public class InfoDBQuery { 
public final String DB_URL="jdbc:derby://localhost:1527/InformationDB;"; 

public InfoDBQuery(String firstName,String lastName,String gender,String month,String date,String year,String age){ 

    try{ 
     Connection conn = DriverManager.getConnection(DB_URL); 
     Statement stmt = conn.createStatement(); 
     String sql = "INSERT INTO PersonalInfo VALUES ('" + 
     firstName + "','" + lastName + "','" + gender + "','" + month + "-" + date + "-" + year + "','" + age + "')"; 
     stmt.executeUpdate(sql); 
     stmt.close(); 
     conn.close(); 
    }catch(Exception ex){ 
     System.out.println("ERROR: " + ex.getMessage()); 
    } 
} 


} 

4部分:

package PersonalInfo; 

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

public class InfoDBViewer extends JFrame{ 
JMenuBar menuBar; 
JMenu fileMenu; 
JMenuItem addItem; 
JMenuItem viewItem; 
JMenuItem exitItem; 

JPanel textPanel; 
JLabel firstNameLabel; 
JLabel lastNameLabel; 
JTextField firstNameText; 
JTextField lastNameText; 
JLabel ageLabel; 
JTextField ageText; 

JPanel rbuttonPanel; 
JRadioButton maleButton; 
JRadioButton femaleButton; 

JPanel comboPanel; 
JComboBox monthBox; 
JComboBox dateBox; 
JComboBox yearBox; 

String[]months = {"January","February","March","April", 
     "May","June","July","August","September","October", 
     "November","December"}; 

String[]date = {"1","2","3","4","5","6","7","8","9","10","11", 
     "12","13","14","15","16","17","18","19","20","21","22","23","24","25", 
     "26","27","28","29","30","31"}; 

String[]year = {"1985","1986","1987","1988","1989","1990","1991","1992","1993", 
     "1994","1995","1996","1997","1998","1999","2000","2001","2002","2003", 
     "2004","2005","2006","2007","2008","2009","2010","2011","2012","2013", 
     "2014","2015"}; 

JPanel buttonPanel; 
JButton submitButton; 
JButton exitButton; 

public InfoDBViewer(){ 
    setTitle("Menu System"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setSize(600,400); 
    buildMenuBar(); 
    setVisible(true); 
} 

private void AddItems(){ 
    setTitle("CoffeeDB Viewer"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setSize(600,400); 
    buildTextFieldPanel(); 
    buildRadioButtonPanel(); 
    buildComboBoxPanel(); 
    buildButtonPanel(); 
    add(textPanel,BorderLayout.NORTH); 
    add(rbuttonPanel,BorderLayout.WEST); 
    add(comboPanel,BorderLayout.EAST); 
    add(buttonPanel,BorderLayout.SOUTH); 

    setVisible(true); 
} 

private void buildMenuBar(){ 
    menuBar = new JMenuBar(); 
    buildFileMenu(); 

    menuBar.add(fileMenu); 
    setJMenuBar(menuBar); 
} 

private void buildFileMenu(){ 
    exitItem = new JMenuItem("Exit"); 
    exitItem.addActionListener(new ExitListener()); 
    addItem = new JMenuItem("Add Item"); 
    addItem.addActionListener(new AddListener()); 
    viewItem = new JMenuItem("View Item"); 
    viewItem.addActionListener(new ViewListener()); 

    fileMenu = new JMenu("File"); 
    fileMenu.add(addItem); 
    fileMenu.add(viewItem); 
    fileMenu.add(exitItem); 
} 

private class AddListener implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
     AddItems(); 
    } 
} 

private class ViewListener implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
     ConnectDBQuery dbQuery = new ConnectDBQuery(); 
     String[]colNames = dbQuery.getColumnNames(); 
     String[][]data = dbQuery.getTableData(); 
     TableFormatter table = new TableFormatter(data,colNames); 
    } 
} 

private class ExitListener implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
     System.exit(0); 
    } 
} 



private void buildTextFieldPanel(){ 
    textPanel = new JPanel(); 
    firstNameLabel = new JLabel("First Name"); 
    firstNameText = new JTextField(10); 
    lastNameLabel = new JLabel("Last Name"); 
    lastNameText = new JTextField(10); 
    ageLabel = new JLabel("Age"); 
    ageText = new JTextField(5); 

    textPanel.add(firstNameLabel); 
    textPanel.add(firstNameText); 
    textPanel.add(lastNameLabel); 
    textPanel.add(lastNameText); 
    textPanel.add(ageLabel); 
    textPanel.add(ageText); 

} 

private void buildRadioButtonPanel(){ 
    rbuttonPanel = new JPanel(); 
    maleButton = new JRadioButton("Male",true); 
    femaleButton = new JRadioButton("Female"); 

    ButtonGroup bg = new ButtonGroup(); 
    bg.add(maleButton); 
    bg.add(femaleButton); 

    rbuttonPanel.add(maleButton); 
    rbuttonPanel.add(femaleButton); 
} 

private void buildComboBoxPanel(){ 
    comboPanel = new JPanel(); 
    monthBox = new JComboBox(months); 
    dateBox = new JComboBox(date); 
    yearBox = new JComboBox(year); 

    comboPanel.add(monthBox); 
    comboPanel.add(dateBox); 
    comboPanel.add(yearBox); 
} 

private void buildButtonPanel(){ 
    buttonPanel = new JPanel(); 
    submitButton = new JButton("Submit"); 
    submitButton.addActionListener(new SubmitButtonListener()); 
    exitButton = new JButton("Exit"); 
    exitButton.addActionListener(new ExitButtonListener()); 
    buttonPanel.add(submitButton); 
    buttonPanel.add(exitButton); 
} 

private class SubmitButtonListener implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
     String firstNameStatement = firstNameText.getText(); 
     String lastNameStatement = lastNameText.getText(); 

     String genderStatement = ""; 
     if(maleButton.isSelected()){ 
      genderStatement = maleButton.getText(); 
     }else if(femaleButton.isSelected()){ 
      genderStatement = femaleButton.getText(); 
     } 

     String monthStatement = (String)monthBox.getSelectedItem(); 
     String dateStatement = (String)dateBox.getSelectedItem(); 
     String yearStatement = (String)yearBox.getSelectedItem(); 

     String ageStatement = ageText.getText(); 

     InfoDBQuery dbQuery = new InfoDBQuery(firstNameStatement, 
       lastNameStatement,genderStatement,monthStatement, 
       dateStatement,yearStatement,ageStatement); 

    } 
} 

private class ExitButtonListener implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
     System.exit(0); 
    } 
} 

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

我爲亂碼道歉,還裸露與我的解釋,截至目前我傾向於忘記編程術語,但希望我將得到改善。

回答

1

問題1)

你需要做的是改變manualy(或建造您的日期組合框)添加偵聽器,以一個月組合框

 monthBox.addItemListener(new ItemListener() { 

     @Override 
     public void itemStateChanged(ItemEvent e) { 
      //Set you days 
     } 
    }); 

問題2)真的不能按照你的代碼,但 System.exit(),將關閉應用程序 setVisible(false)會隱藏,如果你想再次看到它,你需要做的setVisible(true)

問題3)你想告訴你的表在M ENU ??,使用JMenu對象,並添加到它JMenuItems(你的表的第1列?)...

我會建議您使用JFrame,然後你用JPanel將它添加到JFrame顯示了表,如果喜歡添加的人可以打開一個JDialog,用戶可以在其中輸入數據,然後保存關閉JDialog並更新表格。

0

例如,如果我選擇2月份,日期應該只能達到28。

不要忘記閏年計算。您可能需要考慮日期組件,例如JXDateChooser或JCalendar。

但我注意到,當你點擊按鈕出口時,它會關閉所有東西。

應用程序應該只有一個JFrame。其他的子窗口應該是一個模態的JDialog。當您關閉對話框時,只有對話框關閉並且框架保持打開狀態。

String sql = "INSERT INTO PersonalInfo VALUES ('" + firstName + "','" + lastName + "','" + gender + "','" + month + "-" + date + "-" + year + "','" + age + "')"; 

不要像這樣構建你的SQL,它很容易試圖匹配文字。

相反,您可以使用PreparedStatement,這使得SQL語句更容易編碼和維護。

String sql = "INSERT INTO PersonalInfo VALUES (?, ?, ?, ?, ?)"; 

PreparedStatement stmt = connection.prepareStatement(sql); 

stmt.setString(1, firstName); 
stmt.setString(2, lastName); 
stmt.setString(3, gender); 
stmt.setString(4, month + "-" + date + "-" + year); 
stmt.setInt(5, age); 

stmt.executeUpdate(); 

現在PreparedStatement會照顧正確的語法。