I'm pretty new to swing and I would like to receive some help as Im stuck with a task.
Current state:
Im having a nice JFrame object (guiFrame) which is having two JPanel on it (tabsPanel and cardPanel)(one is a simple JPanel with buttons, the other has CardLayout which is switched by the tabsPanel buttons).
Problem:
The task is that if I press the button "Show" on tabsPanel I need to send the cardPanel to a different window (ShowFrame) as a static "image", while on the previous window the program is still running and nice. So basicly Im trying to copy / clone the cardPanel.
What I have tried:
I have tried to simply
JPanel jPanelShow = cardPanel;
show.add(jPanelShow);
Of course not working because the reference number is being copied and if I run the program, the cardPanel "disappears".
I have tried to use clone()
For this its almost working but I'm getting some weird NullPointerException which isn't caused by my code.
Current codes (cloning try):
CardPanel.java
/**
* This is basicly a JPanel, just with a clone() implemented
*/
package javaapplication5;
import javax.swing.JPanel;
import java.util.Stack;
public class CardPanel extends JPanel implements Cloneable {
public CardPanel() {
super();
}
#Override
public CardPanel clone() throws NullPointerException {
/* Creating return object */
final CardPanel copy;
try {
/* Cloning */
copy = (CardPanel) super.clone();
} catch (CloneNotSupportedException e) {
/* Exception (should not happen though) */
e.printStackTrace();
return null;
}
return copy;
}
}
CardLayoutExample.java
package javaapplication5;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class CardLayoutExample {
JFrame guiFrame;
CardLayout cards;
CardPanel cardPanel;
private int showFrameNotShownYet = 1;
public ShowFrame show = new ShowFrame();
public static void main(String[] args) {
/* Random things for Swing */
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new CardLayoutExample();
}
});
}
public CardLayoutExample()
{
/* Creating the main JFrame */
guiFrame = new JFrame();
/* Making sure the program exits when the frame closes */
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("CardLayout Example");
guiFrame.setSize(400,300);
/* This will center the JFrame in the middle of the screen */
guiFrame.setLocationRelativeTo(null);
guiFrame.setLayout(new BorderLayout());
/* Border for JPanel separation */
Border outline = BorderFactory.createLineBorder(Color.black);
/* Creating JButton1 for tabsPanel */
JButton switchCards1 = new JButton("1");
switchCards1.setActionCommand("1");
switchCards1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
cards.show(cardPanel, "TestContent");
}
});
/* Creating JButton2 for tabsPanel */
JButton switchCards2 = new JButton("2");
switchCards2.setActionCommand("2");
switchCards2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
cards.show(cardPanel, "TestContent1");
}
});
/* Creating JButton3 for tabsPanel */
JButton switchCards3 = new JButton("3");
switchCards3.setActionCommand("3");
switchCards3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
cards.show(cardPanel, "TestContent2");
}
});
JButton switchCards4 = new JButton("Show");
switchCards4.setActionCommand("Show");
switchCards4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
/* If there is no ShowFrame yet */
if(showFrameNotShownYet == 1){
show.add((JPanel)cardPanel.clone());
show.setVisible(true);
showFrameNotShownYet = 0;
}
/* If there is a ShowFrame already */
else {
show.setVisible(false);
showFrameNotShownYet = 1;
guiFrame.repaint();
}
}
});
JButton switchCards5 = new JButton("Refresh");
switchCards5.setActionCommand("Refresh");
switchCards5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
show.setVisible(false);
show.add((JPanel)cardPanel.clone());
show.setVisible(true);
showFrameNotShownYet = 0;
}
});
/* Creating JPanel for buttons */
JPanel tabsPanel = new JPanel();
tabsPanel.setBorder(outline);
tabsPanel.add(switchCards1);
tabsPanel.add(switchCards2);
tabsPanel.add(switchCards3);
tabsPanel.add(switchCards4);
tabsPanel.add(switchCards5);
/* Creating JPanel for CardLayout */
cards = new CardLayout();
cardPanel = new CardPanel();
cardPanel.setLayout(cards);
cards.show(cardPanel, "TestContent");
/* Adding 1st card */
JPanel firstCard = new TestContent();
cardPanel.add(firstCard, "TestContent");
/* Adding 2nd card */
JPanel secondCard = new TestContent1();
cardPanel.add(secondCard, "TestContent1");
/* Adding 3rd card */
JPanel thirdCard = new TestContent2();
cardPanel.add(thirdCard, "TestContent2");
/* Filling up JFrame with stuff */
guiFrame.add(tabsPanel,BorderLayout.NORTH);
guiFrame.add(cardPanel,BorderLayout.CENTER);
guiFrame.setVisible(true);
}
}
TestContent, TestContent1 and TestContent2 are simple JPanels with random stuff generated by SwingGUI, just as ShowFrame is empty JFrame. But if needed I will paste in those codes too.
If you only need an "image" of the cardPanel, you can simply create an image and use a JLabel to show, for example...
BufferedImage img = new BufferedImage(cardPanel.getWidth(), cardPane.getHeight(), BufferedImage.BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
cardPanel.printAll(g2d);
g2d.dispose();
Now you have a "copy" of the cardPanel, you can simply use a JLabel to display it, for example...
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.DIPOSE_ON_CLOSE);
frame.add(new JLabel(new ImageIcon(img)));
frame.pack();
frame.setLocationRelativeTo(this);
frame.setVisible(true);
Related
I am new to JAVA swing , where i develop two different JFrame if I click on button frame should move to another frame and previous frame should close by opening of next frame.
I click on button a next frame open but data inside frame is not displaying and previous frame is not closed on button . Please help to find the problem in code.
Frame 1:---------------------------------
package com.demo.test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.demo.gui.TestjigWindow;
public class TestjigWindowCheck extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public TestjigWindowCheck() {
initUI();
}
private void initUI() {
mainFrame = new JFrame("Fuse Test jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showEventDemo(){
//TestjigWindow frame1 = new TestjigWindow();
headerLabel.setText("Fuse Test Jig");
headerLabel.setFont(new Font( "Arial", Font.BOLD, 25));
headerLabel.setBackground(Color.green);
JButton startButton = new JButton("Start");
startButton.setActionCommand("Start");
JButton closeButton = new JButton("Close");
closeButton.setActionCommand("close");
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
frame2.setVisible(true);
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
System.exit(0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
controlPanel.add(startButton);
controlPanel.add(closeButton);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
TestjigWindowCheck test = new TestjigWindowCheck();
test.showEventDemo();
//test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame 2----------------------------------- .
package com.demo.test;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestjigWindow2 extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JPanel controlPanel1;
public TestjigWindow2()
{
prepareGUI();
}
public static void main(String args[])
{
TestjigWindow2 test = new TestjigWindow2();
test.showRadioButton();
}
private void prepareGUI()
{
mainFrame = new JFrame("Fuse Test2 jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showRadioButton()
{
headerLabel.setText("Fuse Mode");
final JRadioButton setting =new JRadioButton("Setting");
final JRadioButton testing =new JRadioButton("Testing");
setting.setBounds(75,50,100,30);
testing.setBounds(75,100,100,30);
setting.setMnemonic(KeyEvent.VK_S);
testing.setMnemonic(KeyEvent.VK_T);
ButtonGroup group = new ButtonGroup();
group.add(setting);
group.add(testing);
controlPanel.add(setting);
controlPanel.add(testing);
JButton button = new JButton("Next");
button.setActionCommand("Next");
controlPanel.add(button);
mainFrame.setVisible(true);
}
}
For this problem, I think it's a fairly simple solution, as Andrew commented, you don't need to keep creating JFrames, you can create your JFrame in your first program, and pass it to your second class through the constructor.
Why I think your program is closing is because you are calling dispose() after creating the new frame which might be destroying the components in your new frame.
You could take this approach, which uses only one frame creating in the opening class and carried over to the second class
For Example (using snipplets of your code):
Frame 1
//This is where you are moving to the second frame.
if(e.getSource() == startButton)
{
mainFrame.getContentPane().removeAll(); //removeAll() method wipes all components attached to the contentpane of the frame
//Frame can be reused when passed to second class
TestjigWindow2 frame2 = new TestjigWindow2(this.mainFrame);
}
Frame 2
//In your constructor you could have something like this
private JFrame mainFrame;
/*
* Other variables and constants go here
*
*/
public TestjigWindow2(JFrame mainFrame)
{
this.mainFrame = mainFrame;
prepareGUI();
}
And then in prepareGUI(), you would then be adding your components to your frame, without creating a new frame. With this, your first page will be closed, and the second frame will be open, without you having to creating mutiple JFrames.
You should just create a new Instance of TestjigWindow2 in the actionPerformed method within your first frame. Instead of adding actionPerformed on the startbutton and stopbutton seperately, implement ActionListener interface in your Frame1 class and just keep one method since you are checking for the source inside the method anyways.
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
//frame2.setVisible(true); do this inside the frame2 preparegui method
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
Also the code will have a more generalized flow if you have the main method inside Frame1 and instantiate the Frame1 in it.
And you don't need to use setVisible inside the actionPerformed of Frame1.
I am designing an elevator for my software engineering class. I am using toggle buttons on the elevator cars inside panel for floor selection. I cannot figure out how to toggle the button off if the current floor equals the button being toggled. I have included a code snippet.
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
public class test {
public JPanel createContentPane() {
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(500, 500);
totalGUI.add(buttonPanel);
final JToggleButton floor3 = new JToggleButton("3");
floor3.setSize(50, 50);
floor3.setLocation(68, 100);
buttonPanel.add(floor3);
floor3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (3 == 3) {
AbstractButton abstractButton = (AbstractButton) e
.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println("Action - selected=" + selected + "\n");
floor3.setSelected(!selected);
// code to toggle the third floor button off
}
}
});
totalGUI.setOpaque(true);
return totalGUI;
}
static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Elevator");
// Create and set up the content pane.
test Welp = new test();
frame.setContentPane(Welp.createContentPane());
frame.setSize(250, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I want to call My JPanel with button. My Jpanel is actually a sub JPanel from main Panel with card layout.
to do that, i am using card layout api method HERE to show the JPanel after a button was clicked.
JButton btnCallPanel1 = new JButton("Call PanelOne");
btnCallPanel1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card = (CardLayout)mainPanel.getLayout();
card.show(mainPanel, "PanelOne"); //call Panel One
}
output :
nothing appear, panel not called and no error pop out.
My Code is HERE
package wan.dev.sample.cardlayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class HowToUseCardLayout {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HowToUseCardLayout window = new HowToUseCardLayout();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HowToUseCardLayout() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 688, 358);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 672, 260);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(new CardLayout(0, 0));
JPanel PrePanel = new JPanel();
mainPanel.add(PrePanel, "name_246268073832057");
PrePanel.setLayout(null);
JLabel lblPanel_1 = new JLabel("Pre Panel");
lblPanel_1.setBounds(280, 115, 57, 20);
PrePanel.add(lblPanel_1);
JPanel panelOne = new JPanel();
mainPanel.add(panelOne, "name_246268067657434");
panelOne.setLayout(null);
JLabel lblPanel = new JLabel("panel 1");
lblPanel.setBounds(279, 118, 46, 14);
panelOne.add(lblPanel);
JButton btnPan1 = new JButton("Call PanelOne");
btnPan1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card = (CardLayout) mainPanel.getLayout();
card.show(mainPanel, "PanelOne");
}
});
btnPan1.setBounds(262, 286, 144, 23);
frame.getContentPane().add(btnPan1);
}
}
ANSWER
The reason i cant call my panel because i did not call it by using identifier.
i have to give identifier name to my desire jpanel and use the identifier on my cardLayout.show(..)
Public Static final String PANEL_ONE = "panel one"; //Name of JPanel Identifier
//add panel to main panel and declare panelOne identifier
mainPanel.add(panelOne, PANEL_ONE); //PANEL_ONE function like
//an identifier
JButton btnCallPanel1 = new JButton("Call PanelOne");
btnCallPanel1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card =
(CardLayout)mainPanel.getLayout();
card.show(mainPanel, PANEL_ONE); //call panelOne using PANEL_ONE
//instead of JPanel name
}
As I suspected — You're calling the CardLayout.show(...) method with the String parameter "PanelOne", but yet you've not added any component to the CardLayout-using container using this same String, so it makes sense that it won't work. Solution: don't do this. Use the Same String that you add the component to the CardLayout using container as the one that you use to display it.
i.e., If you want to display container foo and use the String "bar" to add it to the CardLayout-using container, then you must pass "bar" into the CardLayout's show(...) method. Again, use String constants for this so that you reduce the chances of messing up.
Other issues: You're using null layout and setBounds — Don't. Doing this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain.
e.g.,
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class CardLayoutFoo extends JPanel {
public static final String BAR = "bar";
public static final String BUTTON_PANEL = "button panel";
private CardLayout cardlayout = new CardLayout();
public CardLayoutFoo() {
setLayout(cardlayout);
JLabel fooLabel = new JLabel("Foo", SwingConstants.CENTER);
add(fooLabel, BAR); // added using String constant, BAR
JButton showFooBtn = new JButton(new AbstractAction("Show Foo") {
#Override
public void actionPerformed(ActionEvent evt) {
// use same String, BAR, to get the fooLabl shown
cardlayout.show(CardLayoutFoo.this, BAR);
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(showFooBtn);
add(btnPanel, BUTTON_PANEL);
cardlayout.show(this, BUTTON_PANEL);
}
private static void createAndShowGui() {
CardLayoutFoo mainPanel = new CardLayoutFoo();
JFrame frame = new JFrame("CardLayoutFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I have this GUI setup. tl;dr is: its a gui and a MenuItem calls myActionListener.
There is also an Object o in this class.
I want this object o be accessible by the myActionListener as well as a myActionListener2 etc..
But i cant even call any of the Object methods.
public class MenuDemo implements ActionListener,ItemListener{
// My Object
Object o = new Object();
o.addParam();// wont work
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
menu = new JMenu("A Menu");
menuBar.add(menu);
menuItem = new JMenuItem("Title");
menuItem.addActionListener(new myListener());
menu.add(menuItem);
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
Database db = new Database();
final int test = 5;
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
Ive been trying to figure this out for a while but it seems like i cant find any help or maybe im going at it in the wrong way?
As I said in comment, you can pass a reference of the Object to different objects of type/subtype of an ActionListener:
Main class:
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame
{
private JButton btn;
Object o;
public Main()
{
setLayout(new FlowLayout());
o = new String("Hello Beautiful!");
btn = new JButton("Click!");
//Passing the reference `o` to the constructor
btn.addActionListener(new JButtonListener(o));
add(btn);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
new Test1();
}
});
}
}
Class that implements ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class JButtonListener implements ActionListener
{
private Object _obj;
public JButtonListener(Object obj)
{
_obj = obj;
}
#Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, _obj.toString());
}
}
When I compile it show error in line 33 : Cannot find symbol.
I am calling jbtNew.addActionListener(listener), so why it's unable to find jbtNew in
(e.getSource() == jbtNew) in line 33.
from code
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AnonymousListenerDemo extends JFrame {
public AnonymousListenerDemo() {
// Create four buttons
JButton jbtNew = new JButton("New");
JButton jbtOpen = new JButton("Open");
JButton jbtSave = new JButton("Save");
JButton jbtPrint = new JButton("Print");
// Create a panel to hold buttons
JPanel panel = new JPanel();
panel.add(jbtNew);
panel.add(jbtOpen);
panel.add(jbtSave);
panel.add(jbtPrint);
add(panel);
// Create and register anonymous inner-class listener
AnonymousListenerDemo.ButtonListener listener = new AnonymousListenerDemo.ButtonListener();
jbtNew.addActionListener(listener);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtNew) //Here it show the problem
{
System.out.println("Process New");
}
}
}
/** Main method */
public static void main(String[] args) {
JFrame frame = new AnonymousListenerDemo();
frame.setTitle("AnonymousListenerDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
That's a local variable.
It doesn't exist outside the constructor.
You need to make a field in the class.
this could be work (in the form as you posted here) and #SLaks mentioned +1, with a few major changes
in the case that all methods will be placed into separated classes to use put/getClientProperty()
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AnonymousListenerDemo {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame("AnonymousListenerDemo");
// Create four buttons
private JButton jbtNew = new JButton("New");
private JButton jbtOpen = new JButton("Open");
private JButton jbtSave = new JButton("Save");
private JButton jbtPrint = new JButton("Print");
public AnonymousListenerDemo() {
JPanel panel = new JPanel();// Create a panel to hold buttons
panel.add(jbtNew);
panel.add(jbtOpen);
panel.add(jbtSave);
panel.add(jbtPrint);
// Create and register anonymous inner-class listener
jbtNew.addActionListener(new ButtonListener());
frame.add(panel);
//frame.setTitle("AnonymousListenerDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtNew) {
System.out.println("Process New");
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new AnonymousListenerDemo();
}
});
}
}