How do I "activate" a button on the GUI? - java

By now, I already know my code is flawed. I just want to know why it's flawed. I want to activate the "webButton" so that when it gets clicked, it prints a message on the console that reads "This opens Mozilla Firefox."
package smartphone;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.util.Scanner;
public class Smartphone implements ActionListener {
public static void main(String[] args) {
{
{
JFrame container = new JFrame();
container.setLayout(new BorderLayout());
Scanner daniel = new Scanner(System.in);
JButton webButton = new JButton(new ImageIcon("Firefox.png"));
JButton phoButton = new JButton(new ImageIcon("Facebook.png"));
JButton texButton = new JButton(new ImageIcon("Phone.png"));
JButton setButton = new JButton(new ImageIcon("Settings.png"));
JButton smsButton = new JButton(new ImageIcon("sms.png"));
container.setTitle("Smartphone Interface!");
container.setSize(240,340);
container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container.add(setButton, BorderLayout.CENTER);
container.add(webButton, BorderLayout.SOUTH);
container.add(texButton, BorderLayout.NORTH);
container.add(phoButton, BorderLayout.EAST);
container.add(smsButton, BorderLayout.WEST);
container.setVisible(true);
webButton.addActionListener(instanceofSmartphone);
}
}
}
}

Do this.
webButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
}
});
If you want to use the ActionListener interface then, implement it in your Frame class and then replace that instanceOfSmartphone with
webButton.addActionListener(this);
And put this outside the method
public void actionPerformed(ActionEvent e) {
if(e.getSource() == webButton) {
}
}

You need to implement the actionPerformed method. An example follows.
public void actionPerformed(ActionEvent e) {
System.out.println("This method opens Mozilla Firefox.");
}
Additionally, you need to change how you add the action listener to the following.
webButton.addActionListener(this);
There are also a number of other issues. Here is a modified version of your code to get it working but far from perfect or what you will want in the end. I strongly recommend you walk through all of the tutorials in order at the below website. It doesn't get any easier than what they have. Also, if your not already using it, you should try Netbeans or some other IDE. It give you feedback that may help while you are starting out.
https://docs.oracle.com/javase/tutorial/
package smartphone;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.Scanner;
public class Smartphone extends Frame implements ActionListener {
static JButton webButton = new JButton(new ImageIcon("Firefox.png"));
static JButton phoButton = new JButton(new ImageIcon("Facebook.png"));
static JButton texButton = new JButton(new ImageIcon("Phone.png"));
static JButton setButton = new JButton(new ImageIcon("Settings.png"));
static JButton smsButton = new JButton(new ImageIcon("sms.png"));
Smartphone(){
webButton.addActionListener(this);
}
public static void main(String[] args) {
Smartphone container = new Smartphone();
container.setLayout(new BorderLayout());
Scanner daniel = new Scanner(System.in);
container.setTitle("Smartphone Interface!");
container.setSize(240, 340);
container.add(setButton, BorderLayout.CENTER);
container.add(webButton, BorderLayout.SOUTH);
container.add(texButton, BorderLayout.NORTH);
container.add(phoButton, BorderLayout.EAST);
container.add(smsButton, BorderLayout.WEST);
container.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("This opens a Firefox Webbrowser.");
}
}

You need to add an ActionListener to the buttons INSIDE of the constructor: buttonName.addActionListener(this);.
Then you need to create the following method:
public void actionPerformed(ActionEvent event) {
Object control = event.getSource();
if (control == buttonName) {
//Run code...
}
}

Related

My Buttons won't execute the command given to them

I am trying to get the buttons to at least execute something when they are pressed and BlueJ doesn't show any errors, but when I execute the Program and I try to press the buttons, nothing happens. I am really unsure why that is the case. I would appreciate any help!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MainMenu
{
JFrame frame= new JFrame();
JButton button = new JButton("Singleplayer");
JButton button2 = new JButton("Multiplayer");
MainMenu(){
prepareGUI();
}
public void prepareGUI(){
frame.setTitle("Game");
frame.getContentPane().setLayout(null);
frame.add(button);
frame.add(button2);
button.setBounds(100,200,100,40);
button2.setBounds(200,200,100,40);
frame.setVisible(true);
frame.setBounds(200,200,400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setUpButtonListeners(){
ActionListener buttonlistener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.green);
System.out.println("Singleplayer Selected");
}
};
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame.getContentPane().setBackground(Color.red);
System.out.println("Multiplayer Selected");
}
};
button.addActionListener(buttonlistener);
button2.addActionListener(buttonlistener2);
}
public class MainClass {
public void main(String args[] )
{
new MainMenu();
}
}
}
setUpButtonListeners() are not executed in the program. So action listeners are not available. you can include setUpButtonListeners() in prepareGUI method.

