JButton not visible after use of Jpanel removeAll ..
Hi!
I'm having a calculator class that inherits JFrame. I need to add more buttons after setting an option from the (view) menu bar .. (from normal to scientific calculator). I needed to use the JPanel removeAll method and then add the normal buttons plus extra buttons. But the problem is, that the Buttons are only visible when I touch them with the mouse.
Does anybody know why? Thanks for your help!
See code below (still in construction phase):
/*
Name: Hemanth. B
Original code from Website: java-swing-tutorial.html
Topic : A basic Java Swing Calculator
Conventions Used in Source code
1. All JLabel components start with jlb*
2. All JPanel components start with jpl*
3. All JMenu components start with jmenu*
4. All JMenuItem components start with jmenuItem*
5. All JDialog components start with jdlg*
6. All JButton components start with jbn*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame
implements ActionListener {
///////////////////////////////////////////////////////////
// Constants
final int NORMAL = 0;
final int SCIENTIFIC = 8;
final int MAX_INPUT_LENGTH = 20;
final int INPUT_MODE = 0;
final int RESULT_MODE = 1;
final int ERROR_MODE = 2;
///////////////////////////////////////////////////////////
// Variables
int displayMode;
int calcType = SCIENTIFIC;
boolean clearOnNextDigit, percent;
double lastNumber;
String lastOperator, title;
private JMenu jmenuFile, jmenuView, jmenuHelp;
private JMenuItem jmenuitemExit, jmenuitemAbout;
private JRadioButtonMenuItem jmenuItemNormal = new JRadioButtonMenuItem("Normal");
private JRadioButtonMenuItem jmenuItemScientific = new JRadioButtonMenuItem("Scientific");
privateButtonGroup viewMenuButtonGroup = new ButtonGroup();
private JLabel jlbOutput;
private JButton jbnButtons[];
private JPanel jplButtons, jplMaster, jplBackSpace, jplControl;
/*
* Font(String name, int style, int size)
Creates a new Font from the specified name, style and point size.
*/
Font f12 = new Font("Verdana", 0, 12);
Font f121 = new Font("Verdana", 1, 12);
// Constructor
public Calculator(String title) {
/* Set Up the JMenuBar.
* Have Provided All JMenu's with Mnemonics
* Have Provided some JMenuItem components with Keyboard Accelerators
*/
//super(title);
this.title = title;
//displayCalculator(title);
}//End of Contructor Calculator
private void displayCalculator (String title) {
//add WindowListener for closing frame and ending program
addWindowListener (
new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
}
);
//setResizable(false);
///////////////////////////////////////////////////////////
//Set frame layout manager
setBackground(Color.gray);
validate();
createMenuBar();
createMasterPanel();
createDisplayPanel();
clearAll();
this.getContentPane().validate();
requestFocus();
pack();
//getContentPane().
setVisible(true);
}
private void createMenuBar() {
jmenuFile = new JMenu("File");
jmenuFile.setFont(f121);
jmenuFile.setMnemonic(KeyEvent.VK_F);
jmenuitemExit = new JMenuItem("Exit");
jmenuitemExit.setFont(f12);
jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X,
ActionEvent.CTRL_MASK));
jmenuFile.add(jmenuitemExit);
jmenuView = new JMenu("View");
jmenuFile.setFont(f121);
jmenuFile.setMnemonic(KeyEvent.VK_W);
jmenuItemNormal.setMnemonic(KeyEvent.VK_N);
viewMenuButtonGroup.add(jmenuItemNormal);
jmenuView.add(jmenuItemNormal);
jmenuItemScientific.setMnemonic(KeyEvent.VK_S);
viewMenuButtonGroup.add(jmenuItemScientific);
jmenuView.add(jmenuItemScientific);
if (jmenuItemNormal.isSelected() == false &&
jmenuItemScientific.isSelected() == false)
jmenuItemScientific.setSelected(true);
jmenuHelp = new JMenu("Help");
jmenuHelp.setFont(f121);
jmenuHelp.setMnemonic(KeyEvent.VK_H);
jmenuitemAbout = new JMenuItem("About Calculator");
jmenuitemAbout.setFont(f12);
jmenuHelp.add(jmenuitemAbout);
JMenuBar menubar = new JMenuBar();
menubar.add(jmenuFile);
menubar.add(jmenuView);
menubar.add(jmenuHelp);
setJMenuBar(menubar);
jmenuItemNormal.addActionListener(this);
jmenuItemScientific.addActionListener(this);
jmenuitemAbout.addActionListener(this);
jmenuitemExit.addActionListener(this);
}
private void createDisplayPanel() {
if (jlbOutput != null) {
jlbOutput.removeAll();
}
jlbOutput = new JLabel("0",JLabel.RIGHT);
jlbOutput.setBackground(Color.WHITE);
jlbOutput.setOpaque(true);
// Add components to frame
getContentPane().add(jlbOutput, BorderLayout.NORTH);
jlbOutput.setVisible(true);
}
private void createMasterPanel() {
if (jplMaster != null) {
jplMaster.removeAll();
}
jplMaster = new JPanel(new BorderLayout());
createCalcButtons();
jplMaster.add(jplBackSpace, BorderLayout.WEST);
jplMaster.add(jplControl, BorderLayout.EAST);
jplMaster.add(jplButtons, BorderLayout.SOUTH);
((JPanel)getContentPane()).revalidate();
// Add components to frame
getContentPane().add(jplMaster, BorderLayout.SOUTH);
jplMaster.setVisible(true);
}
private void createCalcButtons() {
int rows = 4;
int cols = 5 + calcType/rows;
jbnButtons = new JButton[31];
// Create numeric Jbuttons
for (int i=0; i<=9; i++) {
// set each Jbutton label to the value of index
jbnButtons = new JButton(String.valueOf(i));
}
// Create operator Jbuttons
jbnButtons[10] = new JButton("+/-");
jbnButtons[11] = new JButton(".");
jbnButtons[12] = new JButton("=");
jbnButtons[13] = new JButton("/");
jbnButtons[14] = new JButton("*");
jbnButtons[15] = new JButton("-");
jbnButtons[16] = new JButton("+");
jbnButtons[17] = new JButton("sqrt");
jbnButtons[18] = new JButton("1/x");
jbnButtons[19] = new JButton("%");
jplBackSpace = new JPanel();
jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));
jbnButtons[20] = new JButton("Backspace");
jplBackSpace.add(jbnButtons[20]);
jplControl = new JPanel();
jplControl.setLayout(new GridLayout(1, 2, 2 ,2));
jbnButtons[21] = new JButton(" CE ");
jbnButtons[22] = new JButton("C");
jplControl.add(jbnButtons[21]);
jplControl.add(jbnButtons[22]);
//if (calcType == SCIENTIFIC) {
jbnButtons[23] = new JButton("s");
jbnButtons[24] = new JButton("t");
jbnButtons[25] = new JButton("u");
jbnButtons[26] = new JButton("v");
jbnButtons[27] = new JButton("w");
jbnButtons[28] = new JButton("x");
jbnButtons[29] = new JButton("y");
jbnButtons[30] = new JButton("z");
//}
// Setting all Numbered JButton's to Blue. The rest to Red
for (int i=0; i<jbnButtons.length; i++){
//activate ActionListener
System.out.println("add action listener: " + i);
jbnButtons.addActionListener(this);
//set button text font/colour
jbnButtons.setFont(f12);
jbnButtons.invalidate();
if (i><10)
jbnButtons.setForeground(Color.blue);
else
jbnButtons.setForeground(Color.red);
}
// container for Jbuttons
jplButtons = new JPanel(new GridLayout(rows, cols, 2, 2));
System.out.println("Cols: " + cols);
//Add buttons to keypad panel starting at top left
// First row
// extra left buttons for scientific
if (calcType == SCIENTIFIC) {
System.out.println("Adding Scientific buttons");
setSize(400, 217);
setLocation(200, 250);
jplButtons.add(jbnButtons[23]);
jplButtons.add(jbnButtons[27]);
} else {
setSize(241, 217);
setLocation(200, 250);
}
for(int i=7; i<=9; i++){
jplButtons.add(jbnButtons);
}
// add button / and sqrt
jplButtons.add(jbnButtons[13]);
jplButtons.add(jbnButtons[17]);
// Second row
// extra left buttons for scientific
if (calcType == SCIENTIFIC) {
System.out.println("Adding Scientific buttons");
jplButtons.add(jbnButtons[24]);
jplButtons.add(jbnButtons[28]);
}
for(int i=4; i<=6; i++){
jplButtons.add(jbnButtons);
}
// add button * and x^2
jplButtons.add(jbnButtons[14]);
jplButtons.add(jbnButtons[18]);
// Third row
// extra left buttons for scientific
if (calcType == SCIENTIFIC) {
System.out.println("Adding Scientific buttons");
jplButtons.add(jbnButtons[25]);
jplButtons.add(jbnButtons[29]);
}
for( int i=1; i<=3; i++) {
jplButtons.add(jbnButtons);
}
//adds button - and %
jplButtons.add(jbnButtons[15]);
jplButtons.add(jbnButtons[19]);
//Fourth Row
// extra left buttons for scientific
if (calcType == SCIENTIFIC) {
System.out.println("Adding Scientific buttons");
jplButtons.add(jbnButtons[26]);
jplButtons.add(jbnButtons[30]);
}
// add 0, +/-, ., +, and =
jplButtons.add(jbnButtons[0]);
jplButtons.add(jbnButtons[10]);
jplButtons.add(jbnButtons[11]);
jplButtons.add(jbnButtons[16]);
jplButtons.add(jbnButtons[12]);
jplButtons.revalidate();
}
// Perform action
public void actionPerformed(ActionEvent e){
double result = 0;
if(e.getSource() == jmenuitemAbout) {
//JDialog dlgAbout = new CustomABOUTDialog(this,
//"About Java Swing Calculator", true);
//dlgAbout.setVisible(true);
} else if(e.getSource() == jmenuitemExit) {
System.exit(0);
}
if (e.getSource() == jmenuItemNormal) {
calcType = NORMAL;
displayCalculator(title);
}
if (e.getSource() == jmenuItemScientific) {
calcType = SCIENTIFIC;
displayCalculator(title);
}
System.out.println("Calculator is set to "
+ (calcType == NORMAL?"Normal":"Scientific") + " :" + jbnButtons.length);
// Search for the button pressed until end of array or key found
for (int i=0; i<jbnButtons.length; i++){
if(e.getSource() == jbnButtons) {
System.out.println(i);
switch(i) {
case 0:
addDigitToDisplay(i);
break;
case 1:
System.out.println("1");
addDigitToDisplay(i);
break;
case 2:
addDigitToDisplay(i);
break;
case 3:
addDigitToDisplay(i);
break;
case 4:
addDigitToDisplay(i);
break;
case 5:
addDigitToDisplay(i);
break;
case 6:
addDigitToDisplay(i);
break;
case 7:
addDigitToDisplay(i);
break;
case 8:
addDigitToDisplay(i);
break;
case 9:
addDigitToDisplay(i);
break;
case 10:// +/-
processSignChange();
break;
case 11:// decimal point
addDecimalPoint();
break;
case 12:// =
processEquals();
break;
case 13:// divide
processOperator("/");
break;
case 14:// *
processOperator("*");
break;
case 15:// -
processOperator("-");
break;
case 16:// +
processOperator("+");
break;
case 17:// sqrt
if (displayMode != ERROR_MODE) {
try {
if (getDisplayString().indexOf("-") == 0)
displayError("Invalid input for function!");
result = Math.sqrt(getNumberInDisplay());
displayResult(result);
}
catch(Exception ex) {
displayError("Invalid input for function!");
displayMode = ERROR_MODE;
}
}
break;
case 18:// 1/x
if (displayMode != ERROR_MODE){
try {
if (getNumberInDisplay() == 0)
displayError("Cannot divide by zero!");
result = 1 / getNumberInDisplay();
displayResult(result);
}
catch(Exception ex) {
displayError("Cannot divide by zero!");
displayMode = ERROR_MODE;
}
}
break;
case 19:// %
if (displayMode != ERROR_MODE){
try {
result = getNumberInDisplay() / 100;
displayResult(result);
}
catch(Exception ex) {
displayError("Invalid input for function!");
displayMode = ERROR_MODE;
}
}
break;
case 20:// backspace
if (displayMode != ERROR_MODE) {
setDisplayString(getDisplayString().substring(0,
getDisplayString().length() - 1));
if (getDisplayString().length() >< 1)
setDisplayString("0");
}
break;
case 21:// CE
clearExisting();
break;
case 22:// C
clearAll();
break;
}
}
}
}
void setDisplayString(String s) {
jlbOutput.setText(s);
}
String getDisplayString () {
return jlbOutput.getText();
}
void addDigitToDisplay(int digit) {
if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
if (inputString.indexOf("0") == 0) {
inputString = inputString.substring(1);
}
if ((!inputString.equals("0") || digit > 0)
&& inputString.length() < MAX_INPUT_LENGTH) {
setDisplayString(inputString + digit);
}
displayMode = INPUT_MODE;
clearOnNextDigit = false;
}
void addDecimalPoint() {
displayMode = INPUT_MODE;
if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
// If the input string already contains a decimal point, don't
// do anything to it.
if (inputString.indexOf(".") < 0)
setDisplayString(new String(inputString + "."));
}
void processSignChange() {
if (displayMode == INPUT_MODE) {
String input = getDisplayString();
if (input.length() > 0 && !input.equals("0")){
if (input.indexOf("-") == 0)
setDisplayString(input.substring(1));
else
setDisplayString("-" + input);
}
} else if (displayMode == RESULT_MODE) {
double numberInDisplay = getNumberInDisplay();
if (numberInDisplay != 0)
displayResult(-numberInDisplay);
}
}
void clearAll() {
setDisplayString("0");
lastOperator = "0";
lastNumber = 0;
displayMode = INPUT_MODE;
clearOnNextDigit = true;
}
void clearExisting() {
setDisplayString("0");
clearOnNextDigit = true;
displayMode = INPUT_MODE;
}
double getNumberInDisplay(){
String input = jlbOutput.getText();
return Double.parseDouble(input);
}
void processOperator(String op) {
if (displayMode != ERROR_MODE) {
double numberInDisplay = getNumberInDisplay();
if (!lastOperator.equals("0")) {
try {
double result = processLastOperator();
displayResult(result);
lastNumber = result;
}
catch (DivideByZeroException e){
displayError("Cannot divide by zero!");
}
} else {
lastNumber = numberInDisplay;
}
clearOnNextDigit = true;
lastOperator = op;
}
}
void processEquals() {
double result = 0;
if (displayMode != ERROR_MODE){
try {
result = processLastOperator();
displayResult(result);
}
catch (DivideByZeroException e) {
displayError("Cannot divide by zero!");
}
lastOperator = "0";
}
}
double processLastOperator() throws DivideByZeroException {
double result = 0;
double numberInDisplay = getNumberInDisplay();
if (lastOperator.equals("/")) {
if (numberInDisplay == 0)
throw (new DivideByZeroException());
result = lastNumber / numberInDisplay;
}
if (lastOperator.equals("*"))
result = lastNumber * numberInDisplay;
if (lastOperator.equals("-"))
result = lastNumber - numberInDisplay;
if (lastOperator.equals("+"))
result = lastNumber + numberInDisplay;
return result;
}
void displayResult(double result){
setDisplayString(Double.toString(result));
lastNumber = result;
displayMode = RESULT_MODE;
clearOnNextDigit = true;
}
void displayError(String errorMessage){
setDisplayString(errorMessage);
lastNumber = 0;
displayMode = ERROR_MODE;
clearOnNextDigit = true;
}
public static void main(String args[]) {
Calculator calci = new Calculator("My Calculator");
calci.displayCalculator("My Calculator");
System.out.println("Exitting...");
}
}//End of Swing Calculator Class.
class DivideByZeroException extends Exception{
public DivideByZeroException() {
super();
}
public DivideByZeroException(String s) {
super(s);
}
}
class CustomABOUTDialog extends JDialog implements ActionListener {
JButton jbnOk;
CustomABOUTDialog(JFrame parent, String title, boolean modal){
super(parent, title, modal);
setBackground(Color.black);
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
StringBuffer text = new StringBuffer();
text.append("Calculator Information\n\n");
text.append("Developer:Hemanth\n");
text.append("Version:1.0");
JTextArea jtAreaAbout = new JTextArea(5, 21);
jtAreaAbout.setText(text.toString());
jtAreaAbout.setFont(new Font("Times New Roman", 1, 13));
jtAreaAbout.setEditable(false);
p1.add(jtAreaAbout);
p1.setBackground(Color.red);
getContentPane().add(p1, BorderLayout.CENTER);
JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
jbnOk = new JButton(" OK ");
jbnOk.addActionListener(this);
p2.add(jbnOk);
getContentPane().add(p2, BorderLayout.SOUTH);
setLocation(408, 270);
setResizable(false);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Window aboutDialog = e.getWindow();
aboutDialog.dispose();
}
}
);
pack();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == jbnOk) {
this.dispose();
}
}
}
Message was edited by:
dungorg

