java calculator decimal point - java

I have fully working calculator using java.Can tell me how to add decimal point.I already have the button and the variables are in type double.I just can't make the button work.
I tried to do it myself,but I ended up with error messages every time.
Here is the code:
package oop;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Kalkulator2 extends Applet {
String arg1= "", arg2="";
double ergebnis;
Button zahl[] =new Button[10];
Button funktion[] = new Button[4];
Button ausfuehren;
Button decimalpoint;
char dec='.';
Panel zahlPanel,funktionPanel,ergebnisPanel;
TextField ergebnisFeld = new TextField(5);
int operationArgument;
char operation;
public void init () {
operationArgument= 1; operation =' ';
setLayout(new BorderLayout());
zahlPanel = new Panel();
zahlPanel.setLayout(new GridLayout (4,3));
for (int i=9; i>=0; i--) {
zahl[i] = new Button(String.valueOf(i));
zahl[i].addActionListener(new ButtonZahlen());
zahlPanel.add(zahl[i]);
}
decimalpoint = new Button(String.valueOf(dec)); //decimal point
//decimalpoint.addActionListener(new Button ());
ausfuehren = new Button("=");
ausfuehren.addActionListener(new ButtonAusfuehren()); //zu dem Listener
zahlPanel.add(decimalpoint);
zahlPanel.add(ausfuehren);
add("Center",zahlPanel);
funktionPanel = new Panel();
funktionPanel.setLayout(new GridLayout(4,1));
funktion[0] = new Button("+");
funktion[0].addActionListener(new ButtonOperation());
funktionPanel.add(funktion[0]);
funktion[1] = new Button("-");
funktion[1].addActionListener(new ButtonOperation());
funktionPanel.add(funktion[1]);
funktion[2] = new Button("*");
funktion[2].addActionListener (new ButtonOperation());
funktionPanel.add(funktion[2]);
funktion[3] = new Button("/");
funktion[3].addActionListener (new ButtonOperation());
funktionPanel.add(funktion[3]);
add("East",funktionPanel);
ergebnisPanel = new Panel();
ergebnisPanel.add(ergebnisFeld);
add("North",ergebnisPanel);
}
class ButtonZahlen implements ActionListener{
public void actionPerformed(ActionEvent e) {
switch (operationArgument) {
case 1 : {
arg1+=e.getActionCommand();
ergebnisFeld.setText(arg1);
break;
}
case 2 : {
arg2 +=e.getActionCommand();
ergebnisFeld.setText(arg2);
break;
}
default: { }
}
}
}
class ButtonAusfuehren implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(operation =='+')
ergebnis = new Double(arg1) + new Double(arg2);
else if (operation == '-')
ergebnis = new Double(arg1) - new Double(arg2);
else if(operation =='*')
ergebnis = new Double(arg1) * new Double(arg2);
else if(operation =='/')
ergebnis = new Double(arg1) / new Double(arg2);
ergebnisFeld.setText(String.valueOf(ergebnis));
}
}
class ButtonOperation implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("+")) {
operation = '+'; operationArgument = 2;
}
else if(e.getActionCommand().equals("-")) {
operation = '-'; operationArgument = 2;
}
else if(e.getActionCommand().equals("*")) {
operation = '*' ; operationArgument =2;
}
else if(e.getActionCommand().equals("/")) {
operation = '/' ; operationArgument =2;
}
}
}
}
public void paint(Graphics g){ }
}

When the button got clicked, it is trying to create a new button object which doesn't implement an actionListener. Thus it will throw an error saying " what must i do with a new button while i need an object with 'actionPerformed' method " Here is a possible solution;
// create button object
decimalpoint = new Button(".");
// not good : decimalpoint.addActionListener(new Button ());
// event on click
decimalpoint.addActionListener(new YourClassName());
and YourClassName is an instance to handle the button event
class YourClassName implements ActionListener {
public void actionPerformed(ActionEvent e) {
// add decimal point
}
}
I also agree with Andrew Thompson that AWT is not a preferred way to handle your tasks. If your teacher has suggested you to use AWT, then please use Swing. Swing is far better then AWT and should be educated to people who is writing GUI-based java for the first time.

To answer the question, to add a DECIMAL POINT to java code (my example is for GUI NetBeans IDE 8.0.2) I have stumbled across this code. I must admit I have not come across this code having looked for an answer on the net.
private void PointActionPerformed(java.awt.event.ActionEvent evt) {
txtDisplay.setText(txtDisplay.getText()+Point.getText());
}

