JButton and ActionListener Issue - java

Hey guys I really appreciate any help but I was recently coding this easy software and ran into a weird issue. I was trying to use an ActionListener but I some how messed up. Its been awhile since I have done this. Sorry if this is just a careless mistake.
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 startScreen implements ActionListener {
JFrame mainFrame;
JPanel mainPanel;
JButton gotIt;
private final String gotItText = "Got It!";
public static void main(String[] args) {
startScreen a = new startScreen();
a.screenSetup();
}
private void screenSetup() {
mainFrame = new JFrame();
mainPanel = new JPanel();
gotIt = new JButton();
mainFrame.add(mainPanel);
mainPanel.add(gotIt);
gotIt.setText(gotItText);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
JButton buttonPressed = (JButton) arg0.getSource();
if (buttonPressed==gotIt) {
System.out.println("gotIt has been pressed!");
}
}
}

You should add your actionListener to the component that you want. Here the problem is you defined a function but you did not add it to your button.
I think this link gives you a very good understanding about how it works.
http://alvinalexander.com/java/jbutton-listener-pressed-actionlistener

Related

How to call this method into my other file?

I want to be able to call the Introduction.Intro() method into my main file code, but it tells me I am unable to call a non-static method intro from a static context. Since I am still fairly new to coding I'm not entirely sure what the problem is. I've added my codes down below. I've tried countless online methods but sadly none have seemed to work.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Start extends JFrame implements ActionListener
{
private JFrame Main;
private JPanel PanelA, PanelB, PanelC;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public Start ()
{
//Button
Button = new JButton("Start");
Button.addActionListener(new ButtonListener());
//Text
Text = new JLabel("Welcome To The Game"); //ADD NAME OF THE GAME
//Image
Image = new ImageIcon(getClass().getResource("download.jfif")); //ADD THE IMAGE FOR WELCOME
ImageL = new JLabel(Image);
//Top Panel (PanelA) - Image
PanelA = new JPanel();
PanelA.setBorder(BorderFactory.createEmptyBorder(0,200,150,200));
PanelA.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelA.add(ImageL);
//Middle Panel (PanelB) - Text
PanelB = new JPanel();
PanelB.setBorder(BorderFactory.createEmptyBorder(50,200,10,200));
PanelB.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelB.add(Text);
//Bottom Panel (PanelC) - Buttons
PanelC = new JPanel();
PanelC.setBorder(BorderFactory.createEmptyBorder(0,200,20,200));
PanelC.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelC.add(Button);
//Main Frame
Main = new JFrame ();
Main.add(PanelA, BorderLayout.NORTH);
Main.add(PanelB, BorderLayout.CENTER);
Main.add(PanelC, BorderLayout.SOUTH);
Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main.setTitle("GAME TITLE"); //ADD THIS LATER
Main.pack();
Main.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae)
{
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button)
{
Introduction.Intro1(); //THESE LINE RIGHT HERE
return null; //THESE LINE RIGHT HERE
}
}
}
public static void main(String[] args)
{
new Start();
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Introduction
{
private JFrame Main;
private JPanel PanelD;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public void Intro()
{
Image = new ImageIcon(getClass().getResource("guy.jfif"));
ImageL = new JLabel(Image);
PanelD = new JPanel();
PanelD.setBorder(BorderFactory.createEmptyBorder(0,100,10,100));
PanelD.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelD.add(ImageL);
PanelD.setVisible(true);
Main.add(PanelD, BorderLayout.NORTH);
}
}
EDIT: So I made another method in the Introduction class where I added this line of code, it managed to fix the error, however, the panel isn't being saved and my JFrame is outputting blank.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}
If you are looking to initialize the Introduction class in main method of Start class, You can add belo code in main method after Start()
Introduction M = new Introduction();
You main method becomes :
public static void main(String[] args)
{
new Start();
Introduction M = new Introduction();
m.Intro
}
Looking at this set of code, It looks like there is incompatible issue, as you have declare JFrame as return type, while you are returning instance of Introduction.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}

How would i make a button in Java onto a JFrame

