I am supposed to implement an application to the user that has 2 buttons(Increment/decrement) and a label. When increment is pressed the number increases and decreases by one when decrement is pressed. The number starts at 50. I have it to where it shows the buttons and they work, but they work on 2 different variables, so their is 2 number printed to the screen instead of 1. My question is how can i make the button act on only one number. I have seen people use push etc. but is there another way to do this by passing in a value to both or something? Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonModifier
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
FlowLayout flow = new FlowLayout();
frame.getContentPane().setLayout(flow);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,300);
frame.setTitle("Button Modifier");
IncrementPanel panel = new IncrementPanel();
DecrementPanel panel1 = new DecrementPanel();
frame.add(panel);
frame.add(panel1);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DecrementPanel extends JPanel
{
private JButton button1;
private JLabel label;
private int number = 50;
public DecrementPanel()
{
button1 = new JButton("Decrement");
button1.addActionListener(new /*DecrementPanel.*/ButtonListener());
label = new JLabel("" + number);
this.add(button1);
this.add(label);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//int increment = 50;
number--;
label.setText("" + number);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class IncrementPanel extends JPanel
{
private JButton button;
private JLabel label;
int number = 50;
public IncrementPanel()
{
button = new JButton("Increment");
button.addActionListener(new ButtonListener());
label = new JLabel("" + number);
this.add(button);
this.add(label);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//int increment = 50;
number++;
label.setText("" + number);
}
}
}
I am supposed to implement an application to the user that has 2 buttons(Increment/decrement) and a label."
Then why do you have two?
IncrementPanel panel = new IncrementPanel();
DecrementPanel panel1 = new DecrementPanel();
Just use one and change the text on that one
Should be more like this
public class ButtonModifier extends JFrame {
private JLabel numberLabel = new JLable("50");
private JButton decrease = new JButton("-1");
private JButton increase = new JButton("+1");
private static int num = 50;
public ButtonModifier(){
setLayout(new GridLayout(1, 3));
add(increase);
add(numberLabel);
add(decrease);
increase.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
num++;
numLabel.setText("" + num);
}
});
decrease.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
num--;
numLabel.setText("" + num);
}
});
}
public static void main(String[] args){
JFrame frame = ButtonModifier();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,300);
frame.setTitle("Button Modifier");
frame.setVisible(true);
}
}
You should have one JLabel which will display the only number in your program.
Then your two buttons will do operations on that number and update the label.
Your mistake is that each Panel has its own number and its own Label to display the number.
public class ButtonModifier {
private static int number = 50;
private static JLabel label;
public static void main(String[] args) {
JFrame frame = new JFrame();
label = new JLabel("" + number);
// <SNIP>
JButton increment = new JButton("Increment");
increment.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
number++;
label.setText("" + number);
}
}
JButton decrement = new JButton("Increment");
increment.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
number--;
label.setText("" + number);
}
}
frame.add(label);
frame.add(increment);
frame.add(decrement);
frame.setVisible(true);
}
}
An important note: Swing is not thread-safe, and all the operations with GUI components must be performed on Event Dispatch Thread. So your main must actually look this way:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Here you create the frame and all the components
}
});
}
Take a look at this program :
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
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;
public class IncDecApp extends JFrame {
private JButton incBtn = new JButton("Increment");
private JButton decBtn = new JButton("Decrement");
private JPanel lowPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
private JLabel showLbl = new JLabel("00", JLabel.CENTER);
private Font myFont = new Font("Tahoma", Font.BOLD, 60);
private int valueInt;
public IncDecApp() {
setTitle("IncDec Application =)");
setDefaultCloseOperation(EXIT_ON_CLOSE);
lowPanel.add(incBtn);
lowPanel.add(decBtn);
incBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
valueInt = Integer.parseInt(showLbl.getText());
valueInt++;
if (valueInt >= 10) {
showLbl.setText(String.valueOf(valueInt));
} else {
showLbl.setText("0" + String.valueOf(valueInt));
}
}
});
decBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
valueInt = Integer.parseInt(showLbl.getText());
if (valueInt > 0) {
valueInt--;
}
if (valueInt >= 10) {
showLbl.setText(String.valueOf(valueInt));
} else {
showLbl.setText("0" + String.valueOf(valueInt));
}
}
});
showLbl.setFont(myFont);
add(showLbl, BorderLayout.CENTER);
add(lowPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new IncDecApp();
}
}
Create the JLabel in the main function. Have the incrementPanel and DecrementPanel classes constructors take a JLabel as an argument that they store as a private variable. The ButtonListeners csn also be passed the JLabel as an argument. Now the button listeners csn update a common JLabel.
Now, you can improve things by combining the code of IncrementPanel and DecrementPanel classes by passing an int in the constructor indicating the increment of +1 or -1.
A quick and dirty way to implement the functionality is through the use of anonymous classes implementing button listeners within a single monolithic class.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonApplet extends Applet implements ActionListener{
Button buttonInc, buttonDec;
int x=0;
public void init(){
buttonInc=new Button("Increment");
buttonDec=new Button("Decrement");
buttonInc.addActionListener(this);
buttonDec.addActionListener(this);
add(buttonInc);
add(buttonDec);
}
public void paint(Graphics g){
g.drawString("Count is : "+x,50,100);
}
public void actionPerformed(ActionEvent ev){
if(ev.getSource() == buttonInc)
{
x++;
repaint();
}
else if(ev.getSource() == buttonDec){
x--;
repaint();
}
}
}
Make Java GUI Application using AWT
You are required to make one label (Count), one textfield, one button (Increment), one button (Decrement) and one button (Close)
When the increment button is clicked, you need to increment the value in textfield, value should be incremented again and again when the button is clicked
When the decrement button is clicked, you need to decrement the value in textfield, value should be decremented again and again when the button is clicked
When the close button is clicked, you need to close the AWT Frame
Related
I'm new to Java and just learning I want to increase a variable by clicking a button but I'm getting the following error
local variables referenced from an inner class must be final or effectively final
The assigned value is never used
Adding final doesn't solved the problem and I'm a bit stuck why this doesn't work? can you help?
public class JavaApplication2 {
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Click");
panel.setLayout(new FlowLayout());
frame.add(panel);
panel.add(button);
int x;
x = 0;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You CLicked the Button " + x + " times");
x = x + 1; // *getting error*
}
});
frame.setVisible(true);
frame.setSize(500,500);
frame.setLocation(50,50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Your variable X needs to be a global, static variable because you never know when the registered ActionListener will be triggered.
X is not in that scope and might be already removed at that time.
I strongly suggest using something like the following.
You shouldn't use global static variables for such a problem.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaApplication2 {
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Click");
panel.setLayout(new FlowLayout());
frame.add(panel);
panel.add(button);
Counter c = new Counter();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("You CLicked the Button " + c.getValue() + " times");
c.increment();
}
});
frame.setVisible(true);
frame.setSize(500, 500);
frame.setLocation(50, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Counter {
private int value = 0;
void increment() {
value++;
}
void reset() {
value = 0;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
It doesn't appear that my thread ever starts. Either that or the run method isn't actually doing anything, for which reason I could not explain.
I have a listener on my button StartRace and it should start the thread which will increment the length of each rectangle until one of them is long enough to be declared winner (by surpassing the width of the window, 250px).
I get all of the components initially painted to the screen, but they're never repainted. Is there something wrong with the way I call the method? Do I have classes nested within others that shouldn't be?
//--------------------------------------------------------------
// Start a race between blue and red, track the winner
// Use threads to manage each rectangle's movement
// Allow for user interaction, like stopping and starting
//--------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class ConcurrencyRace extends JFrame
{
private ConcurrencyPanel panel = new ConcurrencyPanel();
private JButton startRace = new JButton("Start The Race!");
private JButton stopRace = new JButton("Stop The Race!");
private JLabel winnerText = new JLabel("Winner: ");
private int blueDraw = 5, redDraw = 5;
private Random rn = new Random();
//-----------------------------------------------------------------
// Creates and displays the main program frame.
//-----------------------------------------------------------------
public ConcurrencyRace() {
super("Concurrency");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Container cp = getContentPane();
cp.add(panel, BorderLayout.CENTER);
JPanel p = new JPanel();
p.add(startRace);
p.add(stopRace);
cp.add(p, BorderLayout.NORTH);
cp.add(winnerText, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public static void main (String[] args)
{
ConcurrencyRace tRun = new ConcurrencyRace();
tRun.setVisible(true);
}
private class ConcurrencyPanel extends JPanel
{
public class runnerThread extends Thread {
#Override
public void run() {
while (blueDraw < 250 && redDraw < 250) {
panel.validate();
panel.repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
}
}
public ConcurrencyPanel ()
{
setPreferredSize(new Dimension(600,250));
}
private class ButtonListener implements ActionListener {
runnerThread rectDraw = new runnerThread();
//--------------------------------------------------------------
// Starts the thread to draw each rectangle ("racer")
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
if (event.getSource() == startRace) {
rectDraw.start();
}
}
}
#Override
public void paintComponent (Graphics page) {
super.paintComponent(page);
page.setColor(Color.blue);
page.fillRect(0,80,blueDraw,20);
page.setColor(Color.red);
page.fillRect(0,120,redDraw,20);
blueDraw += rn.nextInt(10) + 1;
redDraw += rn.nextInt(10) + 1;
page.dispose();
}
}
}
Primarily
You never add a ActionListener to either of your buttons, so nothing is responding when they are activated
Additionally
The state management is all over the place. blueDraw and redDraw should be instance fields of ConcurrencyPanel.
Don't update the state of the UI (or variables which the UI relies on) from within any paint method. Paint methods should paint the state, not change it. Updating the blueDraw and redDraw should be done in a specific method, which can be called when a update is required.
All of that leads me to believe you'd be better of using a Swing Timer
Conceptually...
You could do something like this...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ConcurrencyRace {
//-----------------------------------------------------------------
// Creates and displays the main program frame.
//-----------------------------------------------------------------
public ConcurrencyRace() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Timer timer = new Timer(200, null);
JFrame frame = new JFrame();
frame.add(new ButtonPane(timer), BorderLayout.NORTH);
frame.add(new RacePane(timer));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
new ConcurrencyRace();
}
public class ButtonPane extends JPanel {
private JButton startRace = new JButton("Start The Race!");
private JButton stopRace = new JButton("Stop The Race!");
public ButtonPane(Timer timer) {
startRace.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
stopRace.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
setLayout(new GridBagLayout());
add(startRace);
add(stopRace);
}
}
private class RacePane extends JPanel {
private int blueDraw = 5, redDraw = 5;
private Random rn = new Random();
public RacePane(Timer timer) {
timer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (updateState()) {
((Timer)e.getSource()).stop();
}
}
});
}
protected boolean updateState() {
blueDraw += rn.nextInt(10) + 1;
redDraw += rn.nextInt(10) + 1;
repaint();
return blueDraw >= getWidth() || redDraw >= getWidth();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 250);
}
#Override
public void paintComponent(Graphics page) {
System.out.println(">>");
super.paintComponent(page);
page.setColor(Color.blue);
page.fillRect(0, 80, blueDraw, 20);
page.setColor(Color.red);
page.fillRect(0, 120, redDraw, 20);
}
}
}
This maintains the Timer as the central concept, which is shared between the buttons and race panels.
I've not added support for generating notification of a winner, this would be done via a simple observer pattern passed to the RacePane
I am trying to have the number the user inputs into the frame either multiply by 2 or divide by 3 depending on which button they decide to click. I am having an hard time with working out the logic to do this. I know this needs to take place in the actionperformed method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
Here's something simpler, but it essentially does what you want out of your program. I added an ActionListener to each of the buttons to handle what I want, which was to respond to what was typed into the textbox. I just attach the ActionListener to the button, and then in the actionPerformed method, I define what I want to happen.
import java.awt.FlowLayout;
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.JTextField;
import javax.swing.SwingUtilities;
public class Quizx extends JFrame {
private JPanel panel;
private JTextField textfield;
private JLabel ansLabel;
public Quizx() {
panel = new JPanel(new FlowLayout());
this.getContentPane().add(panel);
addLabel();
addTextField();
addButtons();
addAnswerLabel();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Quiz 4");
this.setSize(220, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
private void addTextField() {
textfield = new JTextField();
textfield.setColumns(9);
panel.add(textfield);
}
private void addButtons() {
JButton multButton = new JButton("x2");
JButton divButton = new JButton("/3");
panel.add(multButton);
panel.add(divButton);
addMultListener(multButton);
addDivListener(divButton);
}
private void addLabel() {
JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
panel.add(valueLabel);
}
private void addAnswerLabel() {
ansLabel = new JLabel();
panel.add(ansLabel);
}
private void addMultListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Integer.parseInt(textfield.getText().trim()) * 2));
}
});
}
private void addDivListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Double.parseDouble(textfield.getText().trim()) /3));
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Quizx();
}
});
}
}
Hope that helps.
Okay I can get text fields and normal text and even images to show but I can not get a button to show. I am not sure what I am doing wrong because I have done the same steps for the rest. Any help would be great thanks!
package EventHandling2;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import EventHandling.GUITest;
public class EventMain extends JFrame{
private JLabel label;
private JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
//gui.setSize(600, 300);
gui.setVisible(true);
gui.setTitle("Button Test");
}
public void EventMain(){
setLayout(new FlowLayout());
button = new JButton ("click for text");
add(button);
label = new JLabel ("");
add(label);
Events e = new Events();
button.addActionListener(e);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}
The problem is with the method: void EventMain()
Constructor has NO return type. Just remove "void". The code will work just fine.
Your actionListener(e) contains a minor control structure error:
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
Change to:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
label.setText("Now you can see words");
}
}
First off, you have to remove void keyword in EventMain's constructor. Then, creating JPanel and add components into it, then add the JPanel to the JFrame.contentPane.
The following code should work:
public class EventMain extends JFrame {
private final JLabel label;
private final JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x
// close program
gui.setSize(600, 300);
gui.setTitle("Button Test");
gui.setVisible(true);
}
public EventMain() {
// setLayout(new FlowLayout());
JPanel panel = new JPanel(new FlowLayout());
button = new JButton("click for text");
panel.add(button);
label = new JLabel("");
panel.add(label);
Events e = new Events();
button.addActionListener(e);
this.getContentPane().add(panel);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}
I have a problem, I have been making a Swing application.
My question is about how to handle Jbutton like a JOptionPane, if it's possible?
I want handle all of the buttons similarly to JOptionpane button, but our message written in main function System.out.println("this line executes...how to prevent..");
This function is to display the message, until Jframe is visible.
Can anyone let me know how to prevent & how to handle button functionality? Especially when it executes further when I click the button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
JLabel name=new JLabel("Name:");
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(false);
JPanel namePanel = new JPanel();
namePanel.add(name);
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
warningLabel.setForeground(Color.red);
add(warningLabel, BorderLayout.NORTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty :"+name.getText());
warningLabel.setBackground(WARNING_COLOR);
//firstNameField.setText("sorry");
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setSize(200, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGui();
System.out.println("this line executes...how to prevent..");
}
}
Basically, you have something like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
System.err.println("Executed once the button has been clicked");
}
}
And you want the line System.err.println("Executed once the button has been clicked"); to be executed when the button is pressed (which is not the case here above).
The solution is actually very simple: you move the code to execute after the button click in another method (see below the proceed() method) and you invoke that line from an ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
proceed();
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
protected void proceed() {
System.err.println("Executed once the button has been clicked");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
}
}
Well, the question is not very much clear,but from your comment,you dont want to do any thing till a JButton is clicked? Or you want to preform a task after clicking of a button?
If that is so, dont put your further code inside your main block, call a function from actionPerformed block.Something like this:
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
display();///////////this is the function containing further code
}
}
//this is display
public void display()
{
System.out.println("this line executes...how to prevent..");
}