you can do that simply
specify the button -
Button Decimal;
caste the button you specified in your xml file to (Button)Decimal -
Decimal = findViewById(R.id.the id you gave to the button);
Now set on click listener
Decimal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.setText(edit.getText().toString() + ".");
}
where edit is the field you want the text to be filled.

Related

Getting value from JRadioButton

I'd like to change value of my variable "name" when I select right button and click "ok" on my JRadio Frame.
For example when i select r1 and hit "ok" I'd like to have name=="Fast" in the entire package.
package Snake;
public class Radio extends JFrame {
private int delay = 100;
private String name;
JTextField t1;
JButton b;
JRadioButton r1, r2;
JLabel l;
public void selectSpeed() {
b = new JButton("Ok");
r1 = new JRadioButton("Fast");
r2 = new JRadioButton("Slow");
l = new JLabel("Speed: ");
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
add(b);
add(r1);
add(r2);
add(l);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
if (name == "Fast") { // and now name is empty...
delay = 50;
}
if (name == "Slow") {
delay = 500;
}
setLayout(new FlowLayout());
setSize(400, 400);
setVisible(true);
}
public int setSpeed() {
selectSpeed();
return delay;
}
}
If you want to change the delay on button click, You need to write the logic in the ActionListener itself because the code you have written to change the delay will run only once and that too at the start of the execution of your program and at that time, name will be empty.
Then when ever you click the button, It will only execute the ActionListener So delay will not be changed at any time. And other mistake you are making is that you are comparing Strings in wrong way. For more information take a look at it How do I compare Strings in Java?
To change delay dynamically on button click, you need to change it in the ActionListener.
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
delay = 50;
} else {
name = "Slow";
delay = 500;
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
You need to do it in your JRadioButton listener. For example, like here, at first you change the variable "name" and later in the current listener you check conditions, but you need remember that to compare the strings you need to use "equals":
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
if (name.equals("Fast")) { // and now name is empty...
delay = 50;
}
if (name.equals("Slow")) {
delay = 500;
}
} // name=="Slow" when r2 is selected
});
Well I see my mistake now, Thank you.
But it still does not work the way I like. I'd like to change the "delay" value every time I select right button on JRadio and hit "ok" and with this changed value I'd like to go to the other class.
There is the code of a class where I need value of "delay":
package Snake;
public class Gameplay extends Paint implements KeyListener, ActionListener {
private Timer timer;
private int q = 0;
Radio radio = new Radio();
public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(radio.selectSpeed(), this); //here i need flexible "delay" value
timer.start();
}

How do I provide a single button handler object

