Results 1 to 12 of 12
  1. #1
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default adding a jpanel in the middle of the script

    heres my calculator. it works fine, but for the love of god i can't figure out how to add another JPanel when you clikc the advanced button in the menu. Any way to do this?

    Java Code:
    import java.lang.Math;
    import javax.swing.*; 
    import java.awt.*; 
    import java.awt.event.*; 
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.ClipboardOwner;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.StringSelection;
    //import random shit
    
    public class Calculator
    {
    private JPanel CalculatorPanel = new JPanel(); // panel holds the button grid
    public static JPanel screenPanel;
    public static JFrame frame;
    public static JTextField screen;
    public static JMenu menu;
    public static JMenu edit;
    public static JMenuBar menuBar;
    public static JMenuItem exit = new JMenuItem("Exit");
    public static JMenuItem about = new JMenuItem("About");
    public static JMenuItem copy = new JMenuItem("Copy");
    public static JMenuItem paste = new JMenuItem("Paste");
    public static JMenuItem advanced = new JMenuItem("Advanced");
    public static JPanel advancedButtons;
    
    //all the menu items, panels, and the frame
    
    
    //numbers that allow calc to work
    int operation = 0;
    double secondnum1;
    double firstnum1;
    double oppAnswer = 0;
    String firstNum;
    String writeAnswer;
    String secondNum;
    double   secondParse;
    double   firstParse;
    boolean options = true;
    
      String[][] buttonStrings = // use these Strings to create a JButton grid
      {
          {"x", "sin", "cos", "tan"},
      	{"CE", "\u221A", "1/x", "inv"},
          {"7", "8", "9", "/"},
          {"4", "5", "6", "*"},
          {"1", "2", "3", "-"},
          {"0", ".", "=", "+"},
          
      };
    
      public Calculator()
      {
        int rowLength = buttonStrings.length;
        int colLength = buttonStrings[0].length;
        CalculatorPanel.setLayout(new GridLayout(rowLength, colLength));
        CalculatorPanel.setSize(200,200);
        ButtonListener buttonListener = new ButtonListener(); // create our ActionListener
        for (int row = 0; row < rowLength; row++)
        {
          for (int col = 0; col < colLength; col++)
          {
            // for each String in the array, create a button that holds the string
            String buttonString = buttonStrings[row][col];
            JButton button = new JButton(buttonString); // this button here
            button.addActionListener(buttonListener); // add the listener
            Calculator.about.addActionListener(new MenuActionListener());
            CalculatorPanel.add(button); // and add it to the panel
          }
        }
      }
     
     class MenuActionListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
        if ((e.getActionCommand() == "About") && (options == true)){
        	JOptionPane.showMessageDialog(null, "This is a java calculator created by Isaac Flaum as a good looking efficient multiplatform calculator.");
        	options = false;
        }
        if ((e.getActionCommand() == "Copy")){
        	String calcText = screen.getText();
    		StringSelection ss = new StringSelection(calcText);
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
        }
        if ((e.getActionCommand() == "Advanced")){
        	advancedButtons = new JPanel(new GridLayout(1,1)); //pain in the ass gridlayout manager
        	JButton log = new JButton("Log");
        	advancedButtons.add(log);
        	frame.add(advancedButtons,BorderLayout.EAST);
        	frame.getContentPane().add(new Calculator().getComponent2());
        	frame.setVisible(true);
        	//do shit
        }
      }
    }
     
     
      public JComponent getComponent()
      {
        return CalculatorPanel;
      }
    	public JComponent getComponent2()
    	{
    		return advancedButtons;
    	}
      
      // here's the button listener class that of course implements action listener
      private class ButtonListener implements ActionListener
      {
        public void actionPerformed(ActionEvent e)
        {
        	options = true;
        	String screentext = screen.getText();
            // we can easily extract the String held by the button pressed 
            String actionCommand = e.getActionCommand(); // here's the string
                if (actionCommand == "0"){
                    screen.setText(screentext + "0");
          	 
          }
                if (actionCommand == "1"){
                     screen.setText(screentext + "1");
          	 
          }
                if (actionCommand == "2"){
                     screen.setText(screentext + "2");
          	 
          }
                if (actionCommand == "3"){
                     screen.setText(screentext + "3");
          	 
          }
                if (actionCommand == "4"){
                     screen.setText(screentext + "4");
          	 
          } 
                 if (actionCommand == "5"){
                    screen.setText(screentext + "5");
          	 
          }
                if (actionCommand == "6"){
                     screen.setText(screentext + "6");
             
          }
                if (actionCommand == "7"){
                     screen.setText(screentext + "7");
          	 
          }
                if (actionCommand == "8"){
                     screen.setText(screentext + "8");
          	 
          }
                if (actionCommand == "9"){
                     screen.setText(screentext + "9");
          	 
          }
                if (actionCommand == "*"){
                     firstNum = screen.getText();
                     operation = 1;
                     screen.setText("");
          }
                if (actionCommand == "/"){
                    firstNum = screen.getText();
                    operation = 2;
                    screen.setText("");
          	 
          }
                if (actionCommand == "+"){
                     firstNum = screen.getText();
                     operation = 3;
                    screen.setText("");
          }
                if (actionCommand == "-"){
                    firstNum = screen.getText();
                    operation = 4;
                     screen.setText("");
          }
                if (actionCommand == "."){
                    screen.setText(screentext + ".");
          }
          		if (actionCommand == "CE"){
          			screen.setText("");
          			secondNum = "";
          			firstNum = "";
          			firstParse = 0;
          			secondParse = 0;
          			operation = 0;
          			writeAnswer = "";
          		}
          		if (actionCommand == "1/x"){
          			secondNum = screen.getText();
          			secondParse = Double.parseDouble(secondNum);
          			oppAnswer = 1 / secondParse;
          			writeAnswer = Double.toString(oppAnswer);
          			screen.setText(writeAnswer);
          		}
          		if (actionCommand == "inv"){
          			secondNum = screen.getText();
          			secondParse = Double.parseDouble(secondNum);
          			oppAnswer = -1 * secondParse;
          			writeAnswer = Double.toString(oppAnswer);
          			screen.setText(writeAnswer);
          		}
          		if (actionCommand == "\u221A"){
          		    secondNum = screen.getText();
          			secondParse = Double.parseDouble(secondNum);
          			if (secondParse < 0){
          				screen.setText("Error");
          			}
          			else{
          				oppAnswer = Math.sqrt(secondParse);
          			writeAnswer = Double.toString(oppAnswer);
          			screen.setText(writeAnswer);	
          			}
          			
          		}
                     if (actionCommand == "x"){
                            secondNum = screen.getText();
          			secondParse = Double.parseDouble(secondNum);
          			oppAnswer = secondParse * secondParse;
          			writeAnswer = Double.toString(oppAnswer);
          			screen.setText(writeAnswer);	
          		}
                    if (actionCommand == "sin"){
                            secondNum = screen.getText();
          			secondParse = Double.parseDouble(secondNum);
          			oppAnswer = Math.sin(secondParse);
          			writeAnswer = Double.toString(oppAnswer);
          			screen.setText(writeAnswer);	
          		}
                    if (actionCommand == "cos"){
                            secondNum = screen.getText();
          			secondParse = Double.parseDouble(secondNum);
          			oppAnswer = Math.cos(secondParse);
          			writeAnswer = Double.toString(oppAnswer);
          			screen.setText(writeAnswer);	
          		}
                    if (actionCommand == "tan"){
                            secondNum = screen.getText();
          			secondParse = Double.parseDouble(secondNum);
          			oppAnswer = Math.tan(secondParse);
          			writeAnswer = Double.toString(oppAnswer);
          			screen.setText(writeAnswer);	
          		}
                    if (actionCommand == "="){
    			secondNum  = screen.getText();
    			screen.setText("");
    			firstParse = Double.parseDouble(firstNum);
                            secondParse = Double.parseDouble(secondNum);
    			if(operation == 1){
                                oppAnswer = firstParse * secondParse;
                                writeAnswer = Double.toString(oppAnswer);
                                screen.setText(writeAnswer);
    			}	
    			if(operation == 2){
    				oppAnswer = firstParse / secondParse;
    				writeAnswer = Double.toString(oppAnswer);
    				screen.setText(writeAnswer);
    			}
    			if(operation == 4){
    				oppAnswer = firstParse - secondParse;
    				writeAnswer = Double.toString(oppAnswer);
    				screen.setText(writeAnswer);
    			}
    			if(operation == 3){
    				oppAnswer = firstParse + secondParse;
    				writeAnswer = Double.toString(oppAnswer);
    				screen.setText(writeAnswer);
    			}
                
          		} 
         
        }
      }
    
      // this calls our Swing code in a thread-safe manner  
      private static void createAndShowUI()
      {
        Calculator.frame = new JFrame("Isaac's Calculator"); 
        frame.setLayout(new BorderLayout());
        frame.getContentPane().add(new Calculator().getComponent());
        Calculator.screenPanel = new JPanel(); //panel to hold screen
        Calculator.screenPanel.setLayout(new GridLayout(2, 1));
        Calculator.screen = new JTextField(20);
        Calculator.menu = new JMenu("File");
        Calculator.menuBar = new JMenuBar();
        Calculator.edit = new JMenu("Edit");
        edit.add(copy);
       	edit.add(paste);
       	edit.add(advanced);
        menu.add(exit);
        menu.add(about);
        menuBar.add(menu);
        menuBar.add(edit);
        Calculator.screenPanel.add(Calculator.menuBar);
        Calculator.screenPanel.add(screen);
        frame.add(Calculator.screenPanel, BorderLayout.NORTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    	
      public static void main(String[] args)
      {
          try{
          UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
          }
          catch (UnsupportedLookAndFeelException e) {
           // handle exception
        }
        catch (ClassNotFoundException e) {
           // handle exception
        }
        catch (InstantiationException e) {
           // handle exception
        }
        catch (IllegalAccessException e) {
           // handle exception
        }
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I haven't looked at your code, but I'd make sure that the main jpanel is using an appropriate layout, one that will easily accept a JPanel on the bottom, say a BorderLayout or a BoxLayout, add the JPanel on demand, and then call pack() on the JFrame.

  3. #3
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    yea i tried that, didnt work so well...
    advancedButtons = new JPanel(new GridLayout(1,1)); //pain in the ass gridlayout manager
    JButton log = new JButton("Log");
    advancedButtons.add(log);
    frame.add(advancedButtons,BorderLayout.EAST);
    frame.getContentPane().add(new Calculator().getComponent2());
    frame.pack();

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    what you need to do is this: add both panels to the main panel but call setVisible(false) on the advanced panel. Then in your menu actions, call setVisible(true/false) depending on the menu chosen, and repeat a JFrame call to "pack()". I'd also enable and disable menu items depending on the advanced panel visibility state.

    If this doesn't work, then you need to post an SSCCE.

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    And never compare Strings (or any object references) with the == operator, use the .equals(...) method.

    db

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    never compare Strings (or any object references) with the == operator, use the .equals(...)
    It all depends what you are doing. Classes are not required to have an equals method that tests/examines/uses the contents of the object. It's a good idea but NOT required.
    If you want to see if two pointers (object references) point at/refer to the same object them == is the one to use.

  7. #7
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    so i did that, and now i have this, but it still doesn't work :-(

    Java Code:
    if ((e.getActionCommand() == "Advanced")){
        	advancedButtons.setVisible(true);
        	frame.pack();

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    it still doesn't work
    Is there an error message? Or what?

    Did you read the previous posts about equals() and ==?
    If not, you need to.
    You need to use equals(). It will test if the contents of the object returned by getActionCommand is the same as the contents of the String object containing "Advanced".
    equals tests for the same content in TWO objects. == tests if the two object references(pointers) point to the SAME object.

  9. #9
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Is there an error message? Or what?

    Did you read the previous posts about equals() and ==?
    If not, you need to.
    You need to use equals(). It will test if the contents of the object returned by getActionCommand is the same as the contents of the String object containing "Advanced".
    equals tests for the same content in TWO objects. == tests if the two object references(pointers) point to the SAME object.
    i changed it to .equals, no luck, no errors either, just when i click advanced the panel doesnt show

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Here's a simple example of what I'm suggesting:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class AdvancedFrame
    {
      private static final Dimension CENTER_SIZE = new Dimension(250, 200);
      private static final Dimension EAST_SIZE = new Dimension(150, 200);
      private JFrame frame = new JFrame();
      private JPanel mainPanel = new JPanel();
      private Action advancedAction = new AbstractAction("Advanced")
      {
        public void actionPerformed(ActionEvent e)
        {
          advancedAxnPerformed();
        }
      };
      private Action simpleAction = new AbstractAction("Simple")
      {
        public void actionPerformed(ActionEvent e)
        {
          simpleAxnPerformed();
        }
      };
    
      private JMenuItem advancedMenuItem = new JMenuItem(advancedAction);
      private JMenuItem simpleMenuItem = new JMenuItem(simpleAction);
      private JPanel advancedPanel = new JPanel();
      private JPanel mainCalcPanel = new JPanel();
    
      public AdvancedFrame()
      {
        setupMainPanel(mainCalcPanel, advancedPanel);
        
        frame = new JFrame("Advanced Frame");
        frame.getContentPane().add(mainPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        advancedPanel.setVisible(false);
    
        JMenu menu = new JMenu("Calculator Type");
        menu.add(simpleMenuItem);
        menu.add(advancedMenuItem);
        simpleMenuItem.setEnabled(false);
        JMenuBar menubar = new JMenuBar();
        menubar.add(menu);
        frame.setJMenuBar(menubar);
        frame.pack();
        frame.setLocationRelativeTo(null);
      }
    
      private void setupMainPanel(JPanel centerPanel, JPanel eastPanel)
      {
        mainCalcPanel.setBorder(BorderFactory.createTitledBorder("Main Calculator Panel"));
        advancedPanel.setBorder(BorderFactory.createTitledBorder("Advanced Panel"));
        
        mainCalcPanel.setPreferredSize(CENTER_SIZE);
        advancedPanel.setPreferredSize(EAST_SIZE);
        
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        mainPanel.add(eastPanel, BorderLayout.EAST);
        eastPanel.setVisible(false);
      }
      
      private void advancedAxnPerformed()
      {
        advancedPanel.setVisible(true);
        advancedMenuItem.setEnabled(false);
        simpleMenuItem.setEnabled(true);
        frame.pack();
      }
      
      private void simpleAxnPerformed()
      {
        advancedPanel.setVisible(false);
        advancedMenuItem.setEnabled(true);
        simpleMenuItem.setEnabled(false);
        frame.pack();    
      }
      
      public JFrame getFrame()
      {
        return frame;
      }
    
      private static void createAndShowUI()
      {
        AdvancedFrame aFrame = new AdvancedFrame();
        aFrame.getFrame().setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    Have you tried debugging your code to see if it is executing the listener? Add some println()s to it to show if it is being executed and with what values.

    Your long list of if() tests in the listener assumes that one of them will match. What if none of them match? Your code will NOT show that.

    A suggestion: use if{}else if{} ... else{System.out.println("No match");}
    with the ending else to catch the case where none of the above if tests matched. Sort of like the default in a switch statement.

  12. #12
    2o2
    2o2 is offline Member
    Join Date
    Sep 2008
    Posts
    31
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Have you tried debugging your code to see if it is executing the listener? Add some println()s to it to show if it is being executed and with what values.

    Your long list of if() tests in the listener assumes that one of them will match. What if none of them match? Your code will NOT show that.

    A suggestion: use if{}else if{} ... else{System.out.println("No match");}
    with the ending else to catch the case where none of the above if tests matched. Sort of like the default in a switch statement.
    yea wow, i forgot to add an action listener to the advanced button :P wow im an idiot! thanks!

Similar Threads

  1. Running a script within IE
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 07-25-2008, 02:33 PM
  2. Replies: 1
    Last Post: 07-13-2008, 03:16 PM
  3. JSP redirection script
    By ravian in forum New To Java
    Replies: 1
    Last Post: 01-07-2008, 10:33 AM
  4. Middle Click Closes Tab Eclipse Plugin 1.0.0
    By JavaBean in forum Java Software
    Replies: 0
    Last Post: 10-20-2007, 05:59 PM
  5. Return in the Middle of synchronized Block
    By ariak in forum Advanced Java
    Replies: 1
    Last Post: 07-26-2007, 10:24 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •