【发布时间】:2015-05-05 14:58:45
【问题描述】:
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”
谢谢!!!
【问题讨论】:
-
这些是范围为
placeComponents的变量,未在connectDB中定义。请阅读变量范围:java-made-easy.com/variable-scope.html -
跟继承无关。
executeUpdate()由于作用域不同,不能使用提到的变量 -
我猜测与继承无关,但由于它们是内置类的实例,我该如何使用它们?我的意思是如何扩大他们的范围?
-
您需要将保存 GUI 元素的变量声明为类字段,而不是 placeComponents() 函数中的变量。
-
此外,最佳实践是分离出关注点 - 在这种情况下,连接到数据库甚至检索数据之类的事情应该/不/在您的摇摆/显示类中......考虑制作一个具有数据点的抽象表示的数据视图。您将能够以这种方式编写测试和/或稍后重用您的代码。