I am still learning how to code in java and I could use a bit of help right now.
This is the current code I wrote. As you can see, it's a simple panel with a bunch of buttons and a slider. I want to make a different console output whenever I hit a different button. So if I hit Back, it's supposed to write Back in the console. If I scroll a bit on the slider, it's supposed to write the new value in the console. Stuff like that. I know it has to be done with actionListener and actionPerformed but after some experimenting I couldn't get it to work.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui implements ActionListener {
// Adding all the goods
JFrame frame;
JPanel panel;
JButton endButton;
JButton backButton;
JButton calcButton;
JSlider maxIterations;
JLabel view;
Gui() {
// General
this.frame = new JFrame("Trying my best, I swear");
this.frame.setSize(500, 500);
this.frame.setVisible(true);
this.panel = new JPanel();
// Buttons
this.backButton = new JButton("Back");
this.calcButton = new JButton("Calc");
this.endButton = new JButton("End");
this.panel.add(this.endButton);
this.panel.add(this.calcButton);
this.panel.add(this.backButton);
this.frame.add(this.panel);
// Label
JLabel label1 = new JLabel();
label1.setText("Space Holer");
panel.add(label1);
// Slider
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
panel.add(slider);
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
// Make the buttons do something
this.endButton.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
System.out.println("End");
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Gui m = new Gui();
}
}
You could...
Take advantage of the actionCommand property of the button, which is set to the ActionEvent when it's created. If you don't supply an actionCommand to the button yourself, it will default to the text value, so you could do something like
public class ButtonActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "Back":
System.out.println("Back");
break;
case "Calc":
System.out.println("Calc");
break;
case "End":
System.out.println("End");
break;
}
}
}
This is good if the ActionListener is external to the class where the buttons are defined, because you won't have access to the button references. It's also good, because you could have a number of buttons (including toolbar buttons and menu items) which do the same thing
You could...
Make use of the ActionListener's source property
public class ButtonActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == backButton) {
System.out.println("Back");
} else if (e.getSource() == calcButton) {
System.out.println("Calc");
} else if (e.getSource() == endButton) {
System.out.println("End");
}
}
}
This is useful if the ActionListener in defined as a inner class to the parent class from where the buttons are defined
You could...
Use an anonymous class registered directly against the button...
endButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("End");
}
});
This is good where the button does a single, isolated task
You could...
Make use of the Action API which allows you to define a self contained unit of work, which can be used by buttons to configure themselves completely from it. This is useful where you have a repeated action which can be executed from different locations of the UI, like a "open file" action contained in the menu bar, tool bar and some wizard. You can even use it with the key bindings API for extended functionality
See How to use actions for more details
Need to add ActionListener to all buttons,
calcButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("calcButton");
// calculation for slider.
}
});
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("backButton");
}
});
then u get the different console output.
Call setVisible on jframe after you placed all components into it.
Add ActionListener to each button. Add ChangeListener to slider as it cannot have ActionListener.
See full code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
public class Gui implements ActionListener {
// Adding all the goods
JFrame frame;
JPanel panel;
JButton endButton;
JButton backButton;
JButton calcButton;
JSlider maxIterations;
JLabel view;
Gui() {
// General
this.frame = new JFrame("Trying my best, I swear");
this.frame.setSize(500, 500);
this.panel = new JPanel();
// Buttons
this.backButton = new JButton("Back");
this.calcButton = new JButton("Calc");
this.endButton = new JButton("End");
this.panel.add(this.endButton);
this.panel.add(this.calcButton);
this.panel.add(this.backButton);
this.frame.add(this.panel);
// Label
JLabel label1 = new JLabel();
label1.setText("Space Holer");
panel.add(label1);
// Slider
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
panel.add(slider);
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
// Make the buttons do something
this.endButton.addActionListener(this);
this.backButton.addActionListener(this);
this.calcButton.addActionListener(this);
slider.addChangeListener(e -> {
Object source = e.getSource();
if (source instanceof JSlider) {
int value = ((JSlider) source).getValue();
System.out.println(value);
}
});
frame.pack();
this.frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source instanceof JButton) {
String text = ((JButton) source).getText();
System.out.println(text);
}
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Gui m = new Gui();
}
}
Related
So I have 1 class, with a radio button and 1 class, that will create an applet depending on the outcome of the Radio Button. I don't know how to make the graphics run depending on an if/else statement. All help will be greatly appreciated.
Radio Button Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton extends JPanel {
static JFrame frame;
JLabel pic;
RadioListener myListener = null;
protected JRadioButton displacement;
protected JRadioButton accel;
protected JRadioButton time;
public RadioButton() {
// Create the radio buttons
displacement = new JRadioButton("Displacement");
displacement.setMnemonic(KeyEvent.VK_N);
displacement.setSelected(true);
//Displacement Button, set to automatically be clicked
accel = new JRadioButton("Acceleration");
accel.setMnemonic(KeyEvent.VK_A);
accel.setActionCommand("acceleration");
//Acceleration Button
time = new JRadioButton("Change in time");
time.setMnemonic(KeyEvent.VK_S);
time.setActionCommand("deltaT");
//The change in time button
// Creates the group of buttons
ButtonGroup group = new ButtonGroup();
group.add(displacement);
group.add(accel);
group.add(time);
myListener = new RadioListener();
displacement.addActionListener(myListener);
accel.addActionListener(myListener);
time.addActionListener(myListener);
// Set up the picture label
pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg")); //Set the Default Image
pic.setPreferredSize(new Dimension(177, 122));
// Puts the radio buttons down
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.add(displacement);
panel.add(accel);
panel.add(time);
setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(pic, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
//Listening to the buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand()
+ ".jpg"));
}
}
public static void main(String s[]) {
frame = new JFrame("∆x = Vavg * time");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
If/Else Statements class:
import java.lang.Object;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.*;
public class RadioButtonMain extends RadioButton {
public static void main(String [ ] args) {
new RadioButtonMain().doMain();
}
public void doMain() {
if ( displacement.isSelected()) {
//option 1 for applet
}
if ( accel.isSelected()) {
//Option 2 for applet
}
else {
//Option 3 for applet
}
}
}
How would I get the graphics to run based on whether or not the variables accel and displacement are pressed? Thanks.
Remember, a GUI is an event driven environment, things don't run within a linear manner. Instead of trying run a method yourself, you need to use a callback or listener of some kind which will tell you when the state of the program/buttons change...
When the JRadioButton actionPerformed event is raised, you need to call another method which provides information about what has occurred. You can then override these methods in your RadioButtonMain class and take action when they are called
This is very similar to an Observer Pattern
What is the best way to define the action a button will perform in the code? I want to be able to have one button do one action and the next button do a different action. Is this possible?
You can add action listener like this.
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
You can do this way.
JButton button = new JButton("Button Click");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//do your implementation
}
});
JButton subclasses AbstractButton, which has a method, addActionListener. By calling this method and passing it the action listener you wish to add, the action listener is added and will be called once an action is fired, either programatically, or by way of user interaction. Other listners can be added such as mouse listeners.
One way is to have your class implement ActionListener. Then implement the actionPerformed() method. Here is an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Driver extends JFrame implements ActionListener {
private static final long serialVersionUID = 3549094714969732803L;
private JButton button = new JButton("Click");
public Driver(){
JPanel p = new JPanel(new GridLayout(3,4));
p.add(button);
button.addActionListener(this);
add(p);
}
public static void main(String[] args){
Driver frame = new Driver();
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked me!");
}
}
I don't know how I can add mouseListener (mouseClicked, mouseEntered, etc...) to my actionPerformed. I learned only how to add action from JButton but mouseListener is in JLabel.
Here it's this code:
test = new JLabel (ikona);
test.setBounds(200, 200, 100, 100);
add(test);
test.addMouseListener(new MouseListener()
{
public void mouseClicked(MouseEvent e) {
System.out.println(ikona2);
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
and:
public void actionPerformed(ActionEvent arg0)
{
Object Zrodlo = arg0.getSource();
if (Źródło==przycisk)
{
wyswietlacz.setText(new Date().toString());
//System.out.println(new Date());
}
else if (Zrodlo==przycisk2)
{
dispose();
}
else if (Zrodlo==przycisk3)
{
wyswietlacz.setText(new Date().toString());
}
else if (Zrodlo==test)
{
wyswietlacz.setText("");
}
"przycsik, przycisk2, przycisk3" are JButton, I try doing something with JLAbel ("test") but I don't have idea how solve this.
P.S. sorry for my english...
EDIT: For JButton I use this to see action in mine JFrame:
public void actionPerformed(ActionEvent arg0)
{
Object Zrodlo = arg0.getSource();
if (Źródło==przycisk)
{
wyswietlacz.setText(new Date().toString());
//System.out.println(new Date());
}
else if (Źródło==przycisk2)
{
dispose();
}
I want to do same with my JLabel and mouseListener. I want see interaction which mouse/cursor which MouseListener. I want to add icon(gif) to JLabel and use MouseListener to change icon1 to icon2 example mouseClicked or mousePressed. If I use:
test.addMouseListener(new MouseListener()
{
public void mouseClicked(MouseEvent e) {
System.out.println(ikona2);
}
I only see source to my "ikona2" in my Eclipse Console. I want to see action in my JFrame.
A listener is a type of callback that follows the observer pattern, something happens, you get notified.
There are many types of listeners for many different types of events. Buttons have an ActionListener which is triggered by, at least, the user clicking or pressing enter or space while the button has focus.
A label does not have an ActionListener, a label is a static component for all intended purposes, however, a label does have a MouseListener...
MouseListener listener = ...;
JLabel label = new JLabel("This is a clickable lable");
label.addMouseListener(listener);
This will allow you to monitor when a mouse click occurs on the label.
Take a look at:
How to write a mouse listener
Writing Event Listeners
Creating a GUI with Swing
For more details
Not sure I understand the question but you can paint a JButton like a JLabel but still have the ActionListener work like a button:
JButton button3 = new JButton("Label Button");
button3.setBorderPainted(false);
button3..setFocusPainted(false);
button3.setContentAreaFilled(false);
button3.addActionListener( ... );
You can't combine those two action listeners (MouseListener & ActionListener). You can add the MouseListener on a JLabel as well on a JButton. Adding an ActionListener to the JLabel isn't allowed anyway. What you can do is to create one MouseListener which handles the events for the JLabel as well for the JButton. Here is an example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JLabel;
public class MouseListenerTest extends javax.swing.JFrame {
private static final long serialVersionUID = 3109442737770802801L;
public static void main(String[] args) {
MouseListenerTest t = new MouseListenerTest();
t.setLayout(new BorderLayout());
MyMouseListener mouseListener = new MyMouseListener();
JLabel l = new JLabel("JLabel");
l.setPreferredSize(new Dimension(200, 100));
JButton b = new JButton("JButton");
b.setPreferredSize(new Dimension(200, 100));
l.addMouseListener(mouseListener);
b.addMouseListener(mouseListener);
t.add(l, BorderLayout.CENTER);
t.add(b, BorderLayout.SOUTH);
t.pack();
t.setVisible(true);
}
}
class MyMouseListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
Object o = e.getSource();
if (o instanceof JButton) {
System.out.println("JButton");
} else if (o instanceof JLabel) {
System.out.println("JLabel");
}
}
#Override
public void mousePressed(MouseEvent e) {/* TODO */
}
#Override
public void mouseReleased(MouseEvent e) {/* TODO */
}
#Override
public void mouseEntered(MouseEvent e) {/* TODO */
}
#Override
public void mouseExited(MouseEvent e) {/* TODO */
}
}
Me and a friend are trying to make an mp3 player with buttons in java, however once the first button is clicked it resizes all butttons on the second menu.
Any information on how to keep the buttons from rezising would be greatly appreciated.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Player extends JFrame {
class CustomPanel extends JPanel{ //create image
public void paintComponent (Graphics painter){
Image pic = Toolkit.getDefaultToolkit().getImage("playerBase.jpg");
if(pic != null) painter.drawImage(pic, 0, 0, this);
}
}
public static void main(String[] args) {
Player gui = new Player();
gui.go();
}
public void go() {
JFrame frame = new JFrame("MP3 Player."); //Creates window.
CustomPanel base = new CustomPanel(); //Makes the image into a panel.
JButton button1 = new JButton("Artists");
JButton button2 = new JButton("Genres");
JButton button3 = new JButton("Songs");
JButton button4 = new JButton("TEST");
JButton button5 = new JButton("TEST");
button1.setHorizontalAlignment(SwingConstants.LEFT);
button2.setHorizontalAlignment(SwingConstants.LEFT);
button3.setHorizontalAlignment(SwingConstants.LEFT);
button4.setHorizontalAlignment(SwingConstants.LEFT);
button5.setHorizontalAlignment(SwingConstants.LEFT);
button1.addActionListener(new Button1Listener());
button2.addActionListener(new Button2Listener());
button3.addActionListener(new Button3Listener());
button4.addActionListener(new Button4Listener());
button5.addActionListener(new Button5Listener());
base.add(button1);
base.add(button2);
base.add(button3);
base.add(button4);
base.add(button5);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(304, 360);
frame.setResizable(false);
frame.add(base);
frame.setVisible(true);
button1.setSize(280, 30);
button1.setLocation(10,10);
button1.setBackground(Color.BLACK);
button1.setForeground(Color.white);
button2.setSize(280, 30);
button2.setLocation(10,40);
button2.setBackground(Color.BLACK);
button2.setForeground(Color.white);
button3.setSize(280, 30);
button3.setLocation(10,70);
button3.setBackground(Color.BLACK);
button3.setForeground(Color.white);
button4.setSize(280, 30);
button4.setLocation(10,100);
button4.setBackground(Color.BLACK);
button4.setForeground(Color.white);
button5.setSize(280, 30);
button5.setLocation(10,130);
button5.setBackground(Color.BLACK);
button5.setForeground(Color.white);
}
//These are the actions for the 5 buttons.
//Need to get buttons straight once first button is clicked
class Button1Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) {
JButton clickedButton = (JButton) event.getSource();
clickedButton.setSize(280, 30);
clickedButton.setLocation(10,10);
clickedButton.setBackground(Color.BLACK);
clickedButton.setForeground(Color.white);
String buttonText = clickedButton.getText();
if (buttonText.equals("Artists")) {
System.out.println("Artists");
clickedButton.setText("Back");
}
else if (buttonText.equals("Back")) {
System.out.println("Back");
}
}
}
}
//these are just place holders for the other buttons.
class Button2Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Genres");
}
}
class Button3Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Songs");
}
}
class Button4Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("TEST");
}
}
class Button5Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("TEST");
}
}
}
Set the layout Manager to null on your CustomPanel base.
base.setLayout(null);
If you want to force the size and location of your components (using setBounds()), then you need to remove the layout manager.
However, LayoutManagers provide better UI experience across different platforms as they will adapt to differences. LayoutManager's perform the sizing and positionning of the components based on preferredSize and constraints. If you have never used them or heard from them, you should really consider looking into them: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
well, I didn't see a menu code. However, by default, the Layout manager for Panel is Flow Layout. Since you did not specify any layout, Flow Layout is assumed, and any sizing you specify will largely be ignored.
So, as Guillaume suggests, set it to null, so you can position things absolutely. Or use more complex layouts depending on your needs. Have a look at how to use layout managers in the swing tutorial. GridBagLayout is the most complex (difficult to use), unless you use some sort of gui builder. Other candidates are BorderLayout, GridLayout among others. Read through the examples to see which one fits your case.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Menu extends JFrame implements ActionListener{
// Create the components and global variables
JButton newGameButton = new JButton("New Game");
JButton instructionGameButton = new JButton("Instructions");
JButton exitButton = new JButton("Exit");
JLabel mylabel = new JLabel("Welcome to Blackjack");
public Menu()
{
// Create the window
super("ThreeButtons");
setSize(300,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//Creating the container for the components and set the layout
Container content = getContentPane();
FlowLayout layout = new FlowLayout();
content.setLayout(layout);
//Adding the event listener
newGameButton.addActionListener(this);
instructionGameButton.addActionListener(this);
exitButton.addActionListener(this);
//Adding of components
content.add(mylabel);
content.add(newGameButton);
content.add(instructionGameButton);
content.add(exitButton);
setContentPane(content);
}
//Add the event handler
public void actionPerformed(ActionEvent event)
{
if (event.getActionCommand()=="New Game")
new lol4();
if (event.getActionCommand()=="Instructions")
//new Instructions();
if (event.getActionCommand()=="Quit ?")
System.exit(0);
}
public static void main (String[] args)
{
//Create an instance of my class
new Menu();
}
}
Exit does not seem to work
First of all, never use "==" to compare Strings. Use the equals(...) method.
Exit does not seem to work
Why do you check for "Quit ?"?
The action command defaults to the text of the button, unless you set the command explicitly.
I never liked the "switch-board" action listeners where the listener tries to do everything and risks doing nothing due to hard to fix bugs. Better I think to use anonymous inner classes either to hold simple code themselves, or if more complex to route code to other methods, or if still more complex, to call a Controller's method.
For example:
newGameButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGameActionPerformed(); // delegate this to a class method
}
});
instructionGameButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// call a controller object's methods
if (myController != null) {
myController.instructionGameAction();
}
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.dispose(); // simple code can be called in-line
}
});
and elsewhere in the class:
private void newGameActionPerformed() {
// TODO add some code here!
}
public void setController(MyController myController) {
this.myController = myController;
}