GUI Calculator (Swing, BorderLayout, etc.)
I am a bit of a crossroads and am needing some advice. I am trying to create a Calculator in a Window (GUI) that looks similar to a keypad. I have three files that I am working on but cannot get any of them to compile without errors. I am confused as to what I have left out and/or where I have taken a wrong turn. I will post them below and would greatly appreciate any insight and/or direction as to how to make this work! Also, I have heard from a "birdie" that there may be some problems that occur if the files are compiled out of order....does this make sense to anyone? Thank you in
advance for any help--Christle
Constants.java file
//Christle Chumney
import java.awt.*;
public interface Constants
Color FUNCTION_COLOR = Color.red;
Color OPERATOR_COLOR = Color.blue;
Color NUMBER_COLOR = Color.black;
}calculator.java file
//Christle Chumney
import java.awt.*;
public class Calculator {
public static void main(String[] args){
theApp = new Calculator();
theApp.init();
public void init() {
aWindow = new CalculatorFrame("My Calculator");
aWindow.setBounds(10, 10, 250, 250);
aWindow.setVisible(true); }
private static CalculatorFrame aWindow;
private static Calculator theApp;
}calculatorFrame.java file
//Christle Chumney
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
public class CalculatorFrame extends JFrame implements Constants //, ActionListener
private Calculator theApp;
JPanel top, bottom;
JTextField display;
JButton button;
// Constructor
public CalculatorFrame(String title)
setTitle(title); // Set the window title
this.theApp = theApp;
JMenuBar swingMenuBar = new JMenuBar();
JMenu swingMenu = new JMenu("swingMenu");
JMenuItem swingMenuItem1, swingMenuItem2, swingMenuItem3;
swingMenuBar.add(swingMenu);
setJMenuBar(swingMenuBar);
JMenu applicationMenu = new JMenu("Function"); // Create Application menu
applicationMenu.setMnemonic('A'); // Create shortcut
// Construct the application pull down menu
exitItem = applicationMenu.add("Exit"); // Add exit item
exitItem.setAccelerator(KeyStroke.getKeyStroke('X',Event.CTRL_MASK ));
applicationMenu.add(exitItem);
menuBar.add(applicationMenu); // Add the file menu
makeButtons();
public void makeButtons() {
BorderLayout border = new BorderLayout();
Container content = getContentPane();
content.setLayout(border);
top = new JPanel(new BorderLayout());
display = new JTextField("");
display.setEditable(false);
display.setBackground(Color.white);
display.setHorizontalAlignment(display.RIGHT);
top.add(display);
bottom = new JPanel();
GridLayout grid = new GridLayout(5,4,5,5);
bottom.setLayout(grid);
bottom.add(button = new JButton("C"));
button.setForeground(FUNCTION_COLOR);
bottom.add(button = new JButton("<=="));
button.setForeground(FUNCTION_COLOR);
bottom.add(button = new JButton("%"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("/"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("7"));
bottom.add(button = new JButton("8"));
bottom.add(button = new JButton("9"));
bottom.add(button = new JButton("*"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("4"));
bottom.add(button = new JButton("5"));
bottom.add(button = new JButton("6"));
bottom.add(button = new JButton("-"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("1"));
bottom.add(button = new JButton("2"));
bottom.add(button = new JButton("3"));
bottom.add(button = new JButton("+"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("0"));
bottom.add(button = new JButton("+/-"));
bottom.add(button = new JButton("."));
bottom.add(button = new JButton("="));
button.setForeground(OPERATOR_COLOR);
Container content = aWindow.getContentPane();
content.setLayout(new BorderLayout());
content.add(top, BorderLayout, NORTH);
content.add(bottom, BorderLayout, CENTER);
private JMenuBar menuBar = new JMenuBar(); // Window menu bar
private JMenuItem exitItem; // application menu item
}Thanks in advance (again)-
Christle
HERE R U .JAVA FILES AND THEY WORK FINE NOW NO ERRORS NOTHING JUST THAT U HAVE TO CODE THE EVENTS OF UR APPLICATION
ANYOTHER HELP U NEED UR MOST WELCOME
VIJAY
// CALCULATORFRAME.JAVA
//Christle Chumney
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
public class CalculatorFrame extends JFrame implements Constants //,ActionListener
private Calculator theApp;
JPanel top, bottom;
JTextField display;
JButton button;
// Constructor
public CalculatorFrame(String title)
setTitle(title);
// Set the window title
this.theApp = theApp;
JMenuBar swingMenuBar = new JMenuBar();
JMenu swingMenu = new JMenu("swingMenu");
JMenuItem swingMenuItem1, swingMenuItem2, swingMenuItem3;
swingMenuBar.add(swingMenu);
setJMenuBar(swingMenuBar);
JMenu applicationMenu = new JMenu("Function");
// Create Application menu
applicationMenu.setMnemonic('A');
// Create shortcut
// Construct the application pull down menu
exitItem = applicationMenu.add("Exit");
// Add exit item exitItem.setAccelerator(KeyStroke.getKeyStroke('X',Event.CTRL_MASK )); applicationMenu.add(exitItem);
menuBar.add(applicationMenu);
// Add the file menu
makeButtons();
public void makeButtons()
BorderLayout border = new BorderLayout();
Container content = getContentPane();
content.setLayout(border);
top = new JPanel(new BorderLayout());
display = new JTextField("");
display.setEditable(false);
display.setBackground(Color.white);
display.setHorizontalAlignment(display.RIGHT);
top.add(display);
bottom = new JPanel();
GridLayout grid = new GridLayout(5,4,5,5);
bottom.setLayout(grid);
bottom.add(button = new JButton("C"));
button.setForeground(FUNCTION_COLOR);
bottom.add(button = new JButton("<=="));
button.setForeground(FUNCTION_COLOR);
bottom.add(button = new JButton("%"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("/"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("7"));
bottom.add(button = new JButton("8"));
bottom.add(button = new JButton("9"));
bottom.add(button = new JButton("*"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("4"));
bottom.add(button = new JButton("5"));
bottom.add(button = new JButton("6"));
bottom.add(button = new JButton("-"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("1"));
bottom.add(button = new JButton("2"));
bottom.add(button = new JButton("3"));
bottom.add(button = new JButton("+"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("0"));
bottom.add(button = new JButton("+/-"));
bottom.add(button = new JButton("."));
bottom.add(button = new JButton("="));
button.setForeground(OPERATOR_COLOR);
Container content1 = this.getContentPane();
content.setLayout(new BorderLayout());
content1.add(top, BorderLayout.NORTH);
content1.add(bottom, BorderLayout.CENTER);
private JMenuBar menuBar = new JMenuBar();
// Window menu bar
private JMenuItem exitItem;
// application menu item
// CALCULATOR.JAVA
import java.awt.*;
public class Calculator
public static void main(String[] args)
{ theApp = new Calculator();
theApp.init();
public void init()
aWindow = new CalculatorFrame("My Calculator");
aWindow.setBounds(10, 10, 250, 250);
aWindow.setVisible(true);
private static CalculatorFrame aWindow;
private static Calculator theApp;
// CONSTANTS.JAVA
import java.awt.*;
public interface Constants
Color FUNCTION_COLOR = Color.red;
Color OPERATOR_COLOR = Color.blue;
Color NUMBER_COLOR = Color.black;
Similar Messages
-
Please Help/ GUI Calculator
I'm trying to create a GUI Calculator but cannot get my program to compile. Please could someone assistm, thanks.
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalculatorFrame extends JFrame
private Container contentPane;
//The componenets used in the calculator
private JTextField display;
private JButton addition;
private JButton subtract;
private JButton multiply;
private JButton divide;
private JButton mod;
private JButton enter;
private JButton [] digits;
//End of components
//Integer representations for the arithmetic operations needed
private final static int ADD = 1;
private final static int SUB = 2;
private final static int MUL = 3;
private final static int DIV = 4;
private final static int MOD = 5;
//ENd of arithmethic operations
//Integer holding the operator that the user requested
private int op;
//Boolean variable to help perform the calculations
private boolean firstFilled;
private boolean clearScreen;
//Constructor for the class
public CalculatorFrame()
contentPane=new Container();
this.setSize(400,300); //sets the size of the frame
this.setTitle("MIS 222 Calculator"); //sets the title of the frame
//allows the "X" box in the upper right hand corner to close the entire application
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane=this.getContentPane(); //gets the content pane
//Methods
addDisplay();
addDigits();
addDigitActionListeners();
addOperation();
private void addDisplay()
JLabel displayLab = new JLabel("Answer");
JPanel north = new JPanel();
north.add(displayLab);
contentPane.add(north, "North");
//diplay was already declared above the constructor
display = new JTextField(25);
//adding the components to the panel
north.add(displayLab);
north.add(display);
//adding the panel to frame's content pane
contentPane.add(north, "North");
//Declaring the global digits array
private void addDigits()
//Add 1 large panel to hold the 3 inner panels
JPanel digPanel = new JPanel();
//Set the panel's preferred size so that it will keep everything in line
digPanel.setPreferredSize(new Dimension(200, 275));
//Initialize the top 3 digits' JPanel and set its preferrd size
JPanel topDigits = new JPanel();
topDigits.setPreferredSize(new Dimension(200,60));
//Initialize the middle 2 digits' JPanel and set its preferred size
JPanel midDigits = new JPanel();
midDigits.setPreferredSize(new Dimension(200,60));
//Initialize the bottom digits' JPanel and set its preferred size
JPanel botDigits = new JPanel();
botDigits.setPreferredSize(new Dimension(200, 75));
//Initialize the JButton array
digits = new JButton[11];
//Initialize each of the top Panel's digit buttons, and add it to the top panel
for(int i=1; i<4; i++)
String lab=(new Integer(i)).toString();
digits=new JButton(lab);
topDigits.add(digits[i]);
//Adding the top Digit Panel to the overall digit panel
digPanel.add(topDigits, BorderLayout.CENTER);
//Adding the middle Digit Panel to the overall digit panel
digPanel.add(midDigits, BorderLayout.CENTER);
//Adding the bottom Digit Panel to the overall digit panel
digPanel.add(botDigits, BorderLayout.CENTER);
//Add the overall digit Panel to the Frame's contentpane
contentPane.add(digPanel, BorderLayout.CENTER);
//Method created to add the DigitAction Listeners
addDigitActionListeners();
//Method created to add all of the DigitActionListeners
private void addDigitActionListeners()
for(int i=0; i<10; i++)
digits[i].addActionListener(new DigitActionListener(i));
digits[10].addActionListener(new DigitActionListener("."));
//DigitActionListener class
public class DigitActionListener implements ActionListener
private String myNum;
public DigitActionListener(int num)
myNum=""+num;
public DigitActionListener(String num)
myNum=num;
public void actionPerformed(ActionEvent e)
if(display.getText().equals("Please enter a valid number")|| clearScreen)
clearScreen=false;
display.setText("");
//OperatorActionListener class
public void OpActionListener implements ActionListener
private int myOpNum;
public OpActionListener(int op)
myOpNum=op;
public void actionPerformed(ActionEvent e)
{ //Checks to see if the user has already enterd a number
if(!firstFilled)
try{
//Parse the number entered
String number=display.getText();
dNum1=Double.parseDouble(number);
//Sets the flag for the firstFilled to true
firstFilled=true
//Sets the op variable so when the "Enter" button is pressed, it will know which operation to perform
op=myOpNum;
//Clears the textbox
display.setText("");
catch(Exception er)
display.setText("Please enter a valid number");
//This is the second number being entered
else{
try{
String number=display.getText();
String result;
dNum2=Double.parseDouble(number);
firstFilled=true;
op=myOpNum;
display.setText("");
catch(Exception er)
display.setText("Please enter a valid number");
private void addOperation()
JPanel opPanel=new JPanel();
opPanel.setPreferredSize(new Dimension(75,200));
JButton clear = new JButton("C");
JButton addition = new JButton("+");
JButton subtraction = new JButton("-");
JButton multiply = new JButton("*");
JButton divide = new JButton("/");
JButton mod = new JButton("%");
JButton enter = new JButton("Enter");
addition.addActionListener(new OpActionListener(ADD));
subtraction.addActionListener(new OpActionListener(SUB));
multiply.addActionListener(new OpActionListener(MUL));
divide.addActionListener(new OpActionListener(DIV));
mod.addActionListener(new OpActionListener(MOD));
clear.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
display.setText("");
firstFilled=false;
enter.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
double result;
String answer="";
String number = display.getText();
dNum2 = Double.parseDouble(number);
dNum1=Double.parseDouble(number);
switch(op)
case ADD:
result = dNum1 + dNum2;
break;
case SUB:
result = dNum1 - dNum2;
break;
case MUL:
result = dNum1 * dNum2;
break;
case DIV:
result = dNum1 / dNum2;
break;
default:
result= -1.0;
break;
if(result==(int)result)
answer=(new Integer((int)result)).toString();
else
answer=(new Double(result)).toString();
display.setText(answer);
clearScreen=true;
firstFilled=false;
dNum1=0;
dNum2=0;
opPanel.add(clear);
opPanel.add(addition);
opPanel.add(subtraction);
opPanel.add(multiply);
opPanel.add(divide);
opPanel.add(mod);
opPanel.add(enter);
contentPane.add(opPanel, "East");
//Creating the frame object
public class CalculatorMain
public void main(String[] args)
CalculatorFrame cf=new CalculatorFrame();
cf.show();
ERRORS THAT I HAVE!!:
javac calculatorframe.javacalculatorframe.java:150: '(' expected
public void OpActionListener implements ActionListener
^
calculatorframe.java:7: class CalculatorFrame is public, should be declared in a file named CalculatorFrame.java
public class CalculatorFrame extends JFrame
^
calculatorframe.java:54: cannot resolve symbol
symbol : method addOperation ()
location: class CalculatorFrame
addOperation();
^
3 errors
>Hi, actually it's all written there:
>
ERRORS THAT I HAVE!!:
javac calculatorframe.javacalculatorframe.java:150: '(' expected
public void OpActionListener implements
ActionListenerpublic void ... is part of a possible method signature. That's probably why the compiler expects '(' as this is need for a method.
To define a class use:
public class ... (or better: private class ..., if the class is not used outside of this file.
^
calculatorframe.java:7: class CalculatorFrame is
public, should be declared in a file named
CalculatorFrame.java
public class CalculatorFrame extends JFrame
^As it says, you defined a class CalculatorFrame in a file calculatorframe.java. But the file name should be the same as the class name (case sensitive). Java classes should start with capital letters, so rename the file to:
CalculatorFrame.java
calculatorframe.java:54: cannot resolve symbol
symbol : method addOperation ()
location: class CalculatorFrame
addOperation();
^
3 errors
>You didn't declare the method 'addOperation' (-> cannot resolve symbol; which simbol: method addOperation (); where: location: class CalculatorFrame; you see it's all there)
Note there is a method called 'addOperation' in the class OpActionListener, but not in CalculatorFrame.
Note I didn't read the code, just the error messages. I hope this helps.
-Puce -
Hello everyone! I'm trying to create a GUI Calculator but cannot get my program to compile. Please could someone assist me, thanks.
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalculatorFrame extends JFrame
private Container contentPane;
//The componenets used in the calculator
private JTextField display;
private JButton addition;
private JButton subtract;
private JButton multiply;
private JButton divide;
private JButton mod;
private JButton enter;
private JButton [] digits;
//End of components
//Integer representations for the arithmetic operations needed
private final static int ADD = 1;
private final static int SUB = 2;
private final static int MUL = 3;
private final static int DIV = 4;
private final static int MOD = 5;
//ENd of arithmethic operations
//Integer holding the operator that the user requested
private int op;
//Boolean variable to help perform the calculations
private boolean firstFilled;
private boolean clearScreen;
//Constructor for the class
public CalculatorFrame()
contentPane=new Container();
this.setSize(400,300); //sets the size of the frame
this.setTitle("MIS 222 Calculator"); //sets the title of the frame
//allows the "X" box in the upper right hand corner to close the entire application
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane=this.getContentPane(); //gets the content pane
//Methods
addDisplay();
addDigits();
addDigitActionListeners();
addOperation();
private void addDisplay()
JLabel displayLab = new JLabel("Answer");
JPanel north = new JPanel();
north.add(displayLab);
contentPane.add(north, "North");
//diplay was already declared above the constructor
display = new JTextField(25);
//adding the components to the panel
north.add(displayLab);
north.add(display);
//adding the panel to frame's content pane
contentPane.add(north, "North");
//Declaring the global digits array
private void addDigits()
//Add 1 large panel to hold the 3 inner panels
JPanel digPanel = new JPanel();
//Set the panel's preferred size so that it will keep everything in line
digPanel.setPreferredSize(new Dimension(200, 275));
//Initialize the top 3 digits' JPanel and set its preferrd size
JPanel topDigits = new JPanel();
topDigits.setPreferredSize(new Dimension(200,60));
//Initialize the middle 2 digits' JPanel and set its preferred size
JPanel midDigits = new JPanel();
midDigits.setPreferredSize(new Dimension(200,60));
//Initialize the bottom digits' JPanel and set its preferred size
JPanel botDigits = new JPanel();
botDigits.setPreferredSize(new Dimension(200, 75));
//Initialize the JButton array
digits = new JButton[11];
//Initialize each of the top Panel's digit buttons, and add it to the top panel
for(int i=1; i<4; i++)
String lab=(new Integer(i)).toString();
digits=new JButton(lab);
topDigits.add(digits);
//Adding the top Digit Panel to the overall digit panel
digPanel.add(topDigits, BorderLayout.CENTER);
//Adding the middle Digit Panel to the overall digit panel
digPanel.add(midDigits, BorderLayout.CENTER);
//Adding the bottom Digit Panel to the overall digit panel
digPanel.add(botDigits, BorderLayout.CENTER);
//Add the overall digit Panel to the Frame's contentpane
contentPane.add(digPanel, BorderLayout.CENTER);
//Method created to add the DigitAction Listeners
addDigitActionListeners();
//Method created to add all of the DigitActionListeners
private void addDigitActionListeners()
for(int i=0; i<10; i++)
digits.addActionListener(new DigitActionListener(i));
digits[10].addActionListener(new DigitActionListener("."));
//DigitActionListener class
public class DigitActionListener implements ActionListener
private String myNum;
public DigitActionListener(int num)
myNum=""+num;
public DigitActionListener(String num)
myNum=num;
public void actionPerformed(ActionEvent e)
if(display.getText().equals("Please enter a valid number")|| clearScreen)
clearScreen=false;
display.setText("");
//OperatorActionListener class
public void OpActionListener implements ActionListener
private int myOpNum;
public OpActionListener(int op)
myOpNum=op;
public void actionPerformed(ActionEvent e)
{ //Checks to see if the user has already enterd a number
if(!firstFilled)
try{
//Parse the number entered
String number=display.getText();
dNum1=Double.parseDouble(number);
//Sets the flag for the firstFilled to true
firstFilled=true
//Sets the op variable so when the "Enter" button is pressed, it will know which operation to perform
op=myOpNum;
//Clears the textbox
display.setText("");
catch(Exception er)
display.setText("Please enter a valid number");
//This is the second number being entered
else{
try{
String number=display.getText();
String result;
dNum2=Double.parseDouble(number);
firstFilled=true;
op=myOpNum;
display.setText("");
catch(Exception er)
display.setText("Please enter a valid number");
private void addOperation()
JPanel opPanel=new JPanel();
opPanel.setPreferredSize(new Dimension(75,200));
JButton clear = new JButton("C");
JButton addition = new JButton("+");
JButton subtraction = new JButton("-");
JButton multiply = new JButton("*");
JButton divide = new JButton("/");
JButton mod = new JButton("%");
JButton enter = new JButton("Enter");
addition.addActionListener(new OpActionListener(ADD));
subtraction.addActionListener(new OpActionListener(SUB));
multiply.addActionListener(new OpActionListener(MUL));
divide.addActionListener(new OpActionListener(DIV));
mod.addActionListener(new OpActionListener(MOD));
clear.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
display.setText("");
firstFilled=false;
enter.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
double result;
String answer="";
String number = display.getText();
dNum2 = Double.parseDouble(number);
dNum1=Double.parseDouble(number);
switch(op)
case ADD:
result = dNum1 + dNum2;
break;
case SUB:
result = dNum1 - dNum2;
break;
case MUL:
result = dNum1 * dNum2;
break;
case DIV:
result = dNum1 / dNum2;
break;
default:
result= -1.0;
break;
if(result==(int)result)
answer=(new Integer((int)result)).toString();
else
answer=(new Double(result)).toString();
display.setText(answer);
clearScreen=true;
firstFilled=false;
dNum1=0;
dNum2=0;
opPanel.add(clear);
opPanel.add(addition);
opPanel.add(subtraction);
opPanel.add(multiply);
opPanel.add(divide);
opPanel.add(mod);
opPanel.add(enter);
contentPane.add(opPanel, "East");
//Creating the frame object
public class CalculatorMain
public void main(String[] args)
CalculatorFrame cf=new CalculatorFrame();
cf.show();
ERRORS THAT I HAVE!!:
javac calculatorframe.javacalculatorframe.java:150: '(' expected
public void OpActionListener implements ActionListener
^
calculatorframe.java:7: class CalculatorFrame is public, should be declared in a file named CalculatorFrame.java
public class CalculatorFrame extends JFrame
^
calculatorframe.java:54: cannot resolve symbol
symbol : method addOperation ()
location: class CalculatorFrame
addOperation();
^
3 errors
>Here I did this for someone in the 'new to' forum about 2 weeks back. They had some really awful code they say they got from a java book -cannot recall the author, but I do know his work should be burned and the person executed with a mercy killing (I still haven't recovered from the shock of this and I think most of the regular contributors in these forums could write FAR BETTER books than this clown)
Hmm... I do rant sometimes. Erm, you're welcome - this is their rebuild;-import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
JButton []buttons = new JButton[25];
private JTextField display= new JTextField("0.0",12);
String status = " Status : ";
JLabel label = new JLabel(status);
private double sum = 0.0d;
private String nums = "";
private double arg = 0.0d;
private double tot = 0.0d;
private boolean start = true,div,mult,add,sub;
private String memory = "0";
java.text.DecimalFormat df=new java.text.DecimalFormat("#,##0.0####");
Font f = new Font("Times New Roman", Font.BOLD,14);
Color midBlue = new Color(20, 15, 140);
public Calculator(){
super();
setTitle("Java Calculator");
JPanel mainPan = new JPanel();
mainPan.setLayout(new BorderLayout() );
JPanel textPanel = new JPanel();
textPanel.setBackground(midBlue);
textPanel.setLayout(new BorderLayout());
display.setHorizontalAlignment(JTextField.RIGHT);
label.setForeground(Color.white);
display.setFont(new Font("",0,14));
display.setEditable(false);
display.setBackground(Color.white);
label.setFont(new Font("Arial",0,12));
JPanel emptyPan = new JPanel();
emptyPan.setBackground(midBlue);
JPanel emptyP1 = new JPanel();
emptyP1.setBackground(midBlue);
JPanel emptyP2 = new JPanel();
emptyP2.setBackground(midBlue);
textPanel.add("North", label);
textPanel.add("Center", display);
textPanel.add("South",emptyPan );
textPanel.add("East",emptyP1 );
textPanel.add("West",emptyP2 );
JPanel butPanel = new JPanel();
butPanel.setBackground(midBlue);
butPanel.setLayout(new GridLayout(5, 5, 10, 10));
String []str = {"","","","CE","C","1","2","3","/","RM","4","5","6",
"*","CM","7","8","9","+","M+","0",".","=","-","M-"};
for(int j=0; j<25; j++) {
if(j<3) {
buttons[j] = new JButton(str[j]);
butPanel.add(buttons[j]);
else {
buttons[j] = new JButton(str[j]);
buttons[j].addActionListener(this);
buttons[j].setFont(f);
buttons[j].setBorder(BorderFactory.createRaisedBevelBorder());
butPanel.add(buttons[j]);
JPanel emptyPan1 = new JPanel();
emptyPan1.setBackground(midBlue);
JPanel emptyPan2 = new JPanel();
emptyPan2.setBackground(midBlue);
JPanel emptyPan3 = new JPanel();
emptyPan3.setBackground(midBlue);
mainPan.add("North", textPanel);
mainPan.add("Center", butPanel);
mainPan.add("South", emptyPan1);
mainPan.add("East", emptyPan2);
mainPan.add("West", emptyPan3);
getContentPane().add(mainPan);
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
if ((s.equals("1"))||(s.equals("2"))||(s.equals("3"))||(s.equals("4"))
||(s.equals("5"))||(s.equals("6"))||(s.equals("7"))||(s.equals("8"))
||(s.equals("9"))||(s.equals("0"))||(s.equals("."))){
nums += s;
display.setText(nums);
if (s.equals("/")){
arg=Double.parseDouble(display.getText());
nums="";
div=true;
if (s.equals("*")){
arg=Double.parseDouble(display.getText());
nums="";
mult=true;
if (s.equals("-")){
arg=Double.parseDouble(display.getText());
nums="";
sub=true;
if (s.equals("+")){
arg=Double.parseDouble(display.getText());
nums="";
add=true;
if (s.equals("=")){
tot=Double.parseDouble(display.getText());
if(div)tot=arg/tot;
if(mult)tot=arg*tot;
if(add)tot=arg+tot;
if(sub)tot=arg-tot;
display.setText(df.format(tot));
div=mult=sub=add=false;
public static void main(String[] args){
Calculator frame = new Calculator();
frame.setVisible(true);
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
Image onFrame = Toolkit.getDefaultToolkit().getImage("flag.gif") ;
frame.setIconImage(onFrame);
frame.setLocation(300, 240);
frame.setResizable(false);
frame.pack();
} -
I am trying to create a GUI calculator which:
-must use the JOptionPane class to create dialog boxes for user input and
output.
-If the user attempts to divide by 0, you must print a message to that effect (e.g.,
"division by 0 not allowed").
-If the user enters an invalid operator, you must print a message to that effect
(e.g., "operation not supported").
My Program will not work, and any help would be greatly appreciated!
import javax.swing.JOptionPane;
public class GUI {
String numberString =
JOptionPane.showInputDialog("Welcome to my GUI Calculator!\n The following operations are supported:\n +(addition), -(subtraction), *(multiplication)\n /(division),and ^(exponent)\n\n Enter your calculation separated by spaces and press OK.\n Example:2.5 + 3");
int firstSpace =
numberString.indexOf(" ");
double answer;
double
operand1 = Double.parseDouble(numberString.substring(0,firstSpace));
double
operand2 = Double.parseDouble(numberString.substring(firstSpace+3,numberString.length()));
char
operator = numberString.charAt(firstSpace+1);
while (operator == "+")
answer = operand1 + operand2;
while (operator == "-")
answer = operand1 - operand2;
while (operator == "*")
answer = operand1 * operand2;
while (operator == "/")
{ if (operand2 == 0)
JOptionPane.showInputDialog("Division by 0 not allowed!");
else
answer = operand1 / operand2;
while (operator == "^")
answer = Math.pow(operand1, operand2);
while (operator != "+, -, *, /, ^")
JOptionPane.showInputDialog("Operation not supported.");
JOptionPane.showMessageDialog("numberString = answer");
System.exit(0);
}When you post code, please wrap it in [code] [/code] tags so it's easy to read.
You're confusing strings with characters. You read the operator as a character. But when you check it, you compare it with Strings (you can tell they're Strings because you're using double quotes). You should be using single quotes there.
Your code makes a lot of assumptions about the format of the data it's given, for example the number of spaces and where they'll appear.
And this part:while (operator != "+, -, *, /, ^") There's absolutely no reason why that would work. Where did you get the idea that was a thing to do? If you want to see if the operator is in a list of characters, there are a variety of things you can do, but probably the simplest is just to have five if/else statements. You're going to need those anyway when you do the math operation; when you get to the last one, just put an else statement saying that you don't recognize the operator. -
How to use annotation with GUI in swing
hi,
i am new to annotation. I know how to use this with classes, methods and java elements. I am developing a tool in applet to post comment on my notepad, but unable to find that how to use this with GUI of swing. I have gone through most of forums and tutorials but got no idea. Anyone could give me little idea.
Thanks>
i need to use the applet mousedown function in swing..>There is no such class as 'applet' in the JRE, Swing has an upper case 1st letter, functions in Java are generally referred to as methods, and there is no 'mousedown' method in the JRE.
OTOH a Swing JApplet inherits the mouseDown method from Component, and it was deprecated in Java 1.1. The documentation (JavaDocs) provides instructions on what to use instead.
>
is there any way to use it or any other alternative is available for this?
if can provide me a sample code.>If can provide me cash. Short of that, you might actually need to do some research/coding of your own.
As an aside. What does any of this have to do with Java 2D? -
I need good gui in swings for a library management system
i need good gui in swing. i need to develope a small application of library management system where a librarian and manager access the database. librarian take care of add,del,modify the records of customer and books. with good login screens. and the manager is to generate reports
Yup, create one. Good exercise.
Doing it myself right now, am loosing track of my own collection ;)
Don't have the multi-user part in place yet, it's no priority for me (I'll be creating a readonly web interface as an alternative to the read/write Swing interface for remote access). -
How to Transport Rate Tables/Calculation Sheets/Agreements etc
Hi All,
How to add Rate Tables/Calculation Sheets/Agreements etc in a Transport Request ?
Because while creating its not asking for Transport reequest.
Reply ASAP pls.
TM - 9.0
Thanks,
Michael.Hi Michael,
We has the following for facilitate our life.Create templates for main objects.
Then transport this objects (templates) and create again.
Best regards.
Renato Okamoto -
HC - A scientific, graphing, supp complex nums CLI and GUI calculator
I uploaded all three packages to AUR! Please use the PKGBUILDs there if you want to install this now. Thanks a lot goran'agar and foutrelis for help with the PKGBUILDs.
AUR links:
mapm : http://aur.archlinux.org/packages.php?ID=32319
hc : http://aur.archlinux.org/packages.php?ID=32321
hcg : http://aur.archlinux.org/packages.php?ID=32320
UPDATE (28.2.2010) : I now also finally have a github account where you can find the newest version of hc (cli only) which obviously has all the newest things I implemented but on the other hand it may be unstable. Anyway, here's the link : http://github.com/houbysoft/hc
Hello ArchLinux users,
some time ago, I was a little unsatisfied with existing calculators (either it was too memory/CPU-consuming (it had to work well, among others, on a 128MB RAM computer), or it lacked the functions I needed (f.ex. nCr and nPr)), and so I decided to write my own command-line (now there also is a GUI version) calculator.
Here is a little description:
The goal of this program is to provide an open source calculator with a
simple and easy-to-use interface, similar to a command prompt, but a lot of
options and a multitude of functions.
You can also type "help" in the command prompt if you need any help - or
contact me here.
There are two major versions of HC -- a CLI (command line interface) and a
GUI (graphical user interface).
To get you an idea, have some screenshots:
CLI version
GUI version
I thought some of you might like it, so I posted it here. It is of course open source (GPL v3) and cross-platform (precompiled for Linux and Windows).
The calculator's homepage is
http://houbysoft.com/hc/
If you're interested, you'll find a lot more details there.
Please post some feedback/criticism etc.; also please report any bugs - I started this project ~2 months ago so it is not yet completely stable and complete.
Thanks for reading, give it a try!
Last edited by y27 (2010-03-01 01:24:13)goran'agar wrote:I'm not able to create any PKGBUILD for the application itself as the website executes a php script before allowing the download.
Thanks a lot, I'll test it out soon.
If you'd help me with the PKGBUILD for my app itself, the full links are:
http://houbysoft.com/download/hc-VERSION-TYPE.tar.gz
where VERSION is the version number, so for example 0.4.2, and TYPE is either linux or src.
I'm not sure which format of URLs is needed so please ask me if you need something else.
Also, for windows versions, the urls are:
http://houbysoft.com/download/hc-VERSION-win.[b]zip[/b]
(in case you care).
tomd123 wrote:Feature requests: variable assignment and function declaration.
BTW, have you considered using the python interpretor for your calculations? If the functions you need aren't already in it, you can easily add them.
Functions and variables:
I'll put it on my roadmap
For the python interpreter : yes, I did, but dismissed it because:
- it's not very convenient - you have to retype stuff to floats if you don't want only integer results
- it's slow (again, this had to work and take a very small amount of CPU and memory on a 333MHz and 128 MB RAM system), and in algorithms where speed is crucial this would be even more of a concern
- I know about psyco to speed it up, but AFAIK it doesn't work on 64bit processors
- I wanted it to be small and minimalistic, installing a python distribution imo isn't
- I like programming, writing a calculator is fun -
Need Help to update the labels in the GUI syncronously - Swing application
Hello everyone,
I need some help regarding a swing application. I am not able to syncronously update the counters and labels that display on my Swing GUI as the application runs in the background. But when the running of application is completed, then the labels on the GUI are getting updated, But I want update the labels and counters on the GUI syncronously as the code executes... below I am giving the format of the code I have written..............
public class SwingApp extends JFrame{
// here i have declared the label and component varibles like...
private JTextField startTextField;
private JComboBox maxComboBox;
private JTextField logTextField;
private JTextField searchTextField;
private JLabel imagesDownloaded1;
private JLabel imagesDownloaded2;
private JLabel imagesDidnotDownload1;
private JLabel imagesDidnotDownload2;
private JButton startButton;
//now in the constructer.............
public Swing(){
//I used gridbaglayout and wrote the code for the GUI to appear....
startButton = new JButton("Start Downloading");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
actionSearch(); //actionSearch will contain all the code and the function calls of my application...........
}catch(Exception e1){
System.out.println(e1);
constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 5, 5);
layout.setConstraints(startButton, constraints);
searchPanel.add(startButton);
//update is a function which initiates a thread which updates the GUI. this function will be called to pass the required variables in the application
public void update(final int count_hits, final int counter_image_download1, final int didnot_download1) throws Exception{
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("entered into thread");
System.out.println("the variable that has to be set is " + count_hits);
server_hits_count.repaint(count_hits);
server_hits_count.setText( " "+ Integer.toString(count_hits));
imagesDownloaded2.setText(" " + Integer.toString(counter_image_download1));
imagesDidnotDownload2.setText(" " + Integer.toString(didnot_download1));
repaint();
//this.update(count_hits);
thread.start();
//Now in main............................
public static void main(String[] args){
Swing s = new Swing();
s.setVisible(true);
}//end of main
}//end of class SwingAbove I have given the skeleton code of my application........ Please tell me how to update the GUI syncronously...
Please its a bit urgent...............
Thank you very much in advance
chaitanyaFirst off, note that this question should have been posted in the Swing section.
GUI events run in a separate thread (the AWT / Event Dispatch Thread) than your program.
You should be invoking AWT/Swing events via SwingUtilities.invokeLater().
If for whatever reason you want to have the program thread wait for the event to process
you can use invokeAndWait().
http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html -
I'm making a calculator on netbeans and so far i have been able to get the interface and an the function of the number buttons. Also I got the plus button to work but it does not work after using it once. I have tried, but im stuck and can't firgure out what to do next plz help. This is the code i have:
* Calulator.java
* Created on April 3, 2008, 11:30 AM
package me;
* @author period4
public class Calulator extends javax.swing.JFrame {
/** Creates new form Calulator */
public Calulator() {
initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
jButton17 = new javax.swing.JButton();
Input = new javax.swing.JTextField();
Button1 = new javax.swing.JButton();
Button4 = new javax.swing.JButton();
Button7 = new javax.swing.JButton();
Button2 = new javax.swing.JButton();
Button5 = new javax.swing.JButton();
Button8 = new javax.swing.JButton();
Button3 = new javax.swing.JButton();
Button6 = new javax.swing.JButton();
Button9 = new javax.swing.JButton();
Button0 = new javax.swing.JButton();
ButtonPlus = new javax.swing.JButton();
ButtonMinus = new javax.swing.JButton();
ButtonMultiply = new javax.swing.JButton();
ButtonDecimal = new javax.swing.JButton();
ButtonPositiveNegative = new javax.swing.JButton();
ButtonDivide = new javax.swing.JButton();
ButtonEquals = new javax.swing.JButton();
jButton17.setText("jButton17");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Calculator");
Button1.setText("1");
Button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button1ActionPerformed(evt);
Button4.setText("4");
Button4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button4ActionPerformed(evt);
Button7.setText("7");
Button7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button7ActionPerformed(evt);
Button2.setText("2");
Button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button2ActionPerformed(evt);
Button5.setText("5");
Button5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button5ActionPerformed(evt);
Button8.setText("8");
Button8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button8ActionPerformed(evt);
Button3.setText("3");
Button3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button3ActionPerformed(evt);
Button6.setText("6");
Button6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button6ActionPerformed(evt);
Button9.setText("9");
Button9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button9ActionPerformed(evt);
Button0.setText("0");
Button0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button0ActionPerformed(evt);
ButtonPlus.setText("+");
ButtonPlus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonPlusActionPerformed(evt);
ButtonMinus.setText("-");
ButtonMultiply.setText("*");
ButtonDecimal.setText(".");
ButtonDecimal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonDecimalActionPerformed(evt);
ButtonPositiveNegative.setText("+/-");
ButtonDivide.setText("/");
ButtonEquals.setText("=");
ButtonEquals.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonEqualsActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Input, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(Button7, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(Button4, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(Button1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(Button2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Button5, 0, 0, Short.MAX_VALUE)
.addComponent(Button8, 0, 0, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(Button3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonPlus))
.addGroup(layout.createSequentialGroup()
.addComponent(Button6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonMinus))
.addGroup(layout.createSequentialGroup()
.addComponent(Button9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonMultiply))))
.addGroup(layout.createSequentialGroup()
.addComponent(ButtonDecimal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Button0)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonPositiveNegative)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonDivide)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonEquals)))
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(Input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Button1)
.addComponent(Button2)
.addComponent(Button3)
.addComponent(ButtonPlus))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Button4)
.addComponent(Button5)
.addComponent(Button6)
.addComponent(ButtonMinus))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Button7)
.addComponent(Button8)
.addComponent(Button9)
.addComponent(ButtonMultiply))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ButtonDecimal)
.addComponent(Button0)
.addComponent(ButtonPositiveNegative)
.addComponent(ButtonDivide)))
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(ButtonEquals, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(44, Short.MAX_VALUE))
pack();
}// </editor-fold>//GEN-END:initComponents
private void ButtonEqualsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonEqualsActionPerformed
if(operator.equals("+"))
solution = Double.parseDouble(integer1) + Double.parseDouble(integer2);
Input.setText(Double.toString(solution));
operator = null;
integer1 = "";
integer2 = "";
//Input.setText(Double.toString(solution));
solution = 0;
// TODO add your handling code here:
}//GEN-LAST:event_ButtonEqualsActionPerformed
private void ButtonPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonPlusActionPerformed
operator = "+";
// TODO add your handling code here:
}//GEN-LAST:event_ButtonPlusActionPerformed
private void ButtonDecimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonDecimalActionPerformed
Input.setText(".");// TODO add your handling code here:
}//GEN-LAST:event_ButtonDecimalActionPerformed
private void Button0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button0ActionPerformed
if(operator == null)
integer1 = integer1.concat("0");
Input.setText(integer1);
else
integer2 = integer2.concat("0");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button0ActionPerformed
private void Button9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button9ActionPerformed
if(operator == null)
integer1 = integer1.concat("9");
Input.setText(integer1);
else
integer2 = integer2.concat("9");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button9ActionPerformed
private void Button6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button6ActionPerformed
if(operator == null)
integer1 = integer1.concat("6");
Input.setText(integer1);
else
integer2 = integer2.concat("6");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button6ActionPerformed
private void Button3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button3ActionPerformed
if(operator == null)
integer1 = integer1.concat("3");
Input.setText(integer1);
else
integer2 = integer2.concat("3");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button3ActionPerformed
private void Button8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button8ActionPerformed
if(operator == null)
integer1 = integer1.concat("8");
Input.setText(integer1);
else
integer2 = integer2.concat("8");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button8ActionPerformed
private void Button5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button5ActionPerformed
if(operator == null)
integer1 = integer1.concat("5");
Input.setText(integer1);
else
integer2 = integer2.concat("5");
Input.setText(integer2);
// TODO and your handling code here:
}//GEN-LAST:event_Button5ActionPerformed
private void Button7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button7ActionPerformed
if(operator == null)
integer1 = integer1.concat("7");
Input.setText(integer1);
else
integer2 = integer2.concat("7");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button7ActionPerformed
private void Button4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button4ActionPerformed
if(operator == null)
integer1 = integer1.concat("4");
Input.setText(integer1);
else
integer2 = integer2.concat("4");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button4ActionPerformed
private void Button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button1ActionPerformed
if(operator == null)
integer1 = integer1.concat("1");
Input.setText(integer1);
else
integer2 = integer2.concat("1");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button1ActionPerformed
private void Button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button2ActionPerformed
if(operator == null)
integer1 = integer1.concat("2");
Input.setText(integer1);
else
integer2 = integer2.concat("2");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button2ActionPerformed
* @param args the command line arguments
double solution;
String integer1 = "";
String integer2 = "";
String operator;
public static void main(String args[])
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
new Calulator().setVisible(true);
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Button0;
private javax.swing.JButton Button1;
private javax.swing.JButton Button2;
private javax.swing.JButton Button3;
private javax.swing.JButton Button4;
private javax.swing.JButton Button5;
private javax.swing.JButton Button6;
private javax.swing.JButton Button7;
private javax.swing.JButton Button8;
private javax.swing.JButton Button9;
private javax.swing.JButton ButtonDecimal;
private javax.swing.JButton ButtonDivide;
private javax.swing.JButton ButtonEquals;
private javax.swing.JButton ButtonMinus;
private javax.swing.JButton ButtonMultiply;
private javax.swing.JButton ButtonPlus;
private javax.swing.JButton ButtonPositiveNegative;
private javax.swing.JTextField Input;
private javax.swing.JButton jButton17;
// End of variables declaration//GEN-END:variables
}Yeah. Seriously. I don't think anybody wants to wade through a whole bunch of IDE generated crap that you didn't bother to format with code tags.
I know I don't.
So maybe post some formatted relevent code (10 lines or less). -
XML document describing the application's GUI in SWING
Hii Javaites
Can i build Swing GUI from a XML document.
If yes , can anybody tell me how 2 go abt it.
Which parser will i need ?I would avoid it, only my opinion:
http://forum.java.sun.com/thread.jspa?threadID=725055
Jim -
hello frends,
I am new to java , i make instant messenger, But it is console based
i want to add gui to it , But i don't know any technology(Applet ,Swing)
So please help me how to make gui for instant messenger, I tried to start but i have no good tutorial, But i got problem in Taking on line user list, sush that when i click the name new dialog will appear, will you please tell me how to do it, and also suggest some good books,and link that help me to make my messenger gui.
Thank you
alokhi
am also doing same kind of program...
by using jtree we can list all the users...
its very easy ...
u can use sun tutorial itself -
GUI Problem (Swing JFrame/JPanel). HELP!
Hi,
I made an small application for calculate some things.
I download i piece of code for creating bar chart and i icluded in my code. But i have problem when i am trying to show the chart in the Frame. All the buttons, textfields, labels goes to left and half are hiding.
If i open the chart on a new frame i dont have problem.
the problem apears when after i put the panel in the frame i try to put the chart in the frame. Look the code:
add(p); //Put the panel in the Frame
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!that command mades me the problem!
Here are 2 screenshots
1. When i put the chart in the Frame (the problem)
http://www.iweb.gr/images/InFrame.jpg
2. When i put the chart on new frame (works fine)
http://www.iweb.gr/images/NewFrame.jpg
Hopes someone can help. Thanks
The code List:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
//The main class of the program
public class PlantFertilizer extends JFrame{//The main class is a subclass of Frame
private Label lN, lP,lK;//These show the value of the observable
public TextField tN, tP, tK;
private MyData thedata;//The observable we are going to watch
private double[] values=new double[3];
private String[] names=new String[3];
private String title;
public PlantFertilizer(){
thedata=new MyData();// create the observable
addWindowListener(new WindowAdapter(){//if user closes the Frame, quit
public void windowClosing(WindowEvent e){
System.exit(0);
setSize(400,500);//Set size
setTitle(getClass().getName()+" By Pantelis Stoumpis");
JPanel p = new JPanel(); //Make a panel for buttons and output
//Input Data Area
p.add(new Label("-------------------------Input Data Area--------------------------",Label.CENTER));
p.add(new Label("Nitrogen (N)"));
tN = new TextField();p.add(tN);
p.add(new Label("Phosphorus (P)"));
tP = new TextField();p.add(tP);
p.add(new Label("Potassium (K)"));
tK = new TextField();p.add(tK);
lN=new Label("N = %", Label.CENTER);
p.add(lN); //Put the N label in the panel
lP=new Label("P = %", Label.CENTER);
p.add(lP); //Put the P label in the panel
lK=new Label("K = %", Label.CENTER);
p.add(lK); //Put the K label in the panel
addButton(p,"Apply", //Apply new Values
new ActionListener(){
public void actionPerformed(ActionEvent evt){
int iNt = Integer.parseInt(tN.getText());
int iPt = Integer.parseInt(tP.getText());
int iKt = Integer.parseInt(tK.getText());
thedata.addOne(iNt,iPt,iKt); //which adds one to the observable
JFrame f = new JFrame();
f.setSize(400, 300);
values[0] = 40;
names[0] = "N";
values[1] = 20;
names[1] = "P";
values[2] = 30;
names[2] = "K";
f.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"));
f.setVisible(true);
addButton(p,"Close", //add a close button to quit the program
new ActionListener(){
public void actionPerformed(ActionEvent evt){
System.exit(0);
add(p); //Put the panel in the Frame
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!
//A utility function to add a button with a given title and action
public void addButton(Container c, String title,ActionListener a)
Button b=new Button(title);
c.add(b);
b.addActionListener(a);
public class ChartPanel extends JPanel {
private double[] values;
private String[] names;
private String title;
public ChartPanel(double[] v, String[] n, String t) {
names = n;
values = v;
title = t;
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (values == null || values.length == 0)
return;
double minValue = 0;
double maxValue = 0;
for (int i = 0; i < values.length; i++) {
if (minValue > values)
minValue = values[i];
if (maxValue < values[i])
maxValue = values[i];
//Dimension d = getSize();
//int clientWidth = d.width;
//int clientHeight = d.height;
//int barWidth = clientWidth / values.length;
//Dimension d = 100;
int clientWidth = 100;
int clientHeight = 150;
int barWidth = clientWidth / values.length;
Font titleFont = new Font("SansSerif", Font.BOLD, 12);
FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);
int titleWidth = titleFontMetrics.stringWidth(title);
int y = titleFontMetrics.getAscent();
int x = (clientWidth - titleWidth) / 2;
g.setFont(titleFont);
g.drawString(title, 10, 300);
int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();
if (maxValue == minValue)
return;
double scale = (clientHeight - top - bottom) / (maxValue - minValue);
y = clientHeight - labelFontMetrics.getDescent();
g.setFont(labelFont);
for (int i = 0; i < values.length; i++) {
int valueX = i * barWidth + 1;
int valueY = top;
int height = (int) (values[i] * scale);
if (values[i] >= 0)
valueY += (int) ((maxValue - values[i]) * scale);
else {
valueY += (int) (maxValue * scale);
height = -height;
g.setColor(Color.red);
g.fillRect(valueX, valueY, barWidth - 2, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY, barWidth - 2, height);
int labelWidth = labelFontMetrics.stringWidth(names[i]);
x = i * barWidth + (barWidth - labelWidth) / 2;
g.drawString(names[i], x, y);
//main is called when we start the application
public static void main(String[]args){
PlantFertilizer od = new PlantFertilizer();//make an observationsDemo frame
NWatcher watchitN = new NWatcher(od.lN);//make an observer
od.thedata.addObserver(watchitN);//register observer with the observable
PWatcher watchitP = new PWatcher(od.lP);//make an observer
od.thedata.addObserver(watchitP);//register observer with the observable
KWatcher watchitK = new KWatcher(od.lK);//make an observer
od.thedata.addObserver(watchitK);//register observer with the observable
od.setVisible(true);//show the frame on the screenWhy are you putting Labels and TextFields (heavyweight AWT components) into a lightweight JPanels?
What's the first rule of Swing? DO NOT MIX heavyweight AWT components and lightweight Swing components. Period. Never.
There's Swing equivalents for every single AWT component, and then some. There's no excuse for not using them.
However, if this chart library code is AWT based, then you should make a completely AWT based UI. Or find a different library based on Swing (like JFreeChart).
And finally:
add(p); //Put the panel in the Frame
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!is wrong....
add(p); // <-- The problem!!
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"));You don't call add on JFrame or JDialog to add things to it, unless you know what you're doing. And you clearly don't, else you wouldn't have done it. What you probably want to do is this:
this.getContentPane().add(p, BorderLayout.SOUTH);
this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"), BorderLayout.CENTER); -
JSF with Rich GUI Renderers - Swing
Has any one developed a renderer for a Thick Client/GUI such as swing. I know JSF is for web-based applications but with a suitable renderer it could be made to work with a non browser frontend, no ?
You are right.
Don't known about Swing implementation but other interesting ones are available. Have a look at XULFACES for example: http://xulfaces.sourceforge.net/getting-started.html
Anyway AJAX looks to be the "future" of rich JSF implementations. For example MyFaces Tomahawk is working to make a Dojo -http://dojotoolkit.org/- JSF implementation.
I don't known of other JSF implementations for devices like blackberry or Nokia S6x, but would be great too. -
How can I use the function keys in a GUI with swing?
I'm wondering how do you declare you want an action to happen when a user uses a function key or any key for that matter. How can you specify something frame wide or for that matter for a specific jtextbox?
you need to use an accelerator
setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)
Maybe you are looking for
-
How do I delete my OLD apple ID?
I have 2 apple ID's an old one that was @mac and i've recently made a new one. OK so I want to keep the purchases that i have made at the "@mac" ID but i want to change the primary email to the recent one i have made. Both of the ID's are not merge
-
Use SAP defined methods instead of Logical Database(LDB)
Hi All, I gonethrough some documents related to new HR ABAP programing without using logical database. we can replace the logical databased with SAP defined methods for all the infotypes. Appreciate if anyone let me know how do this. Thanks in adva
-
CALCULATION IN HEADER FIELD?
friends... i have designed a form z_pm_common..which i have copied from standard.pm_common. i have made some changes to the layout. now at the header i have a field : DURATION OF JOB :&AFVGD-ARBEI& &AFVGD-ARBEH& AFVGD-ARBEI IS WORK DURATION.I.E 6.3
-
I have over 200 photos on my iPhone photo stream but my iPad 2 only shows 53 of them.
-
Hi, I see two transactions F-22 and FB70 both for posting Customer Invoice, are there any difference in them?