I cannot enter two digit number to be calculator. I also cannot get the clear C operator working as well. My dot sign seems to be not working as well. The code below creates a calculator using java swing and does addition, multiplication,subtraction and divisiion of a single digit number.
//First the necessary packages are imported
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**#return a BODMAS calculator using Javax Swing and awt
* *#author Cihan Altunok
*#version 1
*/
//implementing ActionListener to listen to events. JFrame is also extended to add support to Swing components
public class Calculator extends JFrame implements ActionListener {
//declaring some variables to be used in our program
JFrame guiCalculatorFrame;
JPanel buttonPanel;
JTextArea numberCalculator;
int calculatorOpr=0;
int currentCalculation;
//EventQueue invokeLater is used to ensure the run method is called in the dispatch thread of the EventQueue
//declaring the constructor for the class
public Calculator()
{
//instantiating guiCalculatorFrame
guiCalculatorFrame=new JFrame();
//the red cross sign drawn to exit the window
guiCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiCalculatorFrame.setTitle("Calculator");
//setting the size of the frame
guiCalculatorFrame.setSize(400,400);
//The setLocationRelativeTo has been set to null to center the window
guiCalculatorFrame.setLocationRelativeTo(null);
//JTextField is created to allow a set of characters to be entered
numberCalculator=new JTextArea();
//setting the alignment of JTextField along the RIGHT axis
numberCalculator.setAlignmentX(JTextField.RIGHT);
//making the textfield not editable
numberCalculator.setEditable(false);
//container containing the components in the north region
guiCalculatorFrame.add(numberCalculator, BorderLayout.NORTH);
//panel is created and we will add buttons to the panel later in the program
buttonPanel=new JPanel();
//setting Layout to GridLayout to lay the components in a rectangular grid
buttonPanel.setLayout(new GridLayout(5,5));
//adding the buttons to the frame. Putting the buttons in the center
guiCalculatorFrame.add(buttonPanel,BorderLayout.CENTER);
// a following for loop is done to add the numberButtons
for (int i=0;i<10;i++)
{
addNumberButton(buttonPanel,String.valueOf(i));
}
//next the five mathematical operators are added
addActionButton(buttonPanel,1,"+");
addActionButton(buttonPanel,2,"-");
addActionButton(buttonPanel,3,"*");
addActionButton(buttonPanel,4,"/");
addActionButton(buttonPanel,5,"^2");
addActionButton(buttonPanel,6,"C");
addActionButton(buttonPanel,7,"^");
addActionButton(buttonPanel,8,".");
//equalSign Button is created
JButton equalsSignButton=new JButton("=");
//the action command for the equal sign button is set
equalsSignButton.setActionCommand("=");
equalsSignButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
//checking if the numberCalculator field is a valid mathematical operator
{
if (!numberCalculator.getText().isEmpty())
{
//turning text into integer
int number=Integer.parseInt(numberCalculator.getText());
// doing a series of if statements for the list of operations
if (calculatorOpr==1)
{
int calculate=currentCalculation+number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==2)
{
int calculate=currentCalculation-number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==3)
{
int calculate=currentCalculation*number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==4)
{
int calculate=currentCalculation/number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==5)
{
int calculate=currentCalculation*currentCalculation;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==6)
{
numberCalculator.setText("");
}
else if (calculatorOpr==7)
{
int calculate=(int) Math.sqrt(Integer.parseInt(numberCalculator.getText()));
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==8)
{
numberCalculator.append(".");
}
}
}
});
//adding equals sign to the panel
buttonPanel.add(equalsSignButton);
//setting the visibility to True so the frame can be seen
guiCalculatorFrame.setVisible(true);
}
//passing two paremeters to the addNumberButton method
private void addNumberButton(Container contain, String name) {
JButton buttonOne=new JButton(name);
//setting the action command for the button created above
buttonOne.setActionCommand(name);
buttonOne.addActionListener(this);
//adding buttonOne to the container
contain.add(buttonOne);
}
//passing three parameters to the addActionButton method
private void addActionButton(Container contain, int i, String text) {
JButton buttonOne=new JButton(text);
//setting the action command for the button created above
buttonOne.setActionCommand(text);
//creating a new class
Operators addAction=new Operators(i);
buttonOne.addActionListener(addAction);
//adding buttonOne to the container
contain.add(buttonOne);
}
public void actionPerformed(ActionEvent event) {
//returning the command string associated with this string
String i=event.getActionCommand();
//setting the Text to the specified String
numberCalculator.setText(i);
}
//creating an inner class and implementing ActionListener
private class Operators implements ActionListener
{
private int operators;
//creating a constructor and passing a parameter
public Operators(int operation)
{
operators=operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalculation=Integer.parseInt(numberCalculator.getText());
calculatorOpr=operators;
}
}
}*
The problem was you were overwrting the text field. and the action listener for C button was wrong. This will solve your basic problems, but some work remaining. For instance you are not handling the . at the moment.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
// declaring some variables to be used in our program
JFrame guiCalculatorFrame;
JPanel buttonPanel;
JTextArea numberCalculator;
int calculatorOpr = 0;
int currentCalculation;
boolean isOperatorActive = false;
// EventQueue invokeLater is used to ensure the run method is called in the
// dispatch thread of the EventQueue
// declaring the constructor for the class
public Calculator() {
// instantiating guiCalculatorFrame
guiCalculatorFrame = new JFrame();
// the red cross sign drawn to exit the window
guiCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiCalculatorFrame.setTitle("Calculator");
// setting the size of the frame
guiCalculatorFrame.setSize(400, 400);
// The setLocationRelativeTo has been set to null to center the window
guiCalculatorFrame.setLocationRelativeTo(null);
// JTextField is created to allow a set of characters to be entered
numberCalculator = new JTextArea();
// setting the alignment of JTextField along the RIGHT axis
numberCalculator.setAlignmentX(JTextField.RIGHT);
// making the textfield not editable
numberCalculator.setEditable(false);
// container containing the components in the north region
guiCalculatorFrame.add(numberCalculator, BorderLayout.NORTH);
// panel is created and we will add buttons to the panel later in the
// program
buttonPanel = new JPanel();
// setting Layout to GridLayout to lay the components in a rectangular
// grid
buttonPanel.setLayout(new GridLayout(5, 5));
// adding the buttons to the frame. Putting the buttons in the center
guiCalculatorFrame.add(buttonPanel, BorderLayout.CENTER);
// a following for loop is done to add the numberButtons
for (int i = 0; i < 10; i++) {
addNumberButton(buttonPanel, String.valueOf(i));
}
// next the five mathematical operators are added
addActionButton(buttonPanel, 1, "+");
addActionButton(buttonPanel, 2, "-");
addActionButton(buttonPanel, 3, "*");
addActionButton(buttonPanel, 4, "/");
addActionButton(buttonPanel, 5, "^2");
addActionButton(buttonPanel, 6, "C");
addActionButton(buttonPanel, 7, "^");
addActionButton(buttonPanel, 8, ".");
// equalSign Button is created
JButton equalsSignButton = new JButton("=");
// the action command for the equal sign button is set
equalsSignButton.setActionCommand("=");
equalsSignButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// checking if the numberCalculator field is a valid mathematical
// operator
isOperatorActive = true;
if (!numberCalculator.getText().isEmpty()) {
// turning text into integer
int number = Integer.parseInt(numberCalculator.getText());
// doing a series of if statements for the list of
// operations
int calculate = 0;
switch (calculatorOpr) {
case 1:
calculate = currentCalculation + number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 2:
calculate = currentCalculation - number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 3:
calculate = currentCalculation * number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 4:
calculate = currentCalculation / number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 5:
calculate = currentCalculation * currentCalculation;
numberCalculator.setText(Integer.toString(calculate));
break;
case 7:
calculate = (int) Math.sqrt(Integer
.parseInt(numberCalculator.getText()));
numberCalculator.setText(Integer.toString(calculate));
break;
case 8:
numberCalculator.append(".");
break;
default:
break;
}
}
}
});
// adding equals sign to the panel
buttonPanel.add(equalsSignButton);
// setting the visibility to True so the frame can be seen
guiCalculatorFrame.setVisible(true);
}
// passing two parameters to the addNumberButton method
private void addNumberButton(Container contain, String name) {
JButton buttonOne = new JButton(name);
// setting the action command for the button created above
buttonOne.setActionCommand(name);
buttonOne.addActionListener(this);
// adding buttonOne to the container
contain.add(buttonOne);
}
// passing three parameters to the addActionButton method
private void addActionButton(Container contain, int i, String text) {
JButton buttonOne = new JButton(text);
// setting the action command for the button created above
buttonOne.setActionCommand(text);
// creating a new class
Operators addAction = new Operators(i);
buttonOne.addActionListener(addAction);
// adding buttonOne to the container
contain.add(buttonOne);
}
public void actionPerformed(ActionEvent event) {
// returning the command string associated with this string
String i = event.getActionCommand();
// setting the Text to the specified String
if(isOperatorActive){
numberCalculator.setText(i);
isOperatorActive = false;
} else {
numberCalculator.setText(numberCalculator.getText() + i);
}
}
// creating an inner class and implementing ActionListener
private class Operators implements ActionListener {
private int operators;
// creating a constructor and passing a parameter
public Operators(int operation) {
operators = operation;
}
public void actionPerformed(ActionEvent event) {
isOperatorActive = true;
switch (operators) {
case 6:
numberCalculator.setText("");
currentCalculation = 0;
calculatorOpr = 0;
break;
case 8:
isOperatorActive = false;
default:
currentCalculation = Integer.parseInt(numberCalculator.getText());
calculatorOpr = operators;
break;
}
}
}
}
import javax.swing.*;
import java.awt.*;
/*
# Author 12CSE54
# Date 29.10.14
*/
public class calculator1 extends JFrame
{
public calculator1() {
initComponents();
}
int a,b,c;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a+b;
jTextField3.setText(String.valueOf(c));
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a-b;
jTextField3.setText(String.valueOf(c));
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a*b;
jTextField3.setText(String.valueOf(c));
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a/b;
jTextField3.setText(String.valueOf(c));
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
public static void main(String ar[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new calculator1().setVisible(true);
}
});
}
Related
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
This question already has an answer here:
How do I make my JWindow window always stay focused
(1 answer)
Closed 7 years ago.
First of all i don't know good english.
I want to make a window and have 2 labels and 2 fields. One label for x-coordinate and 1 for y-coordinate.Fields will show the x-y coordinates.
Coordinates are from mouse from full screen (meaning outside from window).
I prefer to be on clicking but i have read from other answers and questions that this will not act as we want (because it loses focus).So i tried not to be on clicking
I want help with my code because it has 2 problems-mistakes:
1) window can't close
2)when mouse is not moving fields take the same coordinates forever and i want take 1 time the coordinates and don't take the same until it moves.
here is the full code:
package mouseClick;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MouseEventDemo extends Frame implements MouseListener {
// Private variables
private TextField tfMouseX; // mouse-click-x
private TextField tfMouseY; // mouse-click-y
// Constructor
public MouseEventDemo() {
//handle the close-window button.
WindowDestroyer listener =new WindowDestroyer();
addWindowListener(listener);
setLayout(new FlowLayout()); // sets layout
// Label
add(new Label("X-Click: ")); // adds component
// TextField
tfMouseX = new TextField(10); // 10 columns
tfMouseX.setEditable(false); // read-only
add(tfMouseX); // adds component
// Label
add(new Label("Y-Click: ")); // adds component
// TextField
tfMouseY = new TextField(10);
tfMouseY.setEditable(false); // read-only
add(tfMouseY); // adds component
// fires the MouseEvent
addMouseListener(this);
setTitle("MouseEvent Demo"); // sets title
setSize(350, 100); // sets initial size
setVisible(true); // shows
}
public static void main(String[] args) {
new MouseEventDemo();
}
// MouseEvent handlers
public void mouseClicked(MouseEvent e) {
while (true){
tfMouseX.setText(Integer.toString(xmouse()));
tfMouseY.setText(Integer.toString(ymouse()));
}
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public class WindowDestroyer extends WindowAdapter {
public void windowClosing (WindowEvent e) {
System.exit(0);
}
}
public int xmouse() {
Point simiox = MouseInfo.getPointerInfo().getLocation();
int x= (int) simiox.getX();
return x;
}
public int ymouse() {
Point simioy = MouseInfo.getPointerInfo().getLocation();
int y=(int) simioy.getY();
return y;
}
}
in order to close the window, use
windowVariable.seDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
where windowVariable is the variable for you JFrame
EDIT:
For returning the value only once, try using a for loop and a hasMoved boolean. For instance,
for (int i = 0; i < 1; i++){
tfMouseX.setText(Integer.toString(xmouse()));
if (hasMoved == true)
i = -1;
}
then do the same for the y.
this basically checks to see if the mouse has moved, and if it has not, it will set the label only once. If it has, it will update the label.
Is there a way to know if a JButton was clicked consecutively? Consider my code.
public void actionPerformed(ActionEvent arg0) {
String bucky[] = new String[2];
String firstclick = null, secondclick = null;
clicks++;
if (clicks == 1) {
bucky[0] = firstclick;
} else if(clicks == 2) {
bucky[1] = secondclick;
if (bucky[0] == bucky[1]) {
//This JButton was clicked twice in a row.
}
}
This code checks the entire number of times my JButton was clicked and displays the message "This button was clicked twice in a row". What I want is to compare two clicks from that button and see if they come one after the other rather than counting the number of clicks made. Or is there a built-in function that does this?
Just use a field remembering what the last clicked button was:
private JButton lastButtonClicked;
...
someButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (lastButtonClicked == e.getSource()) {
displayError();
}
else {
lastButtonClicked = (JButton) e.getSource();
doSomething();
}
}
});
Of course, you'll have to do the same thing with all the other buttons.
I have a different approach to your problem:
You want to not allow the user to press the same button in some group of buttons twice in a row.
You're solutions so far have tried to check which button was pressed last, and then warn the user if the same button has been pressed in a row.
Perhaps a better solution is to create a construct that simply doesn't allow the user to press the same button twice in a row.
You can create your ButtonGroup like object that selectively disables the last button pressed, and enables all the other buttons.
You would give this class an add(AbstractButton btn) method to allow you to add all the buttons that you wish to behave this way to it. The button would then be added to an ArrayList.
You would give it a single ActionListener that listens to all the buttons. Whenever the actionPerformed method has been pressed, it enables all of the buttons, and then selectively disables the last button pressed.
For instance consider my class below:
public class NoRepeatButtonGroup implements ActionListener {
private List<AbstractButton> btnList = new ArrayList<>();
public void add(AbstractButton btn) {
btnList.add(btn);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
((AbstractButton) evt.getSource()).setEnabled(false);
}
public void reset() {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
}
}
If you create a single object of this in your class that creates the buttons, and add each button to the object of this class, your code will automatically disable the last button pressed, and re-enable it once another button has been pressed.
You could use it like so:
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
NoRepeatButtonGroup noRepeatButtonGroup = new NoRepeatButtonGroup();
JButton yesButton = new JButton(new YesAction());
noRepeatButtonGroup.add(yesButton);
buttonPanel.add(yesButton);
JButton noButton = new JButton(new NoAction());
noRepeatButtonGroup.add(noButton);
buttonPanel.add(noButton);
JButton maybeButton = new JButton(new MaybeAction());
noRepeatButtonGroup.add(maybeButton);
buttonPanel.add(maybeButton);
For example, here is a proof of concept minimal runnable example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class NoneInARowBtns {
private static void createAndShowGui() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
NoRepeatButtonGroup noRepeatButtonGroup = new NoRepeatButtonGroup();
int buttonCount = 5;
for (int i = 0; i < buttonCount; i++) {
JButton btn = new JButton(new ButtonAction(i + 1));
noRepeatButtonGroup.add(btn);
buttonPanel.add(btn);
}
JOptionPane.showMessageDialog(null, buttonPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ButtonAction extends AbstractAction {
public ButtonAction(int i) {
super("Button " + i);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand() + " Pressed");
}
}
class NoRepeatButtonGroup implements ActionListener {
private List<AbstractButton> btnList = new ArrayList<>();
public void add(AbstractButton btn) {
btnList.add(btn);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
((AbstractButton) evt.getSource()).setEnabled(false);
}
public void reset() {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
}
}
When the above program runs, and when the second button is pressed, you will see that it is disabled:
Then when the 3rd button has been pressed, the 2nd is re-enabled, and the 3rd one is disabled:
And etc for the 4th button....
A global variable arrau of booleans, one for each button, set true on first click, set false or second, sjould do it
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 = "";
}
}
}
As you can see from my code I am totally missing a whole gaping concept here. My goal is to have the user input:
Jbutton text field:
text orientation and mnemonic
I pass that info to my Button class that checks for errors and gives back a button already defined.
Then populate the JFrame with said button as to the user specs.
BASIC and obviously a course question, but I'm at my wit's end here. This is the first time I've asked for help so please take it easy on me.
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
/**
* This class will create a button using the Button class and with user input to define the instance
* of the Button Class.
*
*/
public class CreateButton extends JPanel
{
// instance variables
private static String userIn; // user input
private static Button userButton; // button to be manipulated
public static JButton createdButton; // finished button
/**
* Contructor for the CreateButton class.
*/
public static void main (String [] args)
{
System.out.println("\nThis program will create a button with some input for you.");
System.out.println("What would you like to call this button?");
userIn = StringIn.get();
userButton = new Button();
userButton.buttonText(userIn);
System.out.println("\nYou can orient your text on the button in the vertical and");
System.out.println("horizontal axis. We will start with the vertical. Where would you like");
System.out.println("the text, on the top, center, or bottom?");
userIn = StringIn.get();
String vertical = userIn;
System.out.println("\nNext let's select the horizontal alignment. Would you like the text");
System.out.println("aligned to the left, center, or right?");
userIn = StringIn.get();
String horizontal = userIn;
userButton.textPosition(vertical,horizontal);
System.out.println("\nFinally let's add a mnemonic or hotkey to the button. Pick a letter");
System.out.println("from a-z on the keyboard and you can activate the button by pushing");
System.out.println("ALT + your letter of choice. Please enter your letter:");
userIn = StringIn.get();
userButton.buttonMnemomic(userIn);
System.out.println("\nGreat let's create and see this button.");
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame = new JFrame("Create a Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
CreateButton newContentPane = new CreateButton();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
My button error checker code is as follows:
import javax.swing.AbstractButton;
import javax.swing.JButton;
/**
* This class will demonstrate the use of a button.
*
*/
public class Button
{
// instance variables
protected JButton myButton; // button to be created and manipulated
private String myButtonText; // text on the button
private String myButtonVerticalTextPosition;
private String myButtonHorizontalTextPosition;
private String myButtonMnemonic; // hotkey for the button
/**
* Constructor for objects of class Button
*/
public Button()
{
}
/**
*Set button text. String input.
*/
public void buttonText(String textIn)
{
myButtonText = textIn;
}
/**
*Set button text position. String input for vertical (top, center, bottom) and horizontal
*(left, center, right).
*/
public void textPosition(String verticalIn, String horizontalIn)
{
myButtonVerticalTextPosition = verticalIn;
boolean validInput = false;
do
{
if ((myButtonVerticalTextPosition.compareToIgnoreCase("top") == 0)||
(myButtonVerticalTextPosition.compareToIgnoreCase("centre") == 0) ||
(myButtonVerticalTextPosition.compareToIgnoreCase("center") == 0) ||
(myButtonVerticalTextPosition.compareToIgnoreCase("bottom") == 0))
{
validInput = true;
} else
{
System.out.println("\nPlease enter top, center, or bottom for vertical position:");
myButtonVerticalTextPosition = StringIn.get();
}
} while (validInput == false);
myButtonHorizontalTextPosition = horizontalIn;
validInput = false;
do
{
if ((myButtonHorizontalTextPosition.compareToIgnoreCase("left") == 0) ||
(myButtonHorizontalTextPosition.compareToIgnoreCase("centre") == 0) ||
(myButtonHorizontalTextPosition.compareToIgnoreCase("center") == 0) ||
(myButtonHorizontalTextPosition.compareToIgnoreCase("right") == 0))
{
validInput = true;
} else
{
System.out.println("\nPlease enter left, center, or right for horizontal position:");
myButtonHorizontalTextPosition = StringIn.get();
}
} while (validInput == false);
}
/**
*Set button mnemomic. String input for mnemomic [a-z].
*/
public void buttonMnemomic(String mnemomicIn)
{
myButtonMnemonic = mnemomicIn;
boolean validInput = false;
do
{
if (myButtonMnemonic.length() > 1)
{
System.out.println("\nPlease enter a letter from a-z: ");
myButtonMnemonic = StringIn.get();
} else if (!myButtonMnemonic.matches("^[a-zA-Z]+$"))
{
System.out.println("\nPlease enter a letter from a-z: ");
myButtonMnemonic = StringIn.get();
} else if ((myButtonMnemonic.length() == 1) &&
(myButtonMnemonic.matches("^[a-zA-Z]+$")))
{
validInput = true;
}
} while (validInput == false);
}
/**
*Create button. Void method to create the button to the variables provided.
*/
public void createButton()
{
// create new button
myButton = new JButton(myButtonText);
// set text position
switch (myButtonVerticalTextPosition)
{
case "top":
myButton.setVerticalTextPosition(AbstractButton.TOP);
break;
case "centre":
myButton.setVerticalTextPosition(AbstractButton.CENTER);
break;
case "center":
myButton.setVerticalTextPosition(AbstractButton.CENTER);
break;
case "bottom":
myButton.setVerticalTextPosition(AbstractButton.BOTTOM);
break;
default:
System.err.format("%n%s is an invalid entry.", myButtonVerticalTextPosition);
break;
}
switch (myButtonHorizontalTextPosition)
{
case "left":
myButton.setHorizontalTextPosition(AbstractButton.LEADING);
break;
case "centre":
myButton.setHorizontalTextPosition(AbstractButton.CENTER);
break;
case "center":
myButton.setHorizontalTextPosition(AbstractButton.CENTER);
break;
case "right":
myButton.setHorizontalTextPosition(AbstractButton.TRAILING);
break;
default:
System.err.format("%n%s is an invalid entry.", myButtonVerticalTextPosition);
break;
}
// set button mnemonic
StringBuilder hotKey = new StringBuilder("KeyEvent.VK_");
hotKey.append(myButtonMnemonic.toUpperCase());
myButton.setMnemonic(hotKey.charAt(0));
// set tool tip text
myButton.setToolTipText("Push the button. You know you want to.");
}
/**
*Returns a JButton for the button type.
*/
public JButton returnButton()
{
return myButton;
}
}
This all works up to the part where you add the "createdButton". If I make it a default button it goes through the motions and puts up the default button.
FYI this is my StringIn code:
import java.util.Scanner;
import java.io.IOException;
/**
* This class will allow the user to type in string from the console.
*
*/
public class StringIn
{
// instance variables
private static String userIn;
public static String get()
{
try (Scanner in = new Scanner(System.in))
{
userIn = new String(in.nextLine()); // Read the string from console.
}
return userIn;
}
}
For the StringIn class just do:
import java.util.Scanner;
public class StringIn
{
// instance variables
private static Scanner scanner = new Scanner(System.in);
public static String get(){
return scanner.nextLine();
}
}
Edit2:
Okay, so I copied your code into my IDE and the error I got was an error originating in your StringIn class. ( I don't remember actually but that doesn't really matter. )
Your StringIn class should look like the above example.
For your createAndShowGUI() function:
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame = new JFrame("Create a Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane. ( Why were you even doing this? )
frame.add(createdButton); //( To display the actual button you need to
//add it to the frame)
//Display the window.
frame.pack();
frame.setVisible(true);
}
Do like that^
I couldn't get the mnemonic related things to work properly, and I don't want to spend so much time on it, so I just removed them.
The orientation thingies didn't work either.
Put this at the bottom in main(String args[])
createdButton = userButton.createButton(); // Make createButton() return Button;
You don't need JButton anywhere in your code except for this part:
public class Button extends JButton
// And of course the import statement...
You can use Button.TOP instead of AbstractButton.TOP which will get rid of an import statement for you.