Java EventHandling - java

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();
}
});
}
}

Related

Utilize a ActionListener object from a separate JFrame class to main class

I am building a GUI program in which specific code takes place when a certain condition is meant (JButton is pressed). I have a seperate class that constructs my Jframe called "MyFrame" .
Essentially I want to know the proper way to use my use a ActionListener/ ActionEvent from my "MyFrame" class in conjunction when a JButton is pressed in which it would correlate properly in the main class.
For example i am able to initiate specific code when a JButton is pressed in my MyFrame class through the actionPerformed provided method by java in my Myframe class, I am just puzzled on how I can make the same thing work through my main class as well.
Any assistance would be appreciated
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
MyFrame mf;
mf= new MyFrame();
Expenses exp ;
BudgetSystem system ;
ActionEvent e ;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class MyFrame extends JFrame implements ActionListener {
JFrame myFrame;
JPanel myPanel;
JLabel greetText ;
JButton addReportButton;
JButton exitButton;
ActionListener event ;
BorderLayout layout ;
MyFrame() {
myFrame = new JFrame();
myPanel = new JPanel();
greetText = new JLabel();
addReportButton = new JButton();
exitButton = new JButton();
myPanel.setBorder(null);
myFrame.setPreferredSize(new Dimension(400,300));
greetText.setText("Please choose one of the following options to begin:" );
myPanel.add(greetText);
myFrame.add(myPanel);
addReportButton.setText("Add a budget report");
addReportButton.addActionListener(this);
myPanel.add(addReportButton);
exitButton.setText("Close Program");
exitButton.addActionListener(this);
myPanel.add(exitButton);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(null);
myFrame.pack();
}
#Override
public void actionPerformed(ActionEvent e) {
/*
if (e.getSource()==addReportButton)
{
JOptionPane.showMessageDialog(myFrame,"This button Works!");
}
else if (e.getSource()== dummyButton)
{
JOptionPane.showMessageDialog(myFrame,"This is the dummy button ! , you are targeting specific buttons now ! ... YOU ROCK :) ");
}else
JOptionPane.showMessageDialog(myFrame,"This is does not work :( ");
*/
}
}
I tried to make a specific ActionEvent object in main but that did not work properly.
I also tried to use a MyFrame object to access the actionPerformed method in java but that doesnt seem to work either.
If your goal is to add listeners to a JButton from another class, one option is to give the class that holds the JButton a public method that allows this to happen, for instance:
public void addMyButtonListener(ActionListener listener) {
myButton.addActionListener(listener);
}
This would allow any object that holds an instance of the class that holds the JButton to call this method and pass in a listener.
For instance:
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.*;
public class AddOutsideActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SomeGUI mainPanel = new SomeGUI();
mainPanel.addMyButtonListener(e -> {
String message = "Message from the main method";
String title = "Message";
int type = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(mainPanel, message, title, type);
});
JFrame frame = new JFrame("Some GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
class SomeGUI extends JPanel {
public static final int PREF_W = 600;
public static final int PREF_H = 400;
private JButton myButton = new JButton("My Button");
public SomeGUI() {
add(myButton);
setPreferredSize(new Dimension(PREF_W, PREF_H));
}
public void addMyButtonListener(ActionListener listener) {
myButton.addActionListener(listener);
}
}

Moving from one frame to another

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.

JFrame is empty

I'm working on a Java HW and faced this problem. Even though everything seems to be coded correctly, I'm getting blank frame in the end. I'm guessing it has something to do with this part in the driver program:
frame.getContentPane().add(new RandomPanel());
Here is my main program:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class RandomPanel extends JPanel
{
private JButton randButton;
private JLabel label;
public void NamePanel()
{
JPanel primary = new JPanel();
randButton = new JButton("Whats my name?");
ButtonListener listener = new ButtonListener();
randButton.addActionListener(listener);
label = new JLabel("Displaying random number");
setBackground(Color.pink);
add(label);
add(randButton);
}
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
label.setText( new Integer(new Random().nextInt(100) + 1).toString() );
}
}
}
And driver program:
import javax.swing.JFrame;
public class RandomPick
{
public static void main (String[] args)
{
JFrame frame = new JFrame("RandomPick");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RandomPanel());
frame.pack();
frame.setVisible(true);
}
}
You need to invoke namePanel to add the components to the frame.
RandomPanel randomPanel = new RandomPanel();
randomPanel.namePanel();
frame.add(randomPanel);
but you may have intended to use the method as a constructor
public RandomPanel() {
which would mean that the method call would not be necessary

how to auto change image in java swing?

Hi i am creating a java desktop application where i want to show image and i want that all image should change in every 5 sec automatically i do not know how to do this
here is my code
public class ImageGallery extends JFrame
{
private ImageIcon myImage1 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\yellow.png");
private ImageIcon myImage2 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\d.jpg");
private ImageIcon myImage3 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\e.jpg");
private ImageIcon myImage4 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\f.jpg");
JPanel ImageGallery = new JPanel();
private ImageIcon[] myImages = new ImageIcon[4];
private int curImageIndex=0;
public ImageGallery ()
{
ImageGallery.add(new JLabel (myImage1));
myImages[0]=myImage1;
myImages[1]=myImage2;
myImages[2]=myImage3;
myImages[3]=myImage4;
add(ImageGallery, BorderLayout.NORTH);
JButton PREVIOUS = new JButton ("Previous");
JButton NEXT = new JButton ("Next");
JPanel Menu = new JPanel();
Menu.setLayout(new GridLayout(1,4));
Menu.add(PREVIOUS);
Menu.add(NEXT);
add(Menu, BorderLayout.SOUTH);
}
How can i achieve this?
Thanks in advance
In this example, a List<JLabel> holds each image selected from a List<Icon>. At each step of a javax.swing.Timer, the list of images is shuffled, and each image is assigned to a label.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
/**
* #see http://stackoverflow.com/a/22423511/230513
* #see http://stackoverflow.com/a/12228640/230513
*/
public class ImageShuffle extends JPanel {
private List<Icon> list = new ArrayList<Icon>();
private List<JLabel> labels = new ArrayList<JLabel>();
private Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
update();
}
});
public ImageShuffle() {
this.setLayout(new GridLayout(1, 0));
list.add(UIManager.getIcon("OptionPane.errorIcon"));
list.add(UIManager.getIcon("OptionPane.informationIcon"));
list.add(UIManager.getIcon("OptionPane.warningIcon"));
list.add(UIManager.getIcon("OptionPane.questionIcon"));
for (Icon icon : list) {
JLabel label = new JLabel(icon);
labels.add(label);
this.add(label);
}
timer.start();
}
private void update() {
Collections.shuffle(list);
int index = 0;
for (JLabel label : labels) {
label.setIcon(list.get(index++));
}
}
private void display() {
JFrame f = new JFrame("ImageShuffle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ImageShuffle().display();
}
});
}
}
one way of achieving your goal is setting a swing.Timer to notify its action listeners every 5 seconds, set your class to be the listener for the timer and implement the actionListener interface by having an actionPerformed method which will change all images using their setImage method. the code should look like this:
public class ImageGallery extends JFrame implements ActionListener {
Timer timer;
public ImageGallery() {
timer = new Timer(5000, this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == timer) {
for (int i=0; i<vectorOfImages.size(); i++) {
vectorOfImages.get(i).setImage(AnotherImage);
}
}
}
}

