How do i add an action to a JFrame JButton? - java

I have a JFrame gui im making and I need help.
Im trying to find out how to add a action to my button.
as in using it in a "if" statement or make i print something out when you push it.
thanks!
code:
package agui;
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
JButton button = new JButton("click me");
JPanel panel = new JPanel();
panel.add(button);
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}

You want the "addActionListener" method, something like:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked the button");
}
});

Related

Simple Java GUI Program

My JPanel and JTextField are for some reason not appearing. The programs only task is to add a number to the counter every time the button is clicked. No compiling errors nor console issues. Simply not showing up??
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Swing
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
final JFrame mainFrame = new JFrame ("Counter (Program 1/2)");
mainFrame.setVisible(true);
mainFrame.setSize(400, 200);
mainFrame.setLayout(new BorderLayout());
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton countButton = new JButton("Count up");
mainFrame.add(countButton, BorderLayout.SOUTH);
countButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextField clicks = new JTextField(BorderLayout.CENTER);
JPanel firstPanel = new JPanel();
mainFrame.add(firstPanel);
mainFrame.add(clicks, BorderLayout.NORTH);
int counter = 1;
counter++;
String textField = String.valueOf(counter);
clicks.setText(textField);
}
});
}
});
}
}
Don't add the JTextField and JPanel inside the ActionListener. This makes no sense since you'll be re-adding new components each time the button is pressed. Instead add them on GUI creation, before calling setVisible(true) on the GUI. Then update the text field's text in the ActionListener.
As a side recommendation: try to make your class more object oriented by giving it fields, a constructor, and getting most all of that code out of the static main method.
Your mistakes:
Add clicks and firstpanel to the frame in run method, not in the actionPerformed
BorderLayout.CENTER should be pass as a parameter to add method, not to the text field constructor.
Define count as static. This is not the best way but in your situation it is the easiest way.
Call mainFrame.setVisible(true); after you added all your components.
Here is the working code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Swing {
public static int counter = 1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame mainFrame = new JFrame("Counter (Program 1/2)");
mainFrame.setSize(400, 200);
mainFrame.setLayout(new BorderLayout());
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton countButton = new JButton("Count up");
mainFrame.add(countButton, BorderLayout.SOUTH);
final JTextField clicks = new JTextField(String.valueOf(counter));
JPanel firstPanel = new JPanel();
mainFrame.add(firstPanel, BorderLayout.CENTER);
mainFrame.add(clicks, BorderLayout.NORTH);
countButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
String textField = String.valueOf(counter);
clicks.setText(textField);
}
});
mainFrame.setVisible(true);
}
});
}
}

how to align buttons in the middle java

