how to open a second jframe from a current one? - java

my current program takes in text from some JTextFields and adds it to a file to keep track of medications. What i want to do, is add another button to the bottom of the program that will open a second jframe to display the medications that are already documented, but all attempts have been brutally unsuccessful. Below is the code that i am currently working with.
Much Thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
#SuppressWarnings({ "serial" })
public class MedGUITest extends JFrame {
private JLabel medName;
private JLabel medTime;
private JLabel medDose;
private JLabel finished;
private JTextField textFieldMed;
private JTextField textFieldTime;
private JTextField textFieldDose;
private JButton submitButton;
private JButton meds;
public MedGUITest(){
setLayout(new FlowLayout());
medName = new JLabel("Type Medication Here:");
add(medName);
textFieldMed = new JTextField("",15);
add(textFieldMed);
medDose = new JLabel("Type Medication Dose:");
add(medDose);
textFieldDose = new JTextField("",15);
add(textFieldDose);
medTime = new JLabel("Type Medication Time:");
add(medTime);
textFieldTime = new JTextField("",15);
add(textFieldTime);
submitButton = new JButton("Click Here to Add");
event e = new event();
submitButton.addActionListener(e);
add(submitButton);
meds = new JButton("Click Here to see meds");
event2 r = new event2();
meds.addActionListener(r);
add(meds);
finished = new JLabel("");
add(finished);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e){
String medName = textFieldMed.getText();
String medDose = textFieldDose.getText();
String medTime = textFieldTime.getText();
File med = new File("med.txt");
try(PrintWriter out= new PrintWriter(new FileWriter(med,true))) {
out.println("Medication: " + medName + " " +"Dosage: "+ medDose + " Mg"+ " " +"Time of day: "+ medTime);
finished.setText("Your Med has been added");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class event2 implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
public static void main(String args[]) throws IOException{
int winWidth = 300;
int winLength = 300;
MedGUITest gui = new MedGUITest();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(winWidth, winLength);
gui.setVisible(true);
gui.setTitle("Standard GUI");
}
}

You would probably want to use a JDialog instead of another JFrame. You just set it up the same way you set up any other JFrame or JDialog. You create the frame/dialog, add components and then call pack() then setvisible(true). You just want to make sure that you don't set JFrame.setDefaultCloseOperation() to close when the close your second JFrame.
I find it easier to set up my classes to sub-class JPanel instead of JFrame so then it is easier to reuse it in other places.

Related

Can I use JButton as a parameter for a constructor

So I have two classes, one is a GUI class with my JButtons, JFrames etc.... My other class has my main method along with a static method to play a sound. I am trying to create a constructor that will allow me to easily create a bunch of quiz questions, it will play a sound, ask the user to identify what makes that noise, and then display if the answer was correct or incorrect. I'm trying to put the JButton in the constructor as the "correct response" for the question that will be created, but I am getting a cannot find symbol error
This is my first Class
import javax.sound.sampled.Clip;
import java.io.File;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NateApp {
private static JLabel label = new JLabel("Select the correct answer");
public static void main(String[] args)
{
File shred = new File("shredNoise.WAV");
// PlaySound(noise);
generateQuestion(" Shred", " Airplane ", "Car", "Pool Party", buttonA, shred);
}
public static void PlaySound(File Sound)
{
try{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Sound));
clip.start();
Thread.sleep(clip.getMicrosecondLength()/1000);
}
catch(Exception e){
}
}
public static void generateQuestion(String option1, String option2, String option3, String option4, JButton correctAnswer, File audioQue)
{
new GUI(option1, option2, option3, option4, correctAnswer, audioQue);
//System.out.println("Can you identify this sound?");
File noise = new File(String.valueOf(audioQue));
PlaySound(noise);
//System.out.println(option1 + option2 + option3 + option4);
if(correctAnswer.getModel().isPressed())
{
label.setText("Correct!");
}
}
}
and here is my second one with the GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class GUI implements ActionListener {
private int clicks = 0;
private JLabel label = new JLabel("Can you identify this sound?");
private JFrame frame = new JFrame();
private Object ActionEvent;
public GUI(String optionA, String optionB, String optionC, String optionD, JButton correct, File noise) {
// the clickable button
JButton buttonA = new JButton("A " + optionA);
JButton buttonB = new JButton("B " + optionB);
JButton buttonC = new JButton("C " + optionC);
JButton buttonD = new JButton("D " + optionD);
buttonA.addActionListener(this);
buttonB.addActionListener(this);
buttonC.addActionListener(this);
buttonD.addActionListener(this);
// the panel with the button and text
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
panel.setLayout(new GridLayout(0, 1));
panel.add(buttonA);
panel.add(buttonB);
panel.add(buttonC);
panel.add(buttonD);
panel.add(label);
// set up the frame and display it
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("GUI");
frame.pack();
frame.setVisible(true);
}
// process the button clicks
public void actionPerformed(ActionEvent e) {
}
// create one Frame
public static void main(String[] args) {
}
}

