I am having a hard time figuring out how to use the db object created in the first action event within the second action... how can i make the object visible there? i am trying to say add a record to db object by saying something like
...
class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {

String record1 = field2.getText();
String record2 = field3.getText();
String record3 = field4.getText();

db.addRecord(record1, record2, record3); // but cannot see instance of db here
}
}

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

public class MyDbGUIPanel extends JPanel {

  private JTextField field1, field2,field3,field4;
  private JLabel label1, label2, label3, label4, label5;
  private JButton button1;

    public MyDbGUIPanel () {
		  
		  label1 = new JLabel("Create a database: ");
		  add (label1);
		  field1 = new JTextField(5);
		  add (field1);
		  field1.addActionListener(new Action());	  
		  label2 = new JLabel("   --------               ");
		  add(label2);
		  label3 = new JLabel("    Create a new record  (Name)");
		  add(label3);
		  field2 = new JTextField(5);
		  add (field2);
		  label4 = new JLabel(" (Homeworks)");
		  add(label4);
		  field3 = new JTextField(5);
		  add (field3);
		  label5 = new JLabel(" (Exams)");
		  add(label5);
		  field4 = new JTextField(5);
		  add (field4);
		  button1 = new JButton ("Add Record");
		  add (button1);
	//	  button1.addActionListener(new Action2());

		  
	     setPreferredSize (new Dimension(400,400));
	 }
	 
	  class Action implements ActionListener {
	     public void actionPerformed (ActionEvent e) {
	         String newDatabaseName = field1.getText();
				StudentDB db = new StudentDB(newDatabaseName);
				label2.setText("databse: " + db);	
	     } 
	 }
	/* 
	  class Action2 implements ActionListener {
	     public void actionPerformed (ActionEvent e) {
	       	db.	  }
	 }  */  
}

The action listeners are both inner classes of your main class, so if you move the declaration of StudentDB db out to the main class class you can access it from both listeners.

i would like the action of creating a new StudentDB when entering it's name into the first field, not quite following how i can do that in main, could you provide an example? here is the main class i'm working with...

import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
public class MyDbGUI {

    public static void main (String[] args) {
	 
	     JFrame frame = new JFrame ("MyDBGUI");
		  MyDbGUIPanel panel = new MyDbGUIPanel();
		  frame.getContentPane().add(panel);
		  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		  frame.pack();
		  frame.setVisible(true);
		  //frame.setResizable(false);  */
		  //	StudentDB db = new StudentDB(newDatabaseName);
	 }
}

Edited 6 Years Ago by kezkez: n/a

This question has already been answered. Start a new discussion instead.