I am a beginner in Java, but somehow have a bit of knowledge but still beyond. I wanted to ask , how do align buttons in this main menu I just created. The buttons are somehow aligned horizontally.
This is my code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class mainmenu extends JFrame
{
JButton b1;
JLabel l1;
JButton b2;
public mainmenu() {
setResizable(false);
setLocation(100, 100);
setSize(500, 500);
setVisible(true);
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Master Boat\\Desktop\\PH\\BG HOROR.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
b2=new JButton(" EXIT! ");
b1.addActionListener(new btnFunc());
background.add(l1);
background.add(b1);
background.add(b2);
}
public void armaged() {
add(new gamesamplingbeta());
}
public static void main(String args[])
{
new mainmenu();
}
public class btnFunc implements ActionListener {
public void actionPerformed (ActionEvent e) {
}
}
public class btnFunc2 implements ActionListener {
public void actionPerformed2 (ActionEvent e) {
System.exit(1);
}
}
}
You should take a look at Swing Layouts for a whole bunch of different layout managers that allow you to position your components in a bunch of different ways.
The one I believe you should be using for this question is the Box Layout if you would like your buttons centered vertically.
Here is an example of one.
import javax.swing.*;
import java.awt.*;
public class MainFrame
{
JFrame mainFrame = new JFrame("Main Frame");
JPanel mainPanel = new JPanel();
JLabel label1 = new JLabel("Vertical Buttons");
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
public MainFrame()
{
label1.setAlignmentX(Component.CENTER_ALIGNMENT);
button1.setAlignmentX(Component.CENTER_ALIGNMENT);
button2.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(label1);
mainPanel.add(button1);
mainPanel.add(button2);
mainFrame.add(mainPanel);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
If you would like to add spacing in between any of the components, use a Rigid Area like so
container.add(component);
container.add(Box.createRigidArea(new Dimension(100, 100));
container.add(component1);

How to add a button to a JFrame Gui

I'm trying to add a button to a frame gui.
i tried making a panel and adding it to that, but it does not work.
please help!
here is my code:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button;
JPanel panel;
// my error lines are under the "panel" and "button"
// it says i must implement the variables. what does that mean???
panel.add(button);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
Change:
JButton button;
JPanel panel;
to:
JButton button = new JButton();
JPanel panel = new JPanel();
You can also pass a String value in JButton() constructor for that string value to be shown on the JButton.
Example: JButton button = new JButton("I am a JButton");
Example Code:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
// Create JButton and JPanel
JButton button = new JButton("Click here!");
JPanel panel = new JPanel();
// Add button to JPanel
panel.add(button);
// And JPanel needs to be added to the JFrame itself!
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
Output:
Note:
Create the JButton and JPanel using new JButton("..."); and new JPanel()
Add the JPanel to the JFrame's content pane using getContentPane().add(...);
If you can Change this Program, You can adjust the button place also
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class agui extends JFrame
{
agui()
{
setTitle("My GUI");
setSize(400,400);
setLayout(null);
JButton button = new JButton("Click Here..!");
button.setBounds(50,100,100,50); /*Distance from left,
Distance from top,length of button, height of button*/
add(button);
setVisible(true);
}
public static void main(String[] args)
{
JFrame agui = new agui();
}
}
Output

how to paint images on clicking button in frame?

I've made two buttons in frame .I want to know how to display different images on clicking different buttons?
is there another way out or i have to make panel?I am at beginner stage
package prac;
import java.awt.*;
import java.awt.event.*;
public class b extends Frame implements ActionListener{
String msg;
Button one,two;
b()
{ setSize(1000,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
one=new Button("1");
two=new Button("2");
add(one);
add(two);
one.addActionListener(this);
two.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
msg=e.getActionCommand();
if(msg.equals("1"))
{
msg="Pressed 1";
}
else
msg="pressed 2";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,300);
}
public static void main(String s[])
{
new b();
}
}
Use JLabel and change the icon when button is clicked.
Some points:
call setVisible(true) in the end after adding all the component.
use JFrame#pack() method that automatically fit the components in the JFrame based on component's preferred dimension instead of calling JFrame#setSize() method.
sample code:
final JLabel jlabel = new JLabel();
add(jlabel);
final Image image1 = ImageIO.read(new File("resources/1.png"));
final Image image2 = ImageIO.read(new File("resources/2.png"));
JPanel panel = new JPanel();
JButton jbutton1 = new JButton("Show first image");
jbutton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image1));
}
});
JButton jbutton2 = new JButton("Show second image");
jbutton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image2));
}
});
panel.add(jbutton1);
panel.add(jbutton2);
add(panel, BorderLayout.NORTH);

How to declare just one

I have the following working code with two buttons as event listeners. One button to get and display a Panel panel1 and the other to get and display another Panel panel2 removing the existing displayed panel. I created two actionPerformed methods for each button to carry out each other's tasks. I just want to make one to shorten the code but I don't know how to detect which button in a panel is displaying at compile time. Any help will be appreciated.
//Switching between panels (screens)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScreenDemo extends JFrame {
private JPanel panel1, panel2;
private JButton btn1, btn2;
JLabel label1 = new JLabel("Screen 1");
JLabel label2 = new JLabel("Screen 2");
public ScreenDemo() {
createPanel(); //Created at Line 14
addPanel(); //Created at Line 28
}
private void createPanel() {
//Panel for first screen
panel1 = new JPanel(new FlowLayout());
btn1 = new JButton("Move to Screen 2");
btn1.addActionListener(new addScreen1ButtonListener());
//Panel for second screen
panel2 = new JPanel(new FlowLayout());
btn2 = new JButton("Move to Screen 1");
btn2.addActionListener(new addScreen2ButtonListener());
}
private void addPanel() {
panel1.add(label1);
panel1.add(btn1);
panel2.add(label2);
panel2.add(btn2);
add(panel1); //Add the first screen panel
}
class addScreen1ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
getContentPane().removeAll();
getContentPane().add(panel2);
repaint();
printAll(getGraphics()); //Prints all content
}
}
class addScreen2ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ea) {
getContentPane().removeAll();
getContentPane().add(panel1);
repaint();
printAll(getGraphics()); //Prints all content
}
}
public static void main(String[] args) {
ScreenDemo screen = new ScreenDemo();
screen.setTitle("Switching Screens");
screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
screen.setSize(500, 500);
screen.setVisible(true);
}
}
implement ActionListener for your class, and try this code
ScreenDemo extends JFrame implements ActionListener
...
btn1.addActionListener(this);
btn2.addActionListener(this);
...
#override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource().equals(btn1)) {
...
}
else if(ae.getSource().equals(btn1)) {
...
}
}
you have to implements the class from ActionListener
than register JButton like : btn.addActionListener(this);
so close now, You just need to capture the event and get the source from where it is called like:
public void actionPerformed(ActionEvent ae) {
if(ae.getSource == btn1){
//shuffle panel from btn1
}
if(ae.getSource == btn2) {
//shuffle panel from btn2
}
}

Categories

Resources