setContentPane() and addActionListener gets a NullPointerException

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Form1 {
private JPanel panel1;
private JButton button1;
public Form1() {
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
}
public static void main(String args[]){
JFrame frame = new JFrame("Form 1");
frame.setContentPane(new Form1().panel1);
frame.pack();
frame.setVisible(true);
}
}
The error relates to the setContentPane in main method and then also the actionListener. I've posted the exact error below. Why is this? I created this using the IntelliJ IDEA GUI form creator.
Exception in thread "main" java.lang.NullPointerException
at Form1.<init>(Form1.java:12)
at Form1.main(Form1.java:22)
In Java you can't use variables that are not initialized, else you will receive a NPE. See the following code and please read a Java book :)
public class Form1 {
private JPanel panel1;
private JButton button1;
public Form1() {
panel1 = new JPanel();
button1 = new JButton1("Press Me");
panel1.add(button1);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
}
public static void main(String args[]){
JFrame frame = new JFrame("Form 1");
frame.setContentPane(new Form1().panel1);
frame.pack();
frame.setVisible(true);
}
}
So there are 2 issues that you're going to run into that are causing that error. After you create an object (JButton, JPanel in this case), you have to instantiate them. There are a lot of different ways to do this, and it depends on what you're trying to do, but the simplest fix for your issue here is to add the following lines in the constructor:
panel1 = new JPanel();
button1 = new JButton();
Your code should run fine after that.

Update JLabel text

I'm working on a simple GUI. On Button press i want to increase/decrease a variable and update the corresponding JLabel.
class JFrameSetUp
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameSetUp extends JFrame implements ActionListener {
private int RecHeight = 0;
private int RecWidth = 0;
//Here Buttons
JButton HeightIncrease = new JButton("+");
JButton HeightDecrease = new JButton("-");
JLabel height = new JLabel(Integer.toString(RecHeight));
JLabel width = new JLabel(Integer.toString(RecWidth));
GridLayout gridLayout = new GridLayout(2, 4);
public JFrameSetUp(){
}
public void addComponentsToPane(final Container pane){
//Create GridPanel and set Layout
JPanel grid = new JPanel();
grid.setLayout(gridLayout);
//Create buttondrawPanel and set Layout
JPanel buttondraw = new JPanel();
buttondraw.setLayout(new GridLayout(2, 0));
//Adding Components to GridPanel
//Adding Layouts to pane
pane.add(grid, BorderLayout.NORTH);
pane.add(new JSeparator(), BorderLayout.CENTER);
pane.add(buttondraw, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
//Setting up ActionListener to Buttons
if (e.getSource() == this.HeightDecrease) {
RecHeight -= 1;
height.setText(Integer.toString(RecHeight));
} else if (e.getSource() == this.HeightIncrease) {
RecHeight += 1;
height.setText(Integer.toString(RecHeight));
}
}
}
Class with MainMethod
import javax.swing.JFrame;
public class Program {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrameSetUp frame = new JFrameSetUp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
I'm aware, that's kind a newbish question. I think I'm wrong with my Code Structure. Any help is appreciated.
Thanks in advance.
You never register any ActionListeners to the buttons...
HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);
You also never add the buttons to the GUI
buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);
You also never add the labels to the GUI either...
grid.add(height);
grid.add(width);
I reworked the code, because your example was messing with my mind, hope you don't mind...
It's conceptually the same idea, just done slightly more efficently
import java.awt.BorderLayout;
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.JSeparator;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int recHeight = 0;
private int recWidth = 0;
//Here Buttons
JButton heightIncrease = new JButton("+");
JButton heightDecrease = new JButton("-");
JLabel height = new JLabel(Integer.toString(recHeight));
JLabel width = new JLabel(Integer.toString(recWidth));
GridLayout gridLayout = new GridLayout(2, 4);
public TestPane() {
setLayout(new BorderLayout());
//Create GridPanel and set Layout
JPanel grid = new JPanel();
grid.setLayout(gridLayout);
grid.add(height);
grid.add(width);
//Create buttondrawPanel and set Layout
JPanel buttondraw = new JPanel();
buttondraw.setLayout(new GridLayout(2, 0));
heightIncrease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recHeight += 1;
height.setText(Integer.toString(recHeight));
}
});
heightDecrease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recHeight -= 1;
height.setText(Integer.toString(recHeight));
}
});
buttondraw.add(heightIncrease);
buttondraw.add(heightDecrease);
//Adding Components to GridPanel
//Adding Layouts to pane
add(grid, BorderLayout.NORTH);
add(new JSeparator(), BorderLayout.CENTER);
add(buttondraw, BorderLayout.SOUTH);
}
}
}
I would encourage you to spend some time having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
After changing the value call
frame.repaint();
Good to see you learning Java! A few things I should point out.
Firstly, your variable names are good, but they don't follow the Java naming convention. Even though it seems small, it's just good practice to follow.
Of course, your actual problem; the action listener you've implemented is on the JFrame. (See how you extend JFrame and implement ActionListener?) This ActionListener should be on the button. You'll can do this a few ways.
Method 1: By adding it inline with your code
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(new ActionListener(){
#Override
public void run(){
//run method here
}
});
Method 2: Create a class which implements ActionListener
class ButtonListener implements ActionListener{
#Override
public void run(){
//actionListener code here
}
}
And then instantiate an object of this type and add it directly to your code.
ActionListner buttonListener = new ButtonListener(); //or ButtonListener buttonListener = new ButtonListener();
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(buttonListener);
Of course, as in MadProgrammers answer, don't forget to add the labels and such to your JFrame or JPanel. Good luck learning Java!
I bet that your program just shows nothing, isn't it? That's because in addComponentsToPane method, you didn't add any component but empty JPanels. After the comment //Adding Components to GridPanel, you should:
buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);
grid.add(height);
grid.add(width);
Then, to listen to button event, you should also add :
HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);
"this" is because your frame JFrameSetUp implements ActionListener, so when either bootton is clicked the method actionPerformed is invoked.
As JLabel.setText method will repaint itself and consequently its component hierarchi is repainted as well, you haven't to do anything othr.