Why won't main method print anything?

I've been trying to figure out what's wrong with my code. I have to build a GUI and there are no errors. The program builds successfully, but no GUI pops up. So in the main method, I commented out the GUI programming and added a simple System.out.println("hello"); but it does the same thing, i.e., it builds successfully, but does not print anything. Can someone please tell me what's wrong? Thanks!
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.*;
import javax.swing.*;
import java.awt.Event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JFrame {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
super("Triangle Area Calculator");
setSize(500, 300);
setLayout(g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5*bInput*hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
public static void main(String[] args) {
/*JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);*/
System.out.println("hello world");
}
}
First, going back to the basic code...
public class GUI extends JFrame {
//...
public static void main(String[] args) {
JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);
}
}
Will fail, because you can't add a window based component to a window. As a general rule of thumb, you should avoid overriding JFrame (and other top level containers) directly and favour something less complex, like JPanel
public class GUI extends JPanel {
//...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GUI());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Next...
calc.addActionListener((ActionListener) this);
The fact that you need to perform a cast in order to get the code to work is a clear sign that something else is wrong and this is likely to cause a runtime error and crash your program. Perhaps you should start by having a read of How to write a Action Listener and How to Use Buttons, Check Boxes, and Radio Buttons to get a better understanding of how the API works
This is further supported by making use of the #Override annotation, which should be used when ever you "think" you're implementing or overriding existing functionality...
#Override
public void actionPerformed(ActionEvent e) {
//...
}
This would then fail to compile, as you're not implementing any existing functionality. This functionality is described by the ActionListener interface which you are not implementing.
While you could implement this interface directly, I prefer to avoid doing so, as it exposes functionality that other classes shouldn't have access to and you run the risk of building a "god" method, which is never a good idea.
Instead, I prefer to make use of Java's Anonymous Classes, which provides a much better means for isolating functionality to single use case, for example...
calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
});
Runnable Example
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JPanel {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
setLayout(g);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GUI());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Netbeans properties...
Now, if all that still fails to net you a result, you need to make sure that your GUI class is configured as the "Main class".
Start by right clicking the Netbeans project node and select "Properties" (it's at the bottom).
From the "Projects Properties", select "Run" from the "Build" options down the left side.
Make sure that your GUI class is marked as the "Main Class", use "Browse" to find it if it's not
Try this
calc.addActionListener(new OptionButtonHandler());
I added one optionButtonHandler class which implements ActionListener. I checked on my IDE and I was able to get the area of the triangle.
private class OptionButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
}
In your case, GUI is not an ActionListener, so that will fail.
Can you right click on the file with the main method in Netbeans, you should see the run option there, select it. This would allow you set your main method. After this, subsequent clicks on the Green play Button should work.
You do not need to cast your Frame class to an ActionListener. Instead, make it implement the ActionListener interface and your code for the button action should work. But in future, its better to add logic to detect what component triggered the action.
I don't know, but how can you write this :
calc.addActionListener((ActionListener) this);
Your object (this) is a JFrame, you should add 'implements ActionListener' first, or create a separate implementation ...
Next error, you do :
GUI one = new GUI();
frame.getContentPane().add(one);
GUI extends JFrame, its a JFrame, you can't add a JFrame in another one !
I tested with add of 'implements ActionListener' and it runs, but some errors remains ;)
Copy/paste needs wisdom, hum ^^
EDIT
this code is not perfect (and very ugly) but it works for your example :
package com.mead.helmet.core;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class GUI extends JPanel implements ActionListener {
public static void main(final String[] args) {
JFrame frame = new JFrame("Triangle Area Calculator");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);
System.out.println("hello world");
}
GridLayout g = new GridLayout(5, 2);
private final JLabel baseIn = new JLabel("Base Input");
private final JLabel heightIn = new JLabel("Height Input");
private final JTextField base = new JTextField();
private final JTextField height = new JTextField();
private final JTextField area = new JTextField();
private final JButton calc = new JButton("Calculate Area");
public GUI() {
super();
setSize(500, 300);
setLayout(g);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
setVisible(true);
}
/**
*
* #param event
*/
#Override
public void actionPerformed(final ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
}

