Two java questions involving swing

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
Im learning swing! :cool: Ive made a simple program to add or decrement a number on screen, there are two JButtons, one JLabel and its all in a JFrame. First question is how come when i run this program and then close with the red X the process continues to run? Or at least netbeans shows it still running.

Heres the code:

package buttontest;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author Max
*/
public class ButtonTest extends JFrame
{
int buttonClicks;
JButton plusButton;
JButton minusButton;
JButton cancelButton;
JLabel outputLabel;

public ButtonTest(String aTitle)
{
super(aTitle);
setSize(300,300);
plusButton = new JButton("Plus");
minusButton = new JButton("Minus");
outputLabel = new JLabel("Button clicks appear here");
add(outputLabel,"Center");
add(plusButton,"East");
add(minusButton,"West");
plusButton.addActionListener(new ButtonListener());
minusButton.addActionListener(new ButtonListener());
}

private class ButtonListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent anEvent)
{
if(anEvent.getSource().equals(plusButton))
{
buttonClicks++;
}
if(anEvent.getSource().equals(minusButton))
{
buttonClicks--;
}


outputLabel.setText("Button clicks = " + buttonClicks);
}
}
}

Second question is whats happening when a method is called with no receiver argument? Up until now ive seen anObject.methodA(); or static like SomeClass.methodB(); what happens when an instance method is called on its own like methodA(); Does it just automatically apply to the JFrame that this method is a part of? Is that why methods like setSize(x,y); work?
 

MrChad

Lifer
Aug 22, 2001
13,507
3
81
First question is how come when i run this program and then close with the red X the process continues to run? Or at least netbeans shows it still running.

Try adding this in your constructor

Code:
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

what happens when an instance method is called on its own like methodA(); Does it just automatically apply to the JFrame that this method is a part of? Is that why methods like setSize(x,y); work?

this is implied in those instances. In general, it's still a good idea to use the this keyword. http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Code:
this.setSize(300,300);
this.add(outputLabel,"Center");
this.add(plusButton,"East");
this.add(minusButton,"West");