Java GUI/OOP 变量问题
Java GUI/OOP variable issues
我是 Java 中使用 GUI 的新手,所以我正在尝试调整我在控制台中编写的卫星导航系统以在 gui 中工作。
我设计了一个表单,我正在尝试获取程序,以便在单击按钮时它将访问 class 中的函数 - 但是在 JFrame class 中,我遇到了问题试图访问我在主程序中创建的变量。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//graph.gatherData();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
}
//</editor-fold>
Engine graph = new Engine();
graph.addNode("Aberdeen", 391, 807);
graph.addNode("Blackpool", 331, 434);
graph.addNode("Bristol", 358, 173);
graph.addNode("Cardiff", 319, 174);
在 jButton1ActionPerformed 函数中,我希望能够访问图表。我试图在别处定义它,但它不起作用。有人可以解释如何解决这个问题吗?
因为main方法是静态方法。创建此 class 的一个实例,并在构造函数中创建您的 Engine 实例(并将其作为变量存储在您的 class 中)。
编辑:一些与之配套的代码:
public class MyClass {
private Engine graph;
public MyClass(){
graph = new Engine();
graph.addNode("Aberdeen", 391, 807);
graph.addNode("Blackpool", 331, 434);
graph.addNode("Bristol", 358, 173);
graph.addNode("Cardiff", 319, 174);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//graph.gatherData();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args){
/* Set the Nimbus look and feel */
//Create instance of your class (im assuming your jframe?)
new MyClass();
}
}
我是 Java 中使用 GUI 的新手,所以我正在尝试调整我在控制台中编写的卫星导航系统以在 gui 中工作。 我设计了一个表单,我正在尝试获取程序,以便在单击按钮时它将访问 class 中的函数 - 但是在 JFrame class 中,我遇到了问题试图访问我在主程序中创建的变量。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//graph.gatherData();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
}
//</editor-fold>
Engine graph = new Engine();
graph.addNode("Aberdeen", 391, 807);
graph.addNode("Blackpool", 331, 434);
graph.addNode("Bristol", 358, 173);
graph.addNode("Cardiff", 319, 174);
在 jButton1ActionPerformed 函数中,我希望能够访问图表。我试图在别处定义它,但它不起作用。有人可以解释如何解决这个问题吗?
因为main方法是静态方法。创建此 class 的一个实例,并在构造函数中创建您的 Engine 实例(并将其作为变量存储在您的 class 中)。
编辑:一些与之配套的代码:
public class MyClass {
private Engine graph;
public MyClass(){
graph = new Engine();
graph.addNode("Aberdeen", 391, 807);
graph.addNode("Blackpool", 331, 434);
graph.addNode("Bristol", 358, 173);
graph.addNode("Cardiff", 319, 174);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//graph.gatherData();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args){
/* Set the Nimbus look and feel */
//Create instance of your class (im assuming your jframe?)
new MyClass();
}
}