Reference clicked JButton inside ActionListener

I'm trying to write a Tic Tac Toe program using swing, but I seem to having some trouble. In my anonymous inner classes I attempt to set up the actionListener for each of my buttons, but I'm having trouble finding the type or the variable which will allow me to reference the buttons and set them to either X or Y. I tried e.getSource().setText() in my anonymous classes, but that came back with errors. Any thoughts?
Thanks!
Alex
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicTacToe {
public JFrame frame;
public JLabel label;
public JPanel panel;
public static int counter;
public void go()
{
frame = new JFrame("TicTacToe");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new GridLayout(3,3,10,10));
frame.add(BorderLayout.CENTER, panel);
label= new JLabel("TIC TAC TOE");
frame.add(BorderLayout.NORTH, label);
;
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 1");
JButton button3 = new JButton("Button 1");
JButton button4 = new JButton("Button 1");
JButton button5 = new JButton("Button 1");
JButton button6 = new JButton("Button 1");
JButton button7 = new JButton("Button 1");
JButton button8 = new JButton("Button 1");
JButton button9 = new JButton("Button 1");
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
panel.add(button7);
panel.add(button8);
panel.add(button9);
frame.setVisible(true);
panel.setVisible(true);
}
public static void main(String[] args)
{
TicTacToe gui = new TicTacToe();
gui.go();
}
}
Remember, ActionListener can be used on a number of different types of components, so the source reference is generalized. You need to cast to back to the expected value
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
// Go ahead and do what you like
}
}
});
While I know your ActionListener as it stands can pretty much guarantee that the source type of the Object will be a JButton, I never like blindly casting objects, but that's me
If you are receiving errors then you should post them but I am assuming it is because you aren't asserting that the source object is in fact a button. There are two straightforward solutions to what you are doing.
First is that since you are only adding one action listener to each button, you can assume that it is the object that the action event is referring to. Just note that the button either needs to be an instance variable or declared final:
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
button1.setText("X/Y");
}
});
Second, which would fix the cause of your error, is by asserting that the ActionEvent source object is in fact a button. This is done by checking that the source is an instance of JButton:
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
((JButton) e.getSource()).setText("X/Y");
}
}
});
I went through and cleaned up your code a little bit. I'm not quite sure why your code had errors, but I didn't get any. I suggest, since you have common code, to reuse it like I did in an array. I also added a boolean to switch between players on each button click.
Lastly, I suggest setting up the JFrame in the constructor, or in a private method called by the constructor (more complex user interfaces might have a lot of code, and breaking it up is a good habit for maintainability of your code) like I showed below.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicTacToe {
public static final boolean PLAYER_X = false;
public static final boolean PLAYER_O = true;
public static int counter;
private JFrame frame;
private JLabel label;
private JPanel panel;
private JButton[] buttons;
private boolean player;
public TicTacToe() {
frame = new JFrame("TicTacToe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 500));
panel.setLayout(new GridLayout(3, 3, 10, 10));
frame.add(BorderLayout.CENTER, panel);
label = new JLabel("TIC TAC TOE");
frame.add(BorderLayout.NORTH, label);
/* Set the initial player turn to player X */
player = PLAYER_X;
/* Create the JButtons */
buttons = new JButton[9];
/* Loop through and set all of them up */
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton();
buttons[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
((JButton)e.getSource()).setText(player ? "O" : "X"); /* Set button text */
player = !player; /* Switch turns */
}
}
});
/* Add all of the buttons to the panel. */
panel.add(buttons[i]);
}
/* Pack the frame to the contents. Basically a "fit to contents". */
frame.pack();
}
public void go() {
frame.setVisible(true);
panel.setVisible(true);
}
public static void main(String[] args) {
TicTacToe gui = new TicTacToe();
gui.go();
}
}