I am completing a past paper exam question and it asks to create an applet that displays a green square in the center, with three buttons + , - and reset, however, I am trying to make it that when any button is clicked the program should essentially figure out which button was pressed. I know you would use e.getSource() but I am not sure how to go about this.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Square extends JApplet {
int size = 100;
public void init() {
JButton increase = new JButton("+");
JButton reduce = new JButton("-");
JButton reset = new JButton("reset");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butPanel.add(increase);
butPanel.add(reduce);
butPanel.add(reset);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
ButtonHandler bh1 = new ButtonHandler(this, 0);
ButtonHandler bh2 = new ButtonHandler(this, 1);
ButtonHandler bh3 = new ButtonHandler(this, 2);
increase.addActionListener(bh1);
reduce.addActionListener(bh2);
reset.addActionListener(bh3);
}
}
class SquarePanel extends JPanel {
Square theApplet;
SquarePanel(Square app) {
theApplet = app;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(10, 10, theApplet.size, theApplet.size);
}
}
class ButtonHandler implements ActionListener {
Square theApplet;
int number;
ButtonHandler(Square app, int num) {
theApplet = app;
number = num;
}
public void actionPerformed(ActionEvent e) {
switch (number) {
case 0:
theApplet.size = theApplet.size + 10;
theApplet.repaint();
break;
case 1:
if (theApplet.size > 10) {
theApplet.size = theApplet.size - 10;
theApplet.repaint();
}
break;
case 2:
theApplet.size = 100;
theApplet.repaint();
break;
}
}
Not the best way to do it, but based on your current code, you could simply compare the object references. You'd need to pass in references to the buttons or access them some other way. e.g.
if(e.getSource() == increase) { \\do something on increase}
Another alternative would be to check the string of the button, e.g.
if(((JButton)e.getSource()).getText().equals("+")){ \\do something on increase}
You can use strings in a switch statement in Java 8, but if you're using Java 7 or lower, it has to be an if statement.
You can use if then else statement as in the sample below
if(e.getSource()==bh1){
//your codes for what should happen
}else if(e.getSource()==bh2){
}else if(e.getSource()==bh3){
}else if(e.getSource()==bh4){
}
OR even in a switch case statement

Combination Lock (Java)

I have a school assignment that i need to create. Below is the info:
Create a frame with ten buttons, labeled 0 through 9. To exit the program, the user must click on the correct three buttons in order, something like 7-3-5. If the wrong combination is used, the frame turns red.
I already finish the frame and the buttons with online research helps, but i just cant make the functionality to work. Please take a look at my codes and thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboNumber extends JFrame implements ActionListener{
//variable declaration
int ans1 = 3;
int ans2 = 7;
int ans3 = 1;
int one, two, three;
String inData1, inData2, inData3;
JButton[] button;
//constructs the combolock object
public ComboNumber()
{
//sets flowlayout
getContentPane().setLayout(new FlowLayout());
Container c = getContentPane();
//creates buttons
button = new JButton[10];
for(int i = 0; i < button.length; ++i) {
button[i] = new JButton("" + i);
//adds buttons to the frame
c.add(button[i]);
//registers listeners with buttons
button[i].addActionListener(this);
}
//sets commands for the buttons (useless)
//sets title for frame
setTitle("ComboLock");
}
//end combolock object
//listener object
public void actionPerformed(ActionEvent evt)
{
Object o = evt.getSource();
for(int i = 0; i < button.length; ++i) {
if(button[i] == o) {
// it is button[i] that was cliked
// act accordingly
return;
}
}
}
//end listener object
//main method
public static void main (String[] args)
{
//calls object to format window
ComboNumber frm = new ComboNumber();
//WindowQuitter class to listen for window closing
WindowQuitter wQuit = new WindowQuitter();
frm.addWindowListener(wQuit);
//sets window size and visibility
frm.setSize(500, 500);
frm.setVisible(true);
}
//end main method
}
//end main class
//window quitter class
class WindowQuitter extends WindowAdapter
{
//method to close the window
public void windowClosing(WindowEvent e)
{
//exits the program when the window is closed
System.exit(0);
}
//end method
}
//end class
The basic idea is simple.
You need two things.
What the combination actually is
What the user has guessed
So. You need to add two variables. One contains the combination/secret, the other contains the guesses.
private String secret = "123";
private String guess = "";
This allows you to make the combination as long as you like ;)
Then in your actionPerformed method, you need to add the most recent button click to the guess, check it against the secret and see if they've made a good guess. If the length of the guess passes the number of characters in the secret, you need to reset the guess.
public void actionPerformed(ActionEvent evt) {
Object o = evt.getSource();
if (o instanceof JButton) {
JButton btn = (JButton) o;
guess += btn.getText();
if (guess.equals(secret)) {
JOptionPane.showMessageDialog(this, "Welcome Overloard Master");
dispose();
} else if (guess.length() >= 3) {
JOptionPane.showMessageDialog(this, "WRONG", "Wrong", JOptionPane.ERROR_MESSAGE);
guess = "";
}
}
}

Trouble with RadioButtons and booleans connection

