Results 1 to 10 of 10
Like Tree1Likes
  • 1 Post By masijade

Thread: How Can I Add a Background Image to My Calculator Program??

  1. #1
    manibby93 is offline Member
    Join Date
    Sep 2013
    Posts
    77
    Rep Power
    0

    Default How Can I Add a Background Image to My Calculator Program??

    For the most part, I used a template and changed things and everything works. I just want to customize the background. I'm not really sure how to do it though. I've been searching Google for hours and came across a solution, but the Calculator doesn't show in front of the background. I'm not really sure what to do.

    These are the classes:

    Java Code:
    import java.awt.Dimension;
    
    import java.awt.Graphics;
    
    import java.awt.Image;
    
    import javax.swing.ImageIcon;
    
    import javax.swing.JFrame;
    
    import javax.swing.JPanel;
    
    public class TestCalculator extends SimpleArithmeticCalculator {
    
      public static void main(String[] args) {
    
        ImagePanel panel = new ImagePanel(new ImageIcon("01_Crane_AGweb.jpg").getImage());
    
        JFrame frame = new JFrame();
        
        frame.getContentPane().add(panel);
        
        frame.pack();
        
        frame.setVisible(true);
      
      }
    
    }
    
    class ImagePanel extends JPanel {
    
      private Image img;
    
      public ImagePanel(String img) {
    
        this(new ImageIcon(img).getImage());
      
      }
    
      public ImagePanel(Image img) {
      
        this.img = img;
        
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        
        setPreferredSize(size);
        
        setMinimumSize(size);
        
        setMaximumSize(size);
        
        setSize(size);
        
        setLayout(null);
      
      }
    
      public void paintComponent(Graphics g) {
      
        g.drawImage(img, 0, 0, null);
      
      }
    
    }
    Java Code:
    import javax.swing.*;
    
    import java.awt.*;
    
    import java.awt.event.*;
    
    public class SimpleArithmeticCalculator extends JFrame implements ActionListener {
    
     private static final int BTN_ONE = 0;
     
     private static final int BTN_TWO = 1;
     
     private static final int BTN_THREE = 2;
     
     private static final int BTN_PLUS = 3;
     
     private static final int BTN_MINUS = 4;
     
     private static final int BTN_FOUR = 5;
     
     private static final int BTN_FIVE = 6;
     
     private static final int BTN_SIX = 7;
     
     private static final int BTN_MULT = 8;
     
     private static final int BTN_DIV = 9;
     
     private static final int BTN_SEVEN = 10;
     
     private static final int BTN_EIGHT = 11;
     
     private static final int BTN_NINE = 12;
     
     private static final int BTN_POWER = 13;
     
     private static final int BTN_PERCENT = 14;
     
     private static final int BTN_ZERO = 15;
     
     private static final int BTN_DECIMAL = 16;
     
     private static final int BTN_BACKSPACE = 17;
     
     private static final int BTN_CALC = 18;
     
     private static final int BTN_CLEAR = 19;
     
     private static final int NUM_BUTTONS = 20;
    
     private static final int OP_MULT = 0;
    
     private static final int OP_DIV = 1;
     
     private static final int OP_PLUS = 2;
     
     private static final int OP_MINUS = 3;
     
     private static final int OP_POWER = 4;
     
     private static final int OP_PERCENT = 5;
     
     private static char[] buttonTexts = {'1' , '2' , '3' , '+' , '-' ,
                '4' , '5' , '6' , '*' , '/' ,
                '7' , '8' , '9' , '^' , '%' ,
                '0' , '.' , '<' , '=' , 'C'};
    
     private static final int[] buttonKeys = {
      KeyEvent.VK_NUMPAD1 , KeyEvent.VK_NUMPAD2 , KeyEvent.VK_NUMPAD3 , KeyEvent.VK_PLUS     , KeyEvent.VK_MINUS ,
      KeyEvent.VK_NUMPAD4 , KeyEvent.VK_NUMPAD5 , KeyEvent.VK_NUMPAD6 , KeyEvent.VK_MULTIPLY , KeyEvent.VK_DIVIDE ,
      KeyEvent.VK_NUMPAD7 , KeyEvent.VK_NUMPAD8 , KeyEvent.VK_NUMPAD9 , '%'      , '%' ,
      KeyEvent.VK_NUMPAD0 , KeyEvent.VK_STOP    , KeyEvent.VK_BACK_SPACE , KeyEvent.VK_ENTER , KeyEvent.VK_C
     };
     
     private Font font;
    
     private JButton[] buttons;
     
     private JTextField displayText;
    
     private JPanel calcPanel;
     
     private JPanel textPanel;
     
     private JPanel buttonPanel;
    
     private String buffer;
     
     private int op;
     
     private int opStored;
     
     private double lhs;
     
     private double rhs;
     
     private double rhsStored;
     
     private boolean left;
     
     private boolean clear;
     
     private char lastAction;
    
        public SimpleArithmeticCalculator() {
    
         super("Simple Arithmetic Calculator");
    
      buffer = new String("0.0");
    
      op = -1;
      
      opStored = -1;
      
      lhs = 0.0;
      
      rhs = 0.0;
      
      rhsStored = 0.0;
      
      left = true;
      
      clear = true;
      
      lastAction = '=';
    
         font = Font.decode("Courier PLAIN 24");
    
         try {
    
           UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         
         }
         
         catch (Exception e) {
           
         }
    
      calcPanel = new JPanel();
         
      textPanel = new JPanel();
      
      buttonPanel = new JPanel();
    
      buttonPanel.setForeground(Color.blue);
      
      textPanel.setForeground(Color.blue);
      
      calcPanel.setForeground(Color.blue);
    
      textPanel.setLayout(new GridLayout(0,1,0,0));
         
      buttonPanel.setLayout(new GridLayout(0 , 5 , 5 , 5));
    
      displayText = new JTextField("" , 20);
      
      displayText.setHorizontalAlignment(JTextField.RIGHT);
      
      displayText.setFont(font);
      
      displayText.setEditable(false);
      
      textPanel.add(displayText);
    
      buttons = new JButton[NUM_BUTTONS];
      
      for (int i = 0 ; i < NUM_BUTTONS ; ++i) {
      
        buttons[i] = new JButton("" + buttonTexts[i]);
        
        buttons[i].setMnemonic(buttonKeys[i]);
        
        buttons[i].setFont(font);
        
        buttons[i].setMinimumSize(new Dimension(50,50));
        
        buttons[i].setActionCommand("" + buttonTexts[i]);
        
        buttons[i].addActionListener(this);
        
        buttonPanel.add(buttons[i]);
        
      }
      
      buttons[BTN_POWER].setText("^");
      
      buttons[BTN_PERCENT].setText("%");
      
      buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
         
      textPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    
      calcPanel.setLayout(new BorderLayout());
      
      calcPanel.add(textPanel , BorderLayout.NORTH);
      
      calcPanel.add(buttonPanel , BorderLayout.CENTER);
      
      add(calcPanel);
      
      pack();
      
      setMinimumSize(getSize());
      
      setPreferredSize(getSize());
      
         for (int i = 0 ; i < NUM_BUTTONS ; ++i) {
      
           buttons[i].setMaximumSize(buttons[i].getSize());
         
         }
         
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        }
    
     public void SetColors(Color bg , Color textbg , Color textcolor) {
      
       calcPanel.setBackground(bg);
      
       buttonPanel.setBackground(bg);
      
       textPanel.setBackground(bg);
      
       displayText.setBackground(textbg);
      
       displayText.setForeground(textcolor);
      
       for (int i = 0 ; i < NUM_BUTTONS ; ++i) {
       
         buttons[i].setForeground(textcolor);
      
       }
     
     }
    
     public void Show() {
     
       setVisible(true);
     
     }
    
     public void actionPerformed(ActionEvent ev) {
    
      String action = ev.getActionCommand();
      
      char c = action.charAt(0);
      
      boolean calc = false;
    
     if (c == buttonTexts[BTN_CLEAR]) {
    
       buffer = "";
     
       left = true;
    
     }
     
     else if (c == buttonTexts[BTN_BACKSPACE]) {
     
       if (buffer.length() > 0) {
       
         buffer = buffer.substring(0 , buffer.length() - 1);
    
       }
       
       if (lastAction == buttonTexts[BTN_CALC]) {
       
         left = true;
    
       }
       
       clear = false;
    
     }
     
     else if ((c == buttonTexts[BTN_CALC]) || isOpCharacter(c)) {
     
       int opCurrent = op;
       
       if (c == buttonTexts[BTN_CALC]) {
    
        if (!left) {
       
          calc = true;
         
          if (isOpCharacter(lastAction)) {
          
            rhs = GetBufferValue();
          
            rhsStored = rhs;
          
            opCurrent = op;
          
            opStored = op;
         
          }
         
          else if (lastAction == buttonTexts[BTN_CALC]) {
    
          rhs = rhsStored;
          
          opCurrent = opStored;
         
          }
         
          else {
    
          rhs = GetBufferValue();
          
          rhsStored = rhs;
          
          opCurrent = op;
          
          opStored = op;
         
          }
        
        }
       
       }
       
       else if (isOpCharacter(c)) {
    
        opStored = op;
       
        if (c == buttonTexts[BTN_MULT])  {op = OP_MULT;}
        
        if (c == buttonTexts[BTN_DIV])   {op = OP_DIV;}
        
        if (c == buttonTexts[BTN_PLUS])  {op = OP_PLUS;}
        
        if (c == buttonTexts[BTN_MINUS]) {op = OP_MINUS;}
        
        if (c == buttonTexts[BTN_POWER])  {op = OP_POWER;}
        
        if (c == buttonTexts[BTN_PERCENT]) {op = OP_PERCENT;}
    
        if (lastAction == buttonTexts[BTN_CALC]) {
    
          lhs = GetBufferValue();
         
          clear = true;
        
        }
        
        else if (isOpCharacter(lastAction)) {
    
        }
        
        else {
    
        
          if (left) {
          
            lhs = GetBufferValue();
          
            left = false;
         
          }
         
          else {
          
            calc = true;
          
            rhs = GetBufferValue();
          
            opCurrent = opStored;
          
            opStored = op;
         
          }
         
          clear = true;
        
        }
       
       }
       
       if (calc) {
    
        double result = 0.0;
       
        if (opCurrent == OP_MULT)  {result = lhs * rhs;}
        
        if (opCurrent == OP_DIV)   {result = lhs / rhs;}
        
        if (opCurrent == OP_PLUS)  {result = lhs + rhs;}
        
        if (opCurrent == OP_MINUS) {result = lhs - rhs;}
        
        if (opCurrent == OP_POWER) {result = Math.pow(lhs,rhs);}  
        
        if (opCurrent == OP_PERCENT) {result = lhs / 100;}
    
        lhs = result;
    
        buffer = "" + result;
        
        clear = true;
       
       }
       
      }
      
     else {
     
       if (lastAction == buttonTexts[BTN_CALC]) {
    
        left = true;
       
       }
       
       if (clear) {
    
        buffer = "";
       
        clear = false;
       
       }
       
       if (c == buttonTexts[BTN_DECIMAL]) {
    
        if (buffer.indexOf('.') == -1) {
         
         if (buffer.length() == 0 || (buffer.length() == 1 && buffer.charAt(0) == '-')) {
       
           buffer += "0";
         
         }
         
         buffer += ".";
        
        }
       
       }
       
       else if (c == buttonTexts[BTN_ZERO]) {
        
        if (buffer.length() == 0 || (buffer.length() == 1 && buffer.charAt(0) == '-')) {
       
          buffer += "0.";
        
        }
        
        else if (buffer.length() > 0 && (isNonZeroNumber(buffer.charAt(0)) ||
                (buffer.charAt(0) == '-' && isNonZeroNumber(buffer.charAt(1))))) {
        
          buffer += "0";
        
        }
        
        else if (buffer.compareTo("0") == 0 || buffer.compareTo("-0") == 0) {
    
        }
        
        else {
        
          buffer += "0";
        
        }
       
       }
       
       else {
     
        if (!buffer.equals("0") && !buffer.equals("-0")) {
    
          buffer += c;
        
        }
       
       }
      
     }
      
      lastAction = c;
     
      displayText.setText(buffer);
     
     }
    
     public double GetBufferValue() {
     
       double d = 0.0;
      
       try {
       
         d = Double.parseDouble(buffer);
      
       }
      
       catch (NumberFormatException e) {
       
       System.out.println("NumberFormatException in GetBufferValue()");
      
       }
      
       return d;
    
     }
     
     public boolean isOpCharacter(char c) {
     
       return ((c == buttonTexts[BTN_MULT]) ||
       
               (c == buttonTexts[BTN_DIV]) ||
        
               (c == buttonTexts[BTN_PLUS]) ||
        
               (c == buttonTexts[BTN_MINUS]) ||
        
               (c == buttonTexts[BTN_POWER]) ||
        
               (c == buttonTexts[BTN_PERCENT]));
      
     }
     
     public boolean isNumericCharacter(char c) {
       
      return ((c == buttonTexts[BTN_ZERO]) ||
              
        (c == buttonTexts[BTN_ONE]) ||
              
        (c == buttonTexts[BTN_TWO]) ||
              
        (c == buttonTexts[BTN_THREE]) ||
              
        (c == buttonTexts[BTN_FOUR]) ||
              
        (c == buttonTexts[BTN_FIVE]) ||
              
        (c == buttonTexts[BTN_SIX]) ||
              
        (c == buttonTexts[BTN_SEVEN]) ||
              
        (c == buttonTexts[BTN_EIGHT]) ||
              
        (c == buttonTexts[BTN_NINE]) ||
              
        (c == buttonTexts[BTN_DECIMAL]));
      
     }
     
     public boolean isNonZeroNumber(char c) {
       
      return (c == buttonTexts[BTN_ONE] ||
              
        c == buttonTexts[BTN_TWO] ||
              
        c == buttonTexts[BTN_THREE] ||
              
        c == buttonTexts[BTN_FOUR] ||
              
        c == buttonTexts[BTN_FIVE] ||
              
        c == buttonTexts[BTN_SIX] ||
              
        c == buttonTexts[BTN_SEVEN] ||
              
        c == buttonTexts[BTN_EIGHT] ||
              
        c == buttonTexts[BTN_NINE]);
      
     }
     
        public static void main(String[] args) {
    
    }
    
    }
    Last edited by manibby93; 12-04-2013 at 06:04 AM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,318
    Rep Power
    5

    Default Re: How Can I Add a Background Image to My Calculator Program??

    Proper technique for painting is to extend JPanel and override paintComponent. Then add the instance of the JPanel class to an internal instance of JFrame.
    To do what you want, you need to do the exact same thing except instead of adding components to your JPanel, you add them to the glassPane. To do this,
    get the glassPane from the JFrame and cast it to a JComponent. Then add your buttons there. In your JPanel paintComponent method, draw your image. And don't forget to set the glassPane to visible. Before committing to this I suggest you try a smaller version to see if you understand it and it works like you want.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    manibby93 is offline Member
    Join Date
    Sep 2013
    Posts
    77
    Rep Power
    0

    Default Re: How Can I Add a Background Image to My Calculator Program??

    I do that in the SimpleArithmeticCalculator class, or can I do that in the Test class? Why do I need to add buttons anywhere? I don't want to change the background of the buttons. Just curious. It's late, so sorry if I'm not making sense.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,318
    Rep Power
    5

    Default Re: How Can I Add a Background Image to My Calculator Program??

    Quote Originally Posted by manibby93 View Post
    Why do I need to add buttons anywhere?
    Uh, did you even read the code? The program is definitely adding buttons. In any event I told you one way to put an image on the background behind the buttons. There may be other ways. I suggest if you don't understand what I said you read the tutorials on painting and using the various panes such as glass pane, root pane, etc.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How Can I Add a Background Image to My Calculator Program??

    I once created a class "ImagePanel" whose constructor took an Image, that extended JPanel and called setOpaque(true) in the constructor. Then I overrode paintComponent to first paint the Image, and then call super.paintComponent() (I believe that was all that was needed, but its been a few years and there may have been something more to it). Then you create your application GUI on this Panel, and call JFrame.setContentPane with this panel.
    jim829 likes this.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,318
    Rep Power
    5

    Default Re: How Can I Add a Background Image to My Calculator Program??

    Sounds like that may work too and may be even simpler to do (haven't tried it yet).

    Edit: Yep! it worked except it was setOpaque(false). What I didn't consider was calling super.paintComponent(g) after drawing the image. Duh!

    Regards,
    Jim
    Last edited by jim829; 12-05-2013 at 04:23 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    manibby93 is offline Member
    Join Date
    Sep 2013
    Posts
    77
    Rep Power
    0

    Default Re: How Can I Add a Background Image to My Calculator Program??

    Uh, I have buttons for the functions, up above, in the first post so I was wondering what you were talking about. No thanks for the attitude, but thanks for the help...

  8. #8
    manibby93 is offline Member
    Join Date
    Sep 2013
    Posts
    77
    Rep Power
    0

    Default Re: How Can I Add a Background Image to My Calculator Program??

    I don't know what the hell I'm doing. I added the crap, but am I supposed to change something in the "SimpleArithmeticCalculator" class!?????

    Java Code:
    import java.awt.Dimension;
    
    import java.awt.Graphics;
    
    import java.awt.Image;
    
    import javax.swing.ImageIcon;
    
    import javax.swing.JPanel;
    
    import java.awt.Color;
    
    public class TestCalculator extends JPanel {
    
      public static void main(String[] args) {
    
        ImagePanel panel = new ImagePanel(new ImageIcon("01_Crane_AGweb.jpg").getImage());
        
        SimpleArithmeticCalculator calc = new SimpleArithmeticCalculator();  
        
            calc.setBackground(Color.YELLOW);
            
            panel.setOpaque(true);
            
            panel.add(calc);
            
            panel.setVisible(true);
            
                calc.pack();
                
        calc.getContentPane().add (new SimpleArithmeticCalculator2());
      }
    
    }
    
    class ImagePanel extends JPanel {
    
      private Image img;
    
      public ImagePanel(String img) {
    
        this(new ImageIcon(img).getImage());
      
      }
    
      public ImagePanel(Image img) {
      
        this.img = img;
        
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        
        setPreferredSize(size);
        
        setMinimumSize(size);
        
        setMaximumSize(size);
        
        setSize(size);
        
        setLayout(null);
      
      }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, this);
        }
    
    }
    Last edited by manibby93; 12-07-2013 at 03:21 AM.

  9. #9
    manibby93 is offline Member
    Join Date
    Sep 2013
    Posts
    77
    Rep Power
    0

    Default Re: How Can I Add a Background Image to My Calculator Program??

    Can I ask my question on a new post or something if I'm pressed for time??

  10. #10
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How Can I Add a Background Image to My Calculator Program??

    Call drawImage BEFORE super.paintComponent, and, most importantly, don't forget about calling setContentPane.

Similar Threads

  1. use image for background
    By tony_stark in forum AWT / Swing
    Replies: 1
    Last Post: 05-31-2011, 08:20 PM
  2. [Help] W/ background image
    By gundum584 in forum New To Java
    Replies: 9
    Last Post: 01-10-2011, 05:48 AM
  3. Replies: 6
    Last Post: 07-21-2010, 06:15 AM
  4. Replies: 1
    Last Post: 07-07-2010, 09:25 AM
  5. Image as background
    By Java.child in forum AWT / Swing
    Replies: 2
    Last Post: 10-02-2008, 11:37 PM

Posting Permissions

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