How do I get user input from a JTextField?

I am attempting a very simple form designed to take user input into a JTextField and show that same input via a pop up dialog.
I can hardcode the JTextField to have a preset number using setText(). If I do this, my program works flawlessly.
However, when I leave the field blank and try getText() to show the text in the pop up dialog, I either get an empty pop up frame, or I get an 'empty string' exception (I am attempting to parse String to Double.)
package buttontest;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import javax.swing.*;
import java.awt.event.ActionEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class ButtonTest
{
public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame
{
#SuppressWarnings("LeakingThisInConstructor")
public ButtonFrame()
{
setTitle("SunStream Loan Calculator v2.0");
setSize(900,900);
ButtonPanel panel = new ButtonPanel();
panel.add(new JLabel("Enter your loan amount:"));
loanAmt = new JTextField(40);
panel.add(loanAmt);
add(panel,BorderLayout.CENTER);
}
public JTextField loanAmt;
class ButtonPanel extends JPanel implements ActionListener
{
private Component frame;
public ButtonPanel()
{
final JButton b2 = new JButton("Calculate");
add(b2, BorderLayout.SOUTH);
b2.setActionCommand("calculate");
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
ButtonFrame bf = new ButtonFrame();
if("calculate".equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(frame, bf.loanAmt.getText());
}
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
Any help would be greatly appreciated. I am researching using a KeyListener or KeyEvent but I don't quite understand it well enough.
You're creating a "shadow" ButtonFrame variable inside of the b2's ActionListener. Yes the bf variable refers to a ButtonFrame object which is of the same class as the displayed ButtonFrame object, but it refers to a completely distinct and non-visualized object. The key to a solution is to get the text from the ButtonFrame object that is actually displayed, and this can be obtained from within an inner class via the ButtonFrame.this construct:
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//!! ButtonFrame bf = new ButtonFrame();
if ("calculate".equals(e.getActionCommand())) {
//!! note use of ButtonFrame.this:
JOptionPane.showMessageDialog(frame, ButtonFrame.this.loanAmt.getText());
}
}
});
Next consider using public getters rather than accessing fields such as the JTextField directly. This reduces the chances of the code causing side effects, such as changing the properties of the JTextField object inadvertently.
For instance (changes denoted by //!! comment):
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ButtonTest {
public static void main(String[] args) {
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame {
private JTextField loanAmt; // !! Make field private
#SuppressWarnings("LeakingThisInConstructor")
public ButtonFrame() {
setTitle("SunStream Loan Calculator v2.0");
setSize(900, 900);
ButtonPanel panel = new ButtonPanel();
panel.add(new JLabel("Enter your loan amount:"));
loanAmt = new JTextField(40);
panel.add(loanAmt);
add(panel, BorderLayout.CENTER);
}
// !! create a public method to get JTextField's text
// !! without exposing the JTextField itself.
public String getLoanAmtText() {
return loanAmt.getText();
}
class ButtonPanel extends JPanel implements ActionListener {
private Component frame;
public ButtonPanel() {
final JButton b2 = new JButton("Calculate");
add(b2, BorderLayout.SOUTH);
b2.setActionCommand("calculate");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// !! ButtonFrame bf = new ButtonFrame();
if ("calculate".equals(e.getActionCommand())) {
//!! call public method on ButtonFrame object
JOptionPane.showMessageDialog(frame,
ButtonFrame.this.getLoanAmtText());
}
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
The only way you can access your loanAmt is through ButtonPanel itself. Because you add loanAmt to this button right ?
So, if you want access loanAmt. You must get all component on this button panel. This is my psudeo code howto accessing your loanAmt from ButtonPanel class.
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonFrame bf = new ButtonFrame();
if("calculate".equals(e.getActionCommand())) {
// Get all component
java.awt.Component[] componentList = this.getComponents();
JTextField txtField;
String value;
for (int i = 0; i < componentList.length; i++) {
if (componentList[i].getClass().getName().equals("javax.swing.JTextField")) {
txtField = (JTextField) componentList[i];
value = textField.getText();
}
}
if (value != null) JOptionPane.showMessageDialog(frame, value);
}
}
});

Categories