Well its weird. I am not good with radiobuttons by the way. But I made a JPanel program in netbeans which includes a RadioButton. You enter all this information with JTextFields(no problem) and then lastly I had a JButton which you click the choice you want. Then I have a JButton that takes all the information and outputs this. For the RadioButton, I first entered the usual:
family = new JRadioButton("Family", true);
friend = new JRadioButton("Friend");
relative = new JRadioButton("Relative");
friendFriend = new JRadioButton("Friend of Friend");
ButtonGroup group = new ButtonGroup();
group.add (friend);
group.add (family);
group.add (relative);
group.add (friendFriend);
(I'm not sure if I needed a listner for the RadioButtons or not but my program still seems to "crash" no matter what).
then I had one action listner for the JButton which included all the textfields and radio buttons. But the RadioButton is the issue.
In the action listner I had:
Object source = event.getSource();
if (source == family)
relation1 = true;
else
if (source == friend)
relation2 = true;
else
if(source == relative)
relation3 = true;
else
if(source == friendFriend)
relation4 = true;
Then I made a relation class:
public class Relation {
private boolean arrayFamily, arrayFriend, arrayRelative, arrayFriendFriend;
public Relation(boolean relation1, boolean relation2, boolean relation3,
boolean relation4)
{
this.arrayFamily = relation1;
this.arrayFriend = relation2;
this.arrayRelative = relation3;
this.arrayFriendFriend = relation4;
}
public String relations ()
{
String relationship = null;
if(arrayFamily && !arrayFriend && !arrayRelative && !arrayFriendFriend == true)
{
relationship = "Family";
}
else
if(arrayFriend && !arrayFamily && !arrayRelative &&
!arrayFriendFriend == true)
{
relationship = "Friend";
}
else
if(arrayRelative && !arrayFamily && !arrayFriend &&
!arrayFriendFriend == true)
{
relationship = "Relative";
}
else
if(arrayFriendFriend && !arrayFamily && !arrayFriend &&
!arrayRelative == true)
{
relationship = "Friend of a Friend";
}
return relationship;
}
}
LASTLY back in the action listner, I implementer this class:
Relation relationship = new Relation(relation1, relation2, relation3
, relation4);
String arrayRelation = relationship.relations();
I lastly included arrayRelation in an array but the array worked fine.
My problem is that the output of the array for my RadioButtons keeps reading "null" (most likey because this code: String relationship = null;). I assume this means that none of my if else statements were satisfied and I really dont know why.
Also important to point out is that if I click submit without clicking any radio button (the button stays on "family"), it reads null. If I click a button once it works perfectly reading the string I intended. But if I click another button afterwards and click submit again, the string goes back to "null".
I know its lengthy but I would really appreciate any help because I am lost.
P.S. some parts of my code are repetitive because I was playing around trying to fix the problem.
I suggest you handle your action events separately, for example:
family.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
familyActionPerformed(evt);
}
});
Then implement familyActionPerformed(evt):
private void familyActionPerformed(java.awt.event.ActionEvent evt) {
// every click on family radio button causes the code here to be executed
relation1 = true;
}
Also write an event handler for the button you click, like this:
submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Here test the state of each radio button
relation1 = family.isSelected();
relation2 = friend.isSelected();
relation3 = relative.isSelected();
relation4 = friendFriend.isSelected();
}
MORE EDIT:
Doing what you're doing with NetBeans should be very easy. Here are tutorials that will clear it all up for you:
Tutorial 1
Tutorial 2
I explain the solution again:
Using 'family' button as an example, in your constructor where you have created and initialised your GUI components do this:
JRadioButton family = new JRadioButton();
// do any other thing you want to do to this button and finally..
family.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
familyActionPerformed(evt);
}
});
JButton submit = new JButton("Submit");
submit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitActionPerformed(evt);
}
});
Then somewhere create these methods:
private void familyActionPerformed(java.awt.event.ActionEvent evt){
// each time family is selected, you code processes the lines below:
...
}
private void submiteActionPerformed(java.awt.event.ActionEvent evt){
relation1 = family.isSelected();
relation2 = friend.isSelected();
relation3 = relative.isSelected();
relation4 = friendFriend.isSelected();
}
Do something similar for the rest of the RadioButtons.
I think that you're making things way too complex for yourself. If all you want is the String of the JRadioButton pressed, then use the ButtonGroup to get it for you. It can return the ButtonModel of the selected JRadioButton (if any one was selected), and from that you can extract the actionCommand String, although you'll have to remember to set this when you create your JRadioButton.
For example:
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class JRadioExample extends JPanel {
private static final String[] RADIO_TITLES = { "Family", "Friend",
"Relative", "Friend or Relative" };
private ButtonGroup btnGrp = new ButtonGroup();
public JRadioExample() {
for (int i = 0; i < RADIO_TITLES.length; i++) {
JRadioButton rBtn = new JRadioButton(RADIO_TITLES[i]);
rBtn.setActionCommand(RADIO_TITLES[i]); // ***** this is what needs to
// be set
btnGrp.add(rBtn);
add(rBtn);
}
add(new JButton(new BtnAction("Get Chosen Selection")));
}
private class BtnAction extends AbstractAction {
public BtnAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent evt) {
ButtonModel model = btnGrp.getSelection();
if (model != null) {
String actionCommand = model.getActionCommand();
System.out.println("Selected Button: " + actionCommand);
} else {
System.out.println("No Button Selected");
}
}
}
private static void createAndShowGui() {
JRadioExample mainPanel = new JRadioExample();
JFrame frame = new JFrame("JRadioExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How to call different actionListeners?

My program has one button, and the other one is a JTextField. The action listener for the button and the textfield are different. I'm using:
textfield.addActionListener(this);
button.addActionListener(this);
... inside my constructor.
They both do the same actionListener. How can I call their respective methods?
You are implementing ActionListener in the class of both components. So, when an action happens, actionPerformed method of the class is called for both of them. You can do following to separate them:
1-Create a separate class and implement ActionListener interface in it and add it as a actionListener for one of the components.
2-In actionPerformed method, there is a parameter with ActionEvent type. Call getSource method of it and check if it returns the object of JTextField or JButton by putting an if statement and do separate things accordingly.
Obviously both components share an ActionListener. If you want to determine which component generated the ActionEvent, invoke getSource(). And from there, you can typecast (if needed), and then invoke that particular component's methods.
For me the easiest way to do what is asked is the following:
textfield.addActionListener(this);
button.addActionListener(this);
...
public void actionPerformed(ActionEvent e){
if( e.getSource().getClass().equals(JTextField.class) ){
System.out.println("textfield");
//Código para el textfield
}
if( e.getSource().getClass().equals(JButton.class) ){
System.out.println("JButton");
//Código para el JButton
}
}
When an action listener is activated, because someone click your button, the method actionPerformed is called. As you havae set this as an action listener, you should have a method actionPerformed in your class. This is the method called in both cases.
Something like:
class MyClass implements ActionListener {
public MyClass() {
...
textfield.addActionListener(this) ;
button.addActionListener(this) ;
...
}
public void actionPerformed(ActionEvent e) {
// This is the method being called when:
// - the button is clicked and
// - the textfield activated
}
}
Though if you have not given your sample code, but I can understand what is there.
Here is an example of how to add listener to any JComponent. (Dont try to run this code!!!)
import java.awt.Button;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class EventListeners extends JFrame implements ActionListener {
TextArea txtArea;
String Add, Subtract, Multiply, Divide;
int i = 10, j = 20, sum = 0, Sub = 0, Mul = 0, Div = 0;
public void init() {
txtArea = new TextArea(10, 20);
txtArea.setEditable(false);
add(txtArea, "center");
Button b = new Button("Add");
Button c = new Button("Subtract");
Button d = new Button("Multiply");
Button e = new Button("Divide");
// YOU ARE DOING SOMETHING LIKE THIS
// THIS WILL WORK, BUT CAN BE A BAD EXMPLE
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
add(b);
add(c);
add(d);
add(e);
}
public void actionPerformed(ActionEvent e) {
sum = i + j;
txtArea.setText("");
txtArea.append("i = " + i + "\t" + "j = " + j + "\n");
Button source = (Button) e.getSource();
// you can work with them like shown below
Button source = (Button) e.getSource();
if (source.getLabel() == "Add") {
txtArea.append("Sum : " + sum + "\n");
}
if (source.getLabel() == "Subtract") {
txtArea.append("Sub : " + Sub + "\n");
}
if (source.getLabel() == "Multiply") {
txtArea.append("Mul = " + Mul + "\n");
}
if (source.getLabel() == "Divide") {
txtArea.append("Divide = " + Div);
}
}
}
UPDATE
You should do something like below
Button b = new Button("Add");
Button c = new Button("Subtract");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// implement what is expected for b button
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// implement what is expected for c button
}
});
// and so on...
// but yes we can improve it
Just set different ActionCommands on each component.
In the actionPerformed method you can check the ActionCommand of the event:
private static final String TEXT_CMD = "text"; // or something more meaningful
private static final String BUTTON_CMD = "button";
...
textfield.setActionCommand(TEXT_CMD);
textfield.addActionListener(this);
button.setActionCommand(BUTTON_CMD);
button.addActionListener(this);
...
public void actionPerformed(ActionEvent ev) {
switch (ev.getActionCommand()) {
case TEXT_CMD:
// do textfield stuff here
break;
case BUTTON_CMD:
// do button stuff here
break;
default:
// error message?
break;
}
}

Categories

Resources