I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?
Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
See How to Write an Action Listener.
I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.
Hope this helps
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});
Related
I'm trying to create a custom component in NetBeans which contains 2 buttons on a panel.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class CustomComponent extends JPanel {
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
public CustomComponent() {
setLayout(new FlowLayout());
add(button1);
add(button2);
button1.setSize(100, 30);
button2.setSize(100, 30);
}
}
When I use this custom component on another project's JFrame (using GUI designer), those two buttons need to have two different ActionPerformed events and those events must be shown in the Netbean's event list. is that possible to do?
(Currently, I only see the events owned by the JPanel.)
Thanks in advance
As per the links above, you can add an action listener like below. This example is for a generic ActionEvent, but you can modify the code to other types of events as well:
//The button to add an event to
JButton test = new JButton();
//The first option
test.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Action performed");
}
});
//The second option. This only works on Java 8 and newer
test.addActionListener((ActionEvent e) ->
{
System.out.println("Action performed");
});
//Or a simplified form for a single call
test.addActionListener(e -> System.out.println("Action performed"));
And a working example in your case:
public CustomComponent() {
setLayout(new FlowLayout());
add(button1);
add(button2);
button1.setSize(100, 30);
button2.setSize(100, 30);
//Add events
button1.addActionListener(e -> System.out.println("Button 1 action performed"));
button2.addActionListener(e -> System.out.println("Button 2 action performed"));
}
instead of passing listeners through the constructor, I have created another setter, because the GUI does not support that.
public void setListners(ActionListener btn1ActionListner, ActionListener btn2ActionListner){
button1.addActionListener(btn1ActionListner);
button2.addActionListener(btn2ActionListner);
}
on the other project
public NewJFrame() {
initComponents();
ActionListener al1 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button 1");
}
};
ActionListener al2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button 2");
}
};
customComponent1.setListners(al1, al2);
}
How can I code a button that, when clicked, closes the current JFrame and opens a new one?
This is what I have so far, but the old frame stays open:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
practise1 s = new practise1();
s.setVisible(true);
}
I have tried using .close() after the first { but it gives me an error.
If you plan on using the originial JFrame later, use setVisible(false) on the original JFrame. If you plan on closing the first JFrame and never reusing it, you can use dispose().
public void actionPerformed(ActionEvent e)
{
if(e.getSource () == button)
{
test = new JFrame();
test.setSize(300,300);
test.setVisible (true);
this.dispose();
}
}
Dispose AFTER creating the new Frame.
Thanks for the help everyone. I got it working using the this.dispose(); method
Lets say current Frame is FirstFrame
and clicking on JButton goes to NewFrame
import javax.swing.*;
public class FirstFrame extends Jframe implements ActionListener{
JButton button;
public FirstFrame(){
setVisible(true);
setSize(500,500);
button=new JButton("Click me");
button.addActionListner(this);
add(button);
}
public static void main(String[] args)
{
new FirstFrame();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
NewFrame nf=new NewFrame(); // Clicking on the Button will OPEN new Frame in NewFrame.java file
dispose(); //this method will close the FirstFrame
}
}
}
you just put this in your code :
(the exemple here i JButton to do this with the ActionPerformed method)
/**********************************************************************/
private void openBTNActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
FrameTarget t = new FrameTaregt();
t.setVisible(true);
//set the size : 1250 pixels de width and 720 pixels de height
t.setSize(1250, 720);
//make the frame in the center wuth this
t.setLocationRelativeTo(null);
t.setResizable(true);
}
I am making a jFrame that represents a go board. I want a click of a given button to change the color to represent placing a piece on the board. In my code below, I show a method that should be able to change the color of a button (it only changes the background of the whole frame). First question: Why is the button color not changing (this is not my bigger problem about changing color after click occurs, my preliminary issue is that the button color will not change). I do not get any errors, the button color just never changes.
public static void showBoard()
{
JFrame frame2 = new JFrame("Go Board");
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
for(int i = 19*19; i > 0; i--)
{
JButton firstButton = new JButton("");
firstButton.setBackground(Color.blue);
firstButton.setVisible(true);
firstButton.setContentAreaFilled(true);
firstButton.setOpaque(true);
firstButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
System.out.println("ddsd");
//int[] arr = findMove(0);
}
});
}
});
frame2.getContentPane().add(firstButton);
}
frame2.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
frame2.setLayout(new GridLayout(19,19));
frame2.pack();
frame2.setVisible(true);
}
My second problem, getting the button to change color after being clicked, is presumably affected by the fact that I am not able to even change the button color. To get the button to change color after a click, I plan to put the button color change code inside the action listener.
So in summation, how can I change the color of the button after a click?
ANSWER:
The problem was the look and feel of my mac. Look to the checked answer for how to fix this if you have similar problem on your mac.
You don't need to call SwingUtilities.invokeLater inside your ActionListener, as the actionPerformed(ActionEvent) method will be invoked on the Event Thread already.
The following example demonstrates how to change a Button's background color when it's clicked on:
public class ChangeButtonColor implements Runnable {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
System.err.println("Cannot set LookAndFeel");
}
SwingUtilities.invokeLater(new ChangeButtonColor());
}
#Override
public void run() {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
JButton button1 = new JButton("click me");
JButton button2 = new JButton("click me too");
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
((Component)source).setBackground(Color.RED);
}
}
};
button1.addActionListener(listener);
button2.addActionListener(listener);
frame.add(button1);
frame.add(button2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Please note that the ActionListener used here can be used for all buttons. There is no need to create a new instance of it for every button.
I have created a frame in Java which has some textfields and buttons in it. Assuming that user wants more textfields (for example to add more data), I want to put a button and when a user clicks the button, then a new textfield should appear. then user can fill data in it and again by clicking that button another textfield should appear.
How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?
Thank you !
It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameExample
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public JFrameExample()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add JTextField");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate(); // For JDK 1.7 or above.
//frame.getContentPane().revalidate(); // For JDK 1.6 or below.
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new JFrameExample().displayGUI();
}
});
}
}
Supposing that you have a main container called panel and a button variable button which is already added to panel, you can do:
// handle the button action event
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// create the new text field
JTextField newTextField = new JTextField();
// add it to the container
panel.add(newTextField);
panel.validate();
panel.repaint();
}
});
When adding the new text field, you may need to mention some layout related characteristics, depending on the layout manager you are using (for instance if you use GridBagLayout, you will need to specify the constraints).
i am trying to make an actionListener on a button in another button which has also an actionlistener and i just couldn't figure it out for some way. I am trying to make an action on the 2nd button but i couldn't figure it out.If anyone helps me i'd appreciate! here is the code below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class basic implements ActionListener{
public static void main(String[] args) {
basic process = new basic ();
}
public basic(){
JFrame fan = new JFrame("Scheme");
JPanel one = new JPanel(new BorderLayout());
fan.add(one);
JPanel uno = new JPanel();
uno.setLayout(new BoxLayout(uno, BoxLayout.Y_AXIS));
JButton addB = new JButton("first choice");
addB.setAlignmentX(Component.CENTER_ALIGNMENT);
uno.add(addB);
addDButton.setActionCommand("hehe");
addDButton.addActionListener(this);
one.add(uno,BorderLayout.CENTER);
fan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fan.setSize(500,700);
fan.setLocationByPlatform(true);
fan.setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
JPanel markP = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,20));
JDialog dialog = new JDialog((JFrame)null);
dialog.getContentPane().add(markP,BorderLayout.CENTER);
if (evt.getActionCommand().equals("hehe")) {
JLabel title = new JLabel("Proceed");
title.setFont(new Font("Arial",Font.BOLD,15));
markP.add(title,BorderLayout.NORTH);
JButton exit = new JButton("Exit");
markP.add(exit);
//here i want to create another actionListener on the exit button only without affecting the other content which is in the button "addB " so that when i click on the addB button the J dialog pops up, and than when i click on exit button the program will return to the menu.I couldn't figure it out.
dialog.toFront();
dialog.setModal(true);
dialog.pack(); //
dialog.setLocationRelativeTo(null); //
dialog.setVisible(true);
}
// here the code goes on but the problem is that of the actionListener which is concerned.
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// you code here
}
});
You should use better variables names. It is not easy to follow your code
You could use the same ActionListener if you check the source of the action using
if (evt.getSource().equals(addDButton) { original code }
else { code for the other button }