How could I make the colour BLACK be transparent on top of the uploaded image?

Right now all I have is created the black background and uploaded my image I wanted. I want to make it so the image is behind a transparent background. I initially had this all in separate class files but put them all in one main class
package Flashlight;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Flashlight3 extends JFrame {
public class FlashLabelChange extends JPanel {
Flashlight.FlashDisp flashDisp;
public FlashLabelChange(Flashlight.FlashDisp _flashDisp) {
flashDisp = _flashDisp;
JButton btn1 = new JButton("Start");
add(btn1);
class Button implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Start")) {
flashDisp.UpdateLabel("Start");
}
}
}
ActionListener button = new Button();
btn1.addActionListener(button);
}
}
public class FlashDisp extends JPanel {
private JLabel lblName;
private String sLabel;
private JLabel lblImage;
public FlashDisp() {
lblImage = new JLabel();
add(lblImage);
lblName = new JLabel("Start?");
add(lblName); //add it to the Frame
}
void UpdateLabel(String _sNew) {
sLabel = _sNew;
lblName.setText(sLabel);
}
void UpdateBackground(String _sNew) {
sLabel = _sNew;
if (sLabel == ("Black")) {
setBackground(Color.black);
lblImage.setIcon(new ImageIcon("Hallway.png"));
}
}
}
public class FlashColour extends JPanel {
FlashDisp flashDisp;
public FlashColour(FlashDisp _flashDisp) {
flashDisp = _flashDisp;
setLayout(new GridLayout(3, 1));
JButton btnDark = new JButton("Dark");
add(btnDark);
class ColourChangeListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Dark")) {
flashDisp.UpdateBackground("Black");
}
}
}
ActionListener colourChangeListener = new ColourChangeListener();
btnDark.addActionListener(colourChangeListener);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
FlashMain flashMain = new FlashMain();
frame.setSize(400, 400);
frame.setTitle("FLAAAASH LIGHT");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(flashMain);
frame.setVisible(true);
}
}
I think that you need to use the opaque method.
Have a look here
setOpaque(true/false); Java for using opaque.
Hope that helps.

Categories