I am coding on Android and using terminal IDE to compile my code. However, for some reason when I compile, it says the Button code is wrong.
package BlahBlahBlah;
import javax.swing.JButton;
import javax.swing.JFrame;
public class blahblahblah extends JFrame{
JFrame w = new JFrame();
w.setVisible(true);
w.setSize(1366, 768);
Button sb = new JButton();
sb.addListener(this);
add(sb);
}
It keeps saying illegal start of type or identifier expected which as you see there's a identifier in the Button.
Button sb = new JButton();
A "Button" without the "J" is not the same as a "JButton".
In Swing components start with a "J".
You should put your code inside a method.
public class blahblahblah extends JFrame{
public static void main(String[] args) {
JFrame w = new JFrame();
w.setVisible(true);
w.setSize(1366, 768);
Button sb = new JButton();
sb.addListener(this);
add(sb);
}
}
You can either remove sb.addListener(this); or implement our class with ActionListener and add it's umimplemented methods to your class. Also, do some changes like:
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class blahblahblah extends JFrame implements ActionListener
{
public blahblahblah()
{
JFrame w = new JFrame();
w.setVisible(true);
w.setSize(1366, 768);
JButton sb = new JButton();
sb.addActionListener(this);
add(sb);
}
public static void main(String[] args) {
blahblahblah b = new blahblahblah();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Your Stuff
}
}

Java - a simple PlayerAction counter to practice object-oriented programming

I am learning the basics of Java and decided to practice working on objects, by making a simple program which I called a 'PlayerAction Counter'. It does nothing more that counting an 'action' which is fired by clicking '+1' button and additionally reset the counter, when the 'Reset' button is clicked. For this case I've made a Application.java which holds the main method and launches the program, Interface.java for GUI, EventHandling.java for events and Person.java which holds interface components and methods to change their state. It looks like this:
My idea was to create the window in Interface class and set it's layout, then create two Person objects called PlayerOne and Player Two. The Person class creates two labels and two buttons and set a label of one by a constructor parameter.
I've managed to add these two objects' elements to the GUI by getters and it looks just fine. I added ActionListener to both buttons in Person class and it also works just fine.
I am stuck on getting back to Person fields and methods from EventHandling class. I've created a setValueLabel() which increases by one a value of 'action' and sets it on the label, but I have to idea how to launch the method from another class. I can not make another object inside (throws StackOverFlow error), but should it not somehow refer to those two made in Interface class?
Here is the code:
Application.java
import java.awt.EventQueue;
public class Application {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Interface().setVisible(true);
}
});
}
}
Interface.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
public class Interface extends JFrame {
private JLabel titleLabel;
private JPanel mainPanel;
private JPanel leftPanel, rightPanel;
private JSeparator separator;
Person PlayerOne = new Person("PlayerOne");
Person PlayerTwo = new Person("PlayerTwo");
public Interface() {
//Basic init
setTitle("PlayerAction Counter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
//Layout
mainPanel = new JPanel();
add(mainPanel);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
leftPanel = new JPanel();
rightPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
leftPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
mainPanel.add(leftPanel, BorderLayout.WEST);
separator = new JSeparator(SwingConstants.VERTICAL);
mainPanel.add(separator, BorderLayout.CENTER);
titleLabel = new JLabel("PlayerAction Counter");
mainPanel.add(titleLabel, BorderLayout.PAGE_START);
//Components init
PlayerTwo.getPersonLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getPersonLabel());
PlayerTwo.getValueLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueLabel());
PlayerTwo.getValueUpButton().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueUpButton());
PlayerTwo.getValueResetButton().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueResetButton());
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
rightPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
mainPanel.add(rightPanel, BorderLayout.EAST);
PlayerOne.getPersonLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getPersonLabel());
PlayerOne.getValueLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueLabel());
PlayerOne.getValueUpButton().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueUpButton());
PlayerOne.getValueResetButton().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueResetButton());
pack();
}
}
Person.java
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JLabel;
public class Person {
private JLabel personLabel;
private JLabel valueLabel;
private JButton valueUpButton;
private JButton valueResetButton;
private int actionValue = 0;
public Person(String s) {
personLabel = new JLabel(s);
setComponents();
}
private void setComponents() {
valueUpButton = new JButton("+1");
valueResetButton = new JButton("Reset");
valueLabel = new JLabel(""+actionValue);
EventHandling eventHand = new EventHandling(valueUpButton, valueResetButton);
valueResetButton.addActionListener(eventHand);
valueUpButton.addActionListener(eventHand);
}
public void setValueLabel() {
actionValue++;
valueLabel.setText("" +actionValue);
}
public JLabel getPersonLabel() {
return personLabel;
}
public JLabel getValueLabel() {
return valueLabel;
}
public JButton getValueUpButton() {
return valueUpButton;
}
public JButton getValueResetButton() {
return valueResetButton;
}
}
EventHandling.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
public class EventHandling implements ActionListener {
private JButton valueUpButton;
private JButton valueResetButton;
public EventHandling(JButton valueUpButton, JButton valueResetButton) {
this.valueUpButton = valueUpButton;
this.valueResetButton = valueResetButton;
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == valueUpButton) {
//no idea how to launch Person.setValueLabel();
//creating new Person object throws StackOverFlow error and I doubt that's the way
}
else if (event.getSource() == valueResetButton) {
}
}
}
I do hope my issue is understandable. The question is: how should it be done?
Please keep in mind that I am a complete rookie and try to learn OOP, but am very confused by it. Please point my mistakes in thinking and the code.
Any feedback will be greatly appraciated.
Thank you.

