I have a simple Swing program (TestButton.java) as under
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class TestButton extends JFrame implements ActionListener{
private final int SIZE = 200;
private Container con = getContentPane();
private JButton button = new JButton("Button");
private TextField text = new TextField(20);
private int numClicks = 0;
public TestButton()
{
super("Button");
setSize(SIZE, SIZE);
con.setLayout(new FlowLayout());
con.add(button);
con.add(text);
//con.setBackground(Color.BLACK);
//button.setBackground(Color.ORANGE);
button.setForeground(Color.BLACK);
button.addActionListener (this);
}
public void actionPerformed(ActionEvent e) {
numClicks++;
text.setText("Button Clicked " + numClicks + " times");
}
public static void main(String[] args)
{
TestButton frame = new TestButton();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
It basically creates a button and on clicking on that prints the numbers of click on the textbox. Cool!
Now I have created a package "MyPackage". Inside the "MyPackage" folder I have the MyButton java file as under
package MyPackage;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class MyButton extends JFrame implements ActionListener{
private final int SIZE = 200;
private Container con = getContentPane();
private JButton button = new JButton("Button");
private TextField text = new TextField(20);
private int numClicks = 0;
public void show()
{
setSize(SIZE, SIZE);
con.setLayout(new FlowLayout());
con.add(button);
con.add(text);
button.setForeground(Color.BLACK);
button.addActionListener (this);
}
public void actionPerformed(ActionEvent e) {
numClicks++;
text.setText("Button Clicked " + numClicks + " times");
}
}
It complied correctly. And then I have changed my TestButton.java program as under
import java.io.*;
import javax.swing.*;
import MyPackage.*;
public class TestButton extends JFrame{
public TestButton()
{
super("Button");
MyButton objButton=new MyButton();
objButton.show();
}
public static void main(String[] args)
{
TestButton frame = new TestButton();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Basically I want to execute the Button Creation/Action stuffs from a separate class file and the main program will just invoke it. The current code yields the below output
What am I doing wrong?