package fisheriesdatabase;

import java.sql.*;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FisheriesDatabase {

public static void main(String[] args) {
    JFrame frame=new JFrame("Fish Data Entry");
    frame.setSize(500,500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel=new JPanel();
    frame.add(panel);
    placeComponents(panel);

    frame.setVisible(true);
}

public static void placeComponents(JPanel panel){
    panel.setLayout(null);

    JLabel idlabel=new JLabel("id");
    idlabel.setBounds(10, 10, 80, 25);
    panel.add(idlabel);
    JTextField idtextfield=new JTextField(20);
    idtextfield.setBounds(100, 10, 160, 25);
    panel.add(idtextfield);

    JLabel namelabel=new JLabel("Name");
    namelabel.setBounds(10, 40, 80, 25);
    panel.add(namelabel);
    JTextField nametextfield=new JTextField(20);
    nametextfield.setBounds(100, 40, 160, 25);
    panel.add(nametextfield);

    JButton button=new JButton("Enter Data");
    button.setBounds(10, 80, 80, 25);
    panel.add(button);

}

public static void connectDB() throws SQLException{
    final String url="jdbc:mysql://localhost:3306";
    final String driver="com.mysql.jdbc.Driver";
    final String dbName="netbeans_test";
    final String uname="root";
    final String pass="";

    Connection conn=null;
    try{
        //Registering the Driver
        Class.forName(driver).newInstance();

        //Open a connection
        conn=DriverManager.getConnection(url+dbName,uname,pass);
        Statement st=conn.createStatement();
        st.executeUpdate("insert into test values('"+idtextfield.getText()+"','"+nametextfield.getText()+"')");

    }
    catch(ClassNotFoundException | InstantiationException | IllegalAccessException se){
        if(conn==null)
            System.err.println("DATABASE NOT CONNECTED");
        se.printStackTrace();
    }
}
}


上面提到的代码是我开始使用Swing的开始,作为一个新手,我只是尝试创建2个方法


一种用于数据库连接
其他的gui
当我尝试访问connectDB()内的placeComponent()的属性时,它显示一个错误。有人可以帮我吗?


错误发生在executeUpdate语句中,在该语句中无法识别“ idtextfield”和“ nametextfield”

谢谢!!!

最佳答案

在课程级别声明/定义它们:

public class FisheriesDatabase {

JTextField idtextfield=new JTextField(20);
JTextField nametextfield=new JTextField(20);

public static void main(String[] args) {
    ....
    ....
}

public static void placeComponents(JPanel panel){
    panel.setLayout(null);

    .....
}

关于java - Java继承/重用能力,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30056530/

10-10 23:46