Hello I have created a graphical calc
in Java. Now I would like to add click
events to specific buttons in order to
handle the datas, what should I add to
my code? I would like to have
something like "onclik" in Javascript.
Max Thanks!
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class Fenetre extends JFrame{
private JPanel pan = new JPanel();
private JButton bouton1 = new JButton("C");
private JButton bouton2 = new JButton("+");
private JButton bouton3 = new JButton("-");
private JButton bouton4 = new JButton("*");
private JButton bouton5 = new JButton("/");
private JButton bouton6 = new JButton("1");
private JButton bouton7 = new JButton("2");
private JButton bouton8 = new JButton("3");
private JButton bouton9 = new JButton("4");
private JButton bouton10 = new JButton("5");
private JButton bouton11 = new JButton("6");
private JButton bouton12 = new JButton("7");
private JButton bouton13 = new JButton("8");
private JButton bouton14 = new JButton("9");
private JButton bouton15 = new JButton("0");
private JButton bouton16 = new JButton(".");
private JButton bouton17 = new JButton("=");
private JLabel ecran = new JLabel();
public Fenetre(){
ecran = new JLabel("0");
this.setTitle("Calculatrice");
this.setSize(300, 450);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
//Ajout du bouton à notre content pane
pan.setLayout(null);
ecran.setBounds(100,2,100,60);
bouton1.setBounds(220,60,60,60);
bouton2.setBounds(220,130,60,60);
bouton3.setBounds(220,200,60,60);
bouton4.setBounds(220,270,60,60);
bouton5.setBounds(220,340,60,60);
bouton6.setBounds(10,60,60,60);
bouton7.setBounds(80,60,60,60);
bouton8.setBounds(150,60,60,60);
bouton9.setBounds(10,130,60,60);
bouton10.setBounds(80,130,60,60);
bouton11.setBounds(150,130,60,60);
bouton12.setBounds(10,200,60,60);
bouton13.setBounds(80,200,60,60);
bouton14.setBounds(150,200,60,60);
bouton15.setBounds(10,270,60,60);
bouton16.setBounds(80,270,60,60);
bouton17.setBounds(150,270,60,60);
pan.add(ecran);
pan.add(bouton1);
pan.add(bouton2);
pan.add(bouton3);
pan.add(bouton4);
pan.add(bouton5);
pan.add(bouton6);
pan.add(bouton7);
pan.add(bouton8);
pan.add(bouton9);
pan.add(bouton10);
pan.add(bouton11);
pan.add(bouton12);
pan.add(bouton13);
pan.add(bouton14);
pan.add(bouton15);
pan.add(bouton16);
pan.add(bouton17);
this.setContentPane(pan);
this.setVisible(true);
}
}enter code here
You can use addActionListener method.
this method accepts an ActionListener instance - this is an interface with one method- actionPerformed, this will be executed when your button is pressed:
For example:
b1.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
// do whatever
}
}
);
There are planty of tutorials out there about swing event handling, like this one which is quite good
You simply need to add an ActionListener to the buttons that should trigger an action on click, something like that:
bouton1.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
// do something here
}
}
);
How to Write an Action Listener
This is equivalent to an onclick so it should be enough in your particular case but if you need to access to more mouse events, you should rather add a MouseListener as next:
bouton1.addMouseListener(
new MouseListener() {
#Override
public void mouseClicked(final MouseEvent e) {
...
}
#Override
public void mousePressed(final MouseEvent e) {
...
}
#Override
public void mouseReleased(final MouseEvent e) {
...
}
#Override
public void mouseEntered(final MouseEvent e) {
...
}
#Override
public void mouseExited(final MouseEvent e) {
...
}
}
);
Related
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
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.JOptionPane;
import java.lang.*;
import java.util.*;
public class Life {
public static void main (String[] args){
JFrame frame = new JFrame("Interest Calculator");
frame.setVisible(true);
frame.setSize(300,100);
frame.setBackground(Color.magenta);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Simple Interest");
panel.add(button);
button.addActionListener (new Action1());
JButton button2 = new JButton("Compound Interest");
panel.add(button2);
button2.addActionListener (new Action2());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Simple");
frame2.setVisible(true);
frame2.setSize(300,100);
JPanel panel = new JPanel();
frame2.add(panel);
JButton button = new JButton("Ordinary");
panel.add(button);
button.addActionListener (new Ordinary());
JButton button2 = new JButton("Exact");
panel.add(button2);
button2.addActionListener (new Exact());
}
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame3 = new JFrame("Compound Interest");
frame3.setVisible(true);
frame3.setSize(300,100);
JPanel panel = new JPanel();
frame3.add(panel);
JButton button = new JButton("Compounded");
panel.add(button);
JButton button2 = new JButton("Continously");
panel.add(button2);
}
}
static class Ordinary implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame4 = new JFrame("Simple");
frame4.setVisible(true);
frame4.setSize(300,100);
JPanel panel = new JPanel();
frame4.add(panel);
JButton button = new JButton("Approximate");
panel.add(button);
button.addActionListener (new Approximate());
JButton button2 = new JButton("Actual");
panel.add(button2);
}
}
static class Exact implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame5 = new JFrame("Exact");
frame5.setVisible(true);
frame5.setSize(300,100);
JPanel panel = new JPanel();
frame5.add(panel);
JButton button = new JButton("Approximate");
panel.add(button);
JButton button2 = new JButton("Actual");
panel.add(button2);
}
}
static class Approximate implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame6 = new JFrame("Simple");
frame6.setVisible(true);
frame6.setSize(300,100);
JPanel panel = new JPanel();
frame6.add(panel);
frame6.setVisible(true);
frame6.setSize(300,300);
frame6.setLayout(null);
frame6.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField P = new JTextField();
panel.add(P);
P.setText("Enter Principal");
JTextField r = new JTextField();
panel.add(r);
r.setText("Enter Rate");
JTextField t = new JTextField();
panel.add(t);
t.setText("Enter Year");
JButton button = new JButton("Calculate");
panel.add(button);
button.addActionListener (new button());
static class button implements ActionListener {
public void actionPerformed (ActionEvent e) {
float P,r,t,result ;
P = Float.parseFloat(P.getText());
r = Float.parseFloat(r.getText());
t = Float.parseFloat(t.getText());
result = P*r/100*t/360;
button.setText(String.valueof(result));
}
}
}
}
}
So this is my code to create a compound calculator but I have a problem it is the illegal start of expression.please help me for my project.
Below is partially fixed part of the code which causes problems. Next time include full error code, and try to show only relevant part of the code.
ActionListener listener = new ActionListener() {
public void actionPerformed (ActionEvent e) {
float P,r,t,result ;
//P = Float.parseFloat(P.getText()); // P makes no sens here - its float !!! and uninitialized
//r = Float.parseFloat(r.getText()); // same for r
//t = Float.parseFloat(t.getText()); // same for t
result = P*r/100*t/360;
button.setText(String.valueOf(result));
}
};
button.addActionListener (listener);
I've created an auto typer because I've always wanted to know how they work. Only problem is when I click the stop button, it doesn't stop and it freezes my system.
I've tried changing the interval time, and it still doesn't stop when the stop button is pushed.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class AutoSpammer{
private static int interval;
private static Timer timerMain;
private static JTextField txtSpam;
private static JTextField txtInterval;
private static JButton btnStart;
private static JButton btnStop;
public static void main(String[]args){
ActionListener taskSpam = new ActionListener(){
public void actionPerformed(ActionEvent evt) {
sendkeys(txtSpam.getText());
}
};
ActionListener taskStartTimer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
timerMain.setDelay(Integer.parseInt(txtInterval.getText()));
timerMain.start();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
txtInterval.setEnabled(false);
}
};
ActionListener taskStopTimer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
timerMain.stop();
btnStart.setEnabled(true);
btnStop.setEnabled(false);
txtInterval.setEnabled(true);
}
};
btnStart = new JButton("Start Spam");
btnStop = new JButton("Stop Spam");
JLabel lbl1 = new JLabel("Enter Text:");
JLabel lbl2 = new JLabel("Interval:");
timerMain = new Timer(1,taskSpam);
txtSpam = new JTextField("Enter text:", 13);
txtInterval = new JTextField("3000",3);
btnStart.addActionListener(taskStartTimer);
btnStop.addActionListener(taskStopTimer);
btnStop.setEnabled(false);
JPanel intervalpane = new JPanel();
intervalpane.add(lbl2,BorderLayout.EAST);
intervalpane.add(txtInterval,BorderLayout.WEST);
JPanel bottompane = new JPanel();
bottompane.add(btnStart,BorderLayout.EAST);
bottompane.add(btnStop,BorderLayout.CENTER);
bottompane.add(intervalpane,BorderLayout.WEST);
JPanel toppane = new JPanel();
toppane.add(lbl1,BorderLayout.EAST);
toppane.add(txtSpam,BorderLayout.NORTH);
JPanel pane = new JPanel(new BorderLayout());
pane.add(toppane,BorderLayout.NORTH);
pane.add(bottompane,BorderLayout.SOUTH);
JFrame frame = new JFrame("Spammer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(pane);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
private static void sendkeys(String text) {
try {
Robot robot = new Robot();
text = text.toUpperCase();
for(int i = 0; i < text.length(); i++)
robot.keyPress(text.charAt(i));
robot.keyPress(KeyEvent.VK_ENTER);
}catch(java.awt.AWTException exc) {
System.out.println("error");
}
}
}
program works fine for me. Stop does stop the robot. I added a simple System.out what has been pressed and this stops
I found this code online and modified it and it stopped working. I'm thinking it has something to do with when I added the Jpanel but what I am doing works best with a JPanel. How do I make it that the events in the action performed if statements work?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class GUI extends JFrame implements ActionListener {
static JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1));
public GUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setSize(100, 100);
//setLocation(100, 100);
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(this);
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(this);
panel.add(button2);
//Button 3
JButton button3 = new JButton("3");
button3.addActionListener(this);
panel.add(button3);
//Button 2
JButton button4 = new JButton("4");
button4.addActionListener(this);
panel.add(button4);
//Button 2
JButton button5 = new JButton("5");
button5.addActionListener(this);
panel.add(button5);
//Button 2
JButton button6 = new JButton("6");
button6.addActionListener(this);
panel.add(button6);
//Button 2
JButton button7 = new JButton("7");
button7.addActionListener(this);
panel.add(button7);
//Button 2
JButton button8 = new JButton("8");
button8.addActionListener(this);
panel.add(button8);
//Button 2
JButton button9 = new JButton("9");
button9.addActionListener(this);
panel.add(button9);
panel.setVisible(true);
}
public static void main(String[] args) {
new GUI();
JFrame f = new JFrame("Calc");
f.setContentPane(panel);
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
ArrayList numbers = new ArrayList();
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("button1")) {
numbers.add(2);
System.out.println("2");
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}
You need to change the part actionPerformed as:
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("2")) {
numbers.add(2);
System.out.println("2");
}
}
Here, when a button is clicked, your e.getActionCommand() will give the constructor string. i.e. "1", "2" ,"3" and so on
reference
I put comments in code, but the first thing you should do is to read official tutorials. How to use Buttons
public class GUI /*extends JFrame implements ActionListener*/ {
//don't extend JFrame is you don't have too neither implement ActionListener in top-container classes that breaks single responsability principle
private JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1)); // why static??
public JPanel getPanel(){
return panel;
}
public GUI() {
//i use anonymous classes for this, then you don't have to use if-else
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
myMethod();
numbers.add(1);
System.out.println("1");
}
});
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//put here logic for button2
}
});
panel.add(button2);
//and goo on with other buttons
//panel.setVisible(true); you don't need to call this!!
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI gui = new GUI();
frame.add(gui.getPanel());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private List<Integer> numbers = new ArrayList<>();//use generics!
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}
Trying to develop a GUI, but I've hit a snag:
I am using a submit button, which will look at a txtEnter field. If the user types "yes" in the txtEnter field and clicks submit, it will execute a shell script. If the user types "no" there will be no action. I know the command to run shell script is Runtime.getRuntime().exec(myShellScript);
How I can use an if-else statement in the SubmitListner to check for the user's input?
import javax.swing.*; import javax.swing.event.DocumentListener;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Executer private JLabel lblCommand;
private JTextField txtEnter;
private JButton btNext, btPrevious, btSubmit;
private JPanel panel;
public static void main(String[] args) {
new Executer();
}
public Executer() {
JFrame frame = new JFrame("Script Executer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,300);
frame.setVisible(true);
myPanel();
Text();
Fields();
Buttons();
frame.add(panel);
frame.setVisible(true);
}
public void myPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void Text(){
lblCommand = new JLabel("Enter Here");
lblCommand.setBounds(145, 100, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblCommand.setFont(styleOne);
panel.add(lblCommand);
}
public void Fields () {
txtEnter = new JTextField();
txtEnter.setBounds(230, 100, 120, 20);
panel.add(txtEnter);
}
public void Buttons() {
btNext = new JButton ("Next");
btNext.setBounds(300,215,100,20);
panel.add(btNext);
btPrevious = new JButton ("Previous");
btPrevious.setBounds(190,215,100,20);
panel.add(btPrevious);
btSubmit = new JButton("Submit");
btSubmit.setBounds(80,215,100,20);
panel.add(btSubmit);
}
class SubmitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
}}}
You have to assign your Actionlistener to your button:
btSubmit = new JButton();
btSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// here the click happend so you can check your Textfield
String userEntered = txtEnter.getText();
if(userEntered.equalsIgnoreCase("yes"))
{
//run your script
}
}
});
How do I prevent this error from happening with my current code? I apologize for my logic being very amateur.
public class jButExmp {
JFrame exmpFrame;
JButton Button1, Button2, Button3;
public jButExmp () {
exmpFrame.setLayout(new FlowLayout());
exmpFrame.setSize(250,150);
exmpFrame.setVisible(true);
exmpFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
exmpFrame.add(Button1);
exmpFrame.add(Button2);
exmpFrame.add(Button3);
}
public static void main(String[] args) {
exmpFrame = new JFrame ("Example Frame");
Button1 = new JButton ("1");
Button2 = new JButton ("2");
Button3 = new JButton ("3");
Button1.setSize(80, 30); //set size of button
Button1.setLocation(0,0);
Button1.setEnabled(true);
Button2.setSize(80,30);
Button2.setLocation(90, 0);
Button2.setEnabled(false);
}
}
import java.awt.FlowLayout;
import javax.swing.*;
public class ExmpFile {
JFrame exmpFrame;
JButton Button1, Button2, Button3;
public ExmpFile() {
exmpFrame = new JFrame ("Example Frame");
Button1 = new JButton ("1");
Button2 = new JButton ("2");
Button3 = new JButton ("3");
Button2.setEnabled(false);
exmpFrame.setLayout(new FlowLayout(FlowLayout.CENTER));
// better to pack() to the size of content.. BNI
exmpFrame.setSize(250,150);
exmpFrame.setVisible(true);
exmpFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
exmpFrame.add(Button1);
exmpFrame.add(Button2);
exmpFrame.add(Button3);
exmpFrame.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new ExmpFile();
}
};
SwingUtilities.invokeLater(r);
}
}
In your code you are trying to access not static variables in static main method, so it will compilation errors.
Try this
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class jButExmp {
JFrame exmpFrame = new JFrame("Example Frame");
JButton button1, button2, button3;
public JButton getButton1() {
return button1;
}
public void setButton1(JButton button1) {
this.button1 = button1;
}
public JButton getButton2() {
return button2;
}
public void setButton2(JButton button2) {
this.button2 = button2;
}
public JButton getButton3() {
return button3;
}
public void setButton3(JButton button3) {
this.button3 = button3;
}
public jButExmp() {
exmpFrame = new JFrame("Example Frame");
exmpFrame.setLayout(new FlowLayout());
exmpFrame.setSize(250, 150);
exmpFrame.setVisible(true);
button1 = new JButton("1");
button2 = new JButton("2");
button3 = new JButton("3");
exmpFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
exmpFrame.add(button1);
exmpFrame.add(button2);
exmpFrame.add(button3);
}
public static void main(String[] args) {
jButExmp jButExmpRef = new jButExmp();
jButExmpRef.getButton1().setSize(80, 30); // set size of button
jButExmpRef.getButton1().setLocation(0, 0);
jButExmpRef.getButton1().setEnabled(true);
jButExmpRef.getButton2().setSize(80, 30);
jButExmpRef.getButton2().setLocation(90, 0);
jButExmpRef.getButton2().setEnabled(false);
}
}
This woud be the more idiomatic way to do it, though this code has some other problems, including the fact that you're not setting up button3 the way you are with button1 and button2, and the fact that you are setting the locations of the buttons while using the default FlowLayout (which doesn't support setting positions).
import javax.swing.JButton;
import javax.swing.JFrame;
public class JButExmp extends JFrame {
JButton button1;
JButton button2;
JButton button3;
public JButExmp (String title) {
super(title);
button1 = new JButton("1");
button2 = new JButton("2");
button3 = new JButton("3");
add(button1);
add(button2);
add(button3);
button1.setSize(80, 30); //set size of button
button1.setLocation(0,0);
button1.setEnabled(true);
button2.setSize(80,30);
button2.setLocation(90, 0);
button2.setEnabled(false);
setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setSize(250,150);
setVisible(true);
}
public static void main(String[] args) {
JButExmp jButExmp = new JButExmp("Example Frame");
}
}