JButton stops working after several clicks with nothing else changed

I am trying to create a piano program where you click the key and using an actionlistener is plays the note from the jfugue library. For some reason after about 18 clicks without changing anything the buttons stop working. I cut down the code to analyze why this might happen, thus only two notes.
Thanks in advance for any advice!
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JComponent;
import java.awt.Color;
import javax.swing.JLayeredPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.*;
import org.jfugue.*;
public class ChordPlayer2 extends JComponent{
public ChordPlayer2(){
final Player player = new Player();
JFrame frame = new JFrame();
JButton cButton, csharpButton;
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(0, 0);
buttonPanel.setSize(1700, 1000);
csharpButton = new JButton("");
csharpButton.setLocation(100, 150);
csharpButton.setSize(100,520);
buttonPanel.add(csharpButton);
cButton = new JButton("");
cButton.setLocation(0, 150);
cButton.setSize(160, 800);
buttonPanel.add(cButton);
class cClicker implements ActionListener {
public void actionPerformed(ActionEvent event) {
player.play("C");
}
}
class csClicker implements ActionListener {
public void actionPerformed(ActionEvent event) {
player.play("C#");
}
}
ActionListener c = new cClicker();
cButton.addActionListener(c);
ActionListener cs = new csClicker();
csharpButton.addActionListener(cs);
buttonPanel.setOpaque(true);
//return buttonPanel;
frame.add(buttonPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1700, 1000);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
//JFrame.setDefaultLookAndFeelDecorated(true);
ChordPlayer2 demo = new ChordPlayer2();
}
}
This is a known bug in JFugue:
https://code.google.com/p/jfugue/issues/detail?id=49
The most recent version is claimed to fix this:
https://code.google.com/p/jfugue/downloads/detail?name=jfugue-4.1.0-20120125.jar&can=2&q=

AWT button not clickable in VLCJ

I have created a simple VLCJ project that consists of a simple embedded player and a button to exit.
The code is as follows:
package test;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class Demo {
private final JFrame frame;
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JPanel videoPane;
private JPanel buttonPane;
private Button exitButton;
private ActionListener a;
private static String vlc_location = "C:\\Program Files\\VideoLAN\\VLC";
public static void main(String[] args) {
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), vlc_location);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().run();
}
});
}
public Demo() {
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
a = new MyActionListener();
exitButton = new Button("Exit");
exitButton.setActionCommand("Exit app");
exitButton.addActionListener(a);
buttonPane = new JPanel();
buttonPane.setLayout(new BorderLayout());
buttonPane.setBackground(Color.black);
buttonPane.add(exitButton, BorderLayout.CENTER);
videoPane = new JPanel();
videoPane.setLayout(new BorderLayout());
videoPane.setBackground(Color.black);
videoPane.add(mediaPlayerComponent, BorderLayout.CENTER);
videoPane.add(buttonPane, BorderLayout.PAGE_END);
frame = new JFrame("vlcj demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.setSize(1200, 800);
frame.setContentPane(videoPane);
frame.setVisible(true);
}
public void run() {
mediaPlayerComponent.getMediaPlayer().playMedia(video_file);
}
class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
String s = arg0.getActionCommand();
if (s.equals("Exit")) {
System.exit(0);
}
}
}
}
The problem is that the button does show up but it cannot be clicked. When i removed the videoPane, it was back to clickable! Any ideas if I'm missing something?
I am using the version 2.1.0 for vlcj.
Thanks!
Thanks MadProgrammer for your advise. I went on to think about it and tried commenting away the line of code in run(). The JButton came back!
However, when i un-commented the code in run(), the JButton disappeared. I was thinking maybe the Swing runnable was causing issue with the creation of the JButton.
Hence, what i did was to comment away the whole Swing runnable and just use:
final Demo demo = new Demo();
demo.run();
The demo can now play video and display the Exit button, thanks!

Categories

Resources