GUI/ActionListener troubles

I'm making a GUI for my database program and I'm trying to create a button that preforms the delete function for the database. I'm having problems with the ActionListener class and getting an error called
No enclosing instance of type delete is accessible. Must qualify the allocation with an enclosing instance of type delete (e.g. x.new A() where x is an instance of delete).
on line 34 of the code. Another error I'm getting is
showDialogButton cannot be resolved to a variable
on line 65 of the code. Any help in fixing my code would be greatly appreciated.
import java.sql.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class delete
{
static JFrame frame;
public static void main(String[] args)
{
// schedule this for the event dispatch thread (edt)
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
displayJFrame();
}
});
}
static void displayJFrame()
{
frame = new JFrame("Our JButton listener example");
// create our jbutton
JButton showDialogButton = new JButton("Click Me");
// add the listener to the jbutton to handle the "pressed" event
showDialogButton.addActionListener(listen);
}
public class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// display/center the jdialog when the button is pressed
try {
Scanner scan = new Scanner(System.in);
//System.out.println("Enter a table");
String table = "teacherexample";
//System.out.println("Enter a num");
int num = 4;
//Get connection to DB
Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false" , "root" , "Starwars991211");
String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
PreparedStatement preparedStatement = myConn.prepareStatement(sql);
preparedStatement.executeUpdate(sql);
}
catch (Exception exc) {
exc.printStackTrace();
}
// put the button on the frame
frame.getContentPane().setLayout(new FlowLayout());
frame.add(showDialogButton);
// set up the jframe, then display it
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
}
Read the comments inside the code in order to get some hints of what is happening.
package test;
import java.sql.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Delete { // Class names should start with an upper case letter.
private JFrame frame; // Don't use a static JFrame (only if you know
// exactly what you are doing :))
private JButton showDialogButton; // This must be a field if you wanna access it in
// another class, in your case, the listener.
public static void main(String[] args) {
// Schedule this for the event dispatch thread (edt)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Delete del = new Delete(); // Create new instance of Delete class.
del.displayJFrame(); //Call display method.
}
});
}
private void displayJFrame() {
frame = new JFrame("Our JButton listener example");
// Create our JButton
showDialogButton = new JButton("Click Me");
// Add the listener to the JButton to handle the "pressed" event
showDialogButton.addActionListener(new MyActionListener());
// Adding the button should be done outside of the ActionLister. If it is inside
// the frame it will never be shown, because the Listener cannot be called
// (obviously) without a visible frame.
frame.getContentPane().setLayout(new FlowLayout());
// Add the button to the frame
frame.add(showDialogButton);
// Set up the JFrame, then display it
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// display/center the JDialog when the button is pressed
try {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter a table");
String table = "teacherexample";
// System.out.println("Enter a num");
int num = 4;
// Get connection to DB
Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false",
"root", "Starwars991211");
String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
PreparedStatement preparedStatement = myConn.prepareStatement(sql);
preparedStatement.executeUpdate(sql);
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
}
Edit: I just gave attention to what you wanna do and how you try to do it. Give a check to the following if you want. Read comments inside the code again to understand more.
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Display/center the JDialog when the button is pressed
final String table = "teacherexample"; // Personal opinion: if something
// wont change, define it final
int num = 500; //Your number here, i guess from scanner input.
String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
// Since java 8, auto closable, read https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false",
"root", "Starwars991211");PreparedStatement preparedStatement = myConn.prepareStatement(sql);)
{
preparedStatement.executeUpdate(sql);
}
catch (SQLException exc) { // Catching all exceptions is bad practice
// catch only the exception you wait here...
exc.printStackTrace();
}
}
}

Java - Jframe not displaying Buttons Labels or textfields

im new to java but when I try to create a new frame all I get is a new window open with a white background on and none of the buttons or text boxes or labels get added. I don't know what im doing wrong?
private static void MainGui(){
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle(name+ "'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
MainInterfaces Class
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
Your code doesn't compile because you have a lot of errors (you have no main method, private static void MainGui(){ makes no sense etc.). Try this code instead which compiles and opens the GUI fine for me, showing everything as you want to (the buttons, the labels, etc.):
1) Class MainGui.java
class MainGui{
public static void main(String[] args) {
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle("'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(MainGui.EXIT_ON_CLOSE);
}
}
2) Class MainInterfaces.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
I fixed it with one line of code. Just switch the "setVisible(true)" method to being inside the MainInterface class. However, make sure you put it as the last line of code inside the constructor, or it won't work. Basically, what was happening is that while the frame itself was being set to be true, the components were being added afterwards and were consequently not being shown. Putting "setVisible(true)" last makes sure all the components are added when you display the frame.
As a side note, you can add all methods you typed in the MainGUI class inside of MainInterface.
Here's MainGUI:
public class MainGUI
{
public static void main(String[] args)
{
new MainInterfaces();
}
}
Here's what MainInterfaces looks likes:
public class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces()
{
setTitle("(Name)'s Inbox");
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl); add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
}

Java GUI Variables Problems

I seem to have set up something wrong in the action listener for the Create Button handler. When I tried to get the value of the text field nameTF I get a null pointer error. I tried to imitate your code for the calculator, and the Exit Button Handler works well. I know that pressing the Create button invokes the handler but the statement
inName = nameTF.getText();
gives the error message.
The complete text of the listener is
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
and the whole program is below. Any help/explanation/suggestion would be very welcome.
import javax.swing.*; // import statement for the GUI components
import java.awt.*; //import statement for container class
import java.awt.event.*;
public class DogGUI //creation of DogGUI clas
{
private JLabel nameL, typeL, ageL, outtputL;
private JTextField nameTF, typeTF, ageTF;
private JButton createB, exitB;
CreateButtonHandler cbHandler;
ExitButtonHandler ebHandler;
public void driver () //creates everything
{
//create the window
JFrame DogInfo = new JFrame ("Dog GUI");
DogInfo.setSize(400,300); //set the pixels for GUI
DogInfo.setVisible(true); // set visibility to true
DogInfo.setDefaultCloseOperation(DogInfo.EXIT_ON_CLOSE); // when closed JFrame will disappear
//layout
Container DogFields = DogInfo.getContentPane();
DogFields.setLayout(new GridLayout(5,2));
// setting labels for GUI
nameL = new JLabel ("Enter name of Dog: ",
SwingConstants.RIGHT);
typeL = new JLabel ("Enter the type of the Dog: ",
SwingConstants.RIGHT);
ageL = new JLabel ("Enter the age of the Dog: ",
SwingConstants.RIGHT);
outtputL = new JLabel ("Dog Information: ",
SwingConstants.RIGHT);
//Buttons
JButton createB, exitB; //creating button for creation of Dog and button to exit
createB = new JButton("Create Dog");
exitB = new JButton("Exit");
//text fields
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
typeTF = new JTextField(15);
ageTF = new JTextField(5);
outtputTF = new JTextField(25);
outtputTF.setEditable(false); //this TF is to display this output
//Lables and Textfields
DogInfo.add(nameL);
DogInfo.add(nameTF);
DogInfo.add(typeL);
DogInfo.add(typeTF);
DogInfo.add(ageL);
DogInfo.add(ageTF);
DogInfo.add(outtputL);
DogInfo.add(outtputTF);
//Buttons
DogInfo.add(createB);
DogInfo.add(exitB);
//Instantiate Listeners
cbHandler = new CreateButtonHandler();
ebHandler = new ExitButtonHandler();
//Register Listeners
createB.addActionListener(cbHandler);
exitB.addActionListener(ebHandler);
DogInfo.setVisible(true);
}
//run the program from main, instantiate class, invoke driver() method
public static void main(String[] args)
{
DogGUI d = new DogGUI();
d.driver();
}
// class to actually handle Dog creation
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
private class ExitButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("inside exit button");
System.exit(0);
} // end method actionPerformed
}
}
You have a local variable in the driver() method called nameTF that is hiding that field (same for some other variables).
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
Remove the declaration of those fields since they are already declared as instance fields.
private JTextField nameTF, typeTF, ageTF;
(probably not outtputTF, depending on what you want to do)

Categories

Resources