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.
Related
I've been trying to make a game for a school project and wanted to add some easter eggs, but in order to do so I need to detect key input. I've been looking up how to do this for a while and couldn't find any ways that work.
The setup I'm using is making a JOptionPane and creating it with a JDialog to make a title and add an icon to the window.
Here's my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyAdapter;
public class ObamaSimulator {
public static void main(String[] args) {
JLabel label; // text in JOptionPane
label = new JLabel("<html><center><b style = 'font-size: 40px; color: red;'>WELCOME</b><p style = 'width: 175px;'><br> To Obama Simulator. In this game you are obama, there isn't really much else to say <br>(The story will tell you more)<br>[press OK to continue or X to quit]", SwingConstants.CENTER);
String choice = JText("Yes", null, label, "Welcome!"); // Runs JText with option 1, option 2, label, and title, and outputs with the option they chose
if(choice == "Yes"){
game();
}else{
System.out.println("Baboon closed the window :(");
label = new JLabel("<html><center><p style = 'width: 175px;'>Game Closed", SwingConstants.CENTER);
JText("OK", null, label, null);
System.exit(0); // Used to end the program, IDK why it dosn't end by it's self
}
}
public static String JText(String op1, String op2, JLabel label, String title){
Object[] options; // Options in JOptionPane
JFrame frm = new JFrame(); // Frame used to make JOptionPane have icon
frm.setIconImage(new ImageIcon("Obama (1).gif").getImage()); // Sets icon of JOptionPane window
if(op1 == null){ // Checks if an option is missing
options = new Object[] {op2};
}else if(op2 == null){
options = new Object[] {op1};
}else{
options = new Object[] {op1, op2};
}
if(title == null){ // Checks if title is missing
title = "Obama Simulator";
}
JOptionPane jp = new JOptionPane(label , JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,null, options, options[0]); // Creates basic JOptionPane
JDialog dialog = jp.createDialog(frm, title); // Finishes by adding icon and title
dialog.setSize(350, 300); // Sets size
dialog.setLocationRelativeTo(null); // Centers the Window
dialog.setResizable(true); // Needed to make icon
dialog.addKeyListener(new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
// Nothing
}
#Override
public void keyPressed(KeyEvent e) {
// Nothing
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP){
System.out.println("up");
}
}
});
dialog.setVisible(true); // Sets JOptionPane visible
String choice = (String) jp.getValue(); // Sets Choice to variable
return choice; // Sends choice back to meathod
}
public static void game(){
JLabel label;
String choice;
System.out.println("Baboon picked yes");
label = new JLabel("<html><center><p style = 'width: 175px; font-size: 10px;'>You are Obama, having a lovely day in Minecraft, feeding your dog. You need more quarts and Redstone blocks to build a lighthouse by the sea. While running to your portal room you find an untamed wolf, do you want to tame it?", SwingConstants.CENTER);
choice = JText("Tame", "Dont tame", label, null);
if(choice == "Tame"){
System.out.println("Baboon picked tame");
label = new JLabel("<html><center><p style = 'width: 175px; font-size: 10px;'>You shove a bone deep into the mouth of the wolf. You tame it but it makes you feel horrible, maybe it will make you feel better if you dye the collar?", SwingConstants.CENTER);
choice = JText("Dye", "Dont dye", label, null);
if(choice == "Dye"){
System.out.println("Baboon Dyed");
}
}
// System.exit(0);
}
}
I tried to use keyListener on the dialog, but it doesn't work. I've tried other basic examples and they work, I just have no clue what's wrong with mine.
You're going to want to avoid KeyListener. When ever you have another focusable component on the screen, it's not going to work.
Instead, you'll want to look at How to Use Key Bindings.
choice == "Yes" is not how you compare Strings in Java, you'll want to use "Yes".equals(choice) instead.
I'd also suggesting having a look at How to Use CardLayout as another means for flipping the UI ;)
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
public class ObamaSimulator {
public static void main(String[] args) {
JLabel label; // text in JOptionPane
label = new JLabel("<html><center><b style = 'font-size: 40px; color: red;'>WELCOME</b><p style = 'width: 175px;'><br> To Obama Simulator. In this game you are obama, there isn't really much else to say <br>(The story will tell you more)<br>[press OK to continue or X to quit]", SwingConstants.CENTER);
String choice = JText("Yes", null, label, "Welcome!"); // Runs JText with option 1, option 2, label, and title, and outputs with the option they chose
if ("Yes".equals(choice)) {
game();
} else {
System.out.println("Baboon closed the window :(");
label = new JLabel("<html><center><p style = 'width: 175px;'>Game Closed", SwingConstants.CENTER);
JText("OK", null, label, null);
System.exit(0); // Used to end the program, IDK why it dosn't end by it's self
}
}
public static String JText(String op1, String op2, JLabel label, String title) {
Object[] options; // Options in JOptionPane
JFrame frm = new JFrame(); // Frame used to make JOptionPane have icon
frm.setIconImage(new ImageIcon("Obama (1).gif").getImage()); // Sets icon of JOptionPane window
if (op1 == null) { // Checks if an option is missing
options = new Object[]{op2};
} else if (op2 == null) {
options = new Object[]{op1};
} else {
options = new Object[]{op1, op2};
}
if (title == null) { // Checks if title is missing
title = "Obama Simulator";
}
JOptionPane jp = new JOptionPane(label, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); // Creates basic JOptionPane
JDialog dialog = jp.createDialog(frm, title); // Finishes by adding icon and title
dialog.pack();//setSize(350, 300); // Sets size
dialog.setLocationRelativeTo(null); // Centers the Window
dialog.setResizable(true); // Needed to make icon
InputMap im = jp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = jp.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "up");
am.put("up", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Up");
}
});
//
//dialog.addKeyListener(new KeyListener() {
//
// #Override
// public void keyTyped(KeyEvent e) {
// // Nothing
// }
//
// #Override
// public void keyPressed(KeyEvent e) {
// // Nothing
// }
//
// #Override
// public void keyReleased(KeyEvent e) {
//
// if (e.getKeyCode() == KeyEvent.VK_UP) {
// System.out.println("up");
// }
//
// }
//});
dialog.setVisible(true); // Sets JOptionPane visible
String choice = (String) jp.getValue(); // Sets Choice to variable
return choice; // Sends choice back to meathod
}
public static void game() {
JLabel label;
String choice;
System.out.println("Baboon picked yes");
label = new JLabel("<html><center><p style = 'width: 175px; font-size: 10px;'>You are Obama, having a lovely day in Minecraft, feeding your dog. You need more quarts and Redstone blocks to build a lighthouse by the sea. While running to your portal room you find an untamed wolf, do you want to tame it?", SwingConstants.CENTER);
choice = JText("Tame", "Dont tame", label, null);
if ("Tame".equals(choice)) {
System.out.println("Baboon picked tame");
label = new JLabel("<html><center><p style = 'width: 175px; font-size: 10px;'>You shove a bone deep into the mouth of the wolf. You tame it but it makes you feel horrible, maybe it will make you feel better if you dye the collar?", SwingConstants.CENTER);
choice = JText("Dye", "Dont dye", label, null);
if ("Dye".equals(choice)) {
System.out.println("Baboon Dyed");
}
}
// System.exit(0);
}
}
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
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);
}
});
}
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.
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 = "";
}
}
}