1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test 
    {

    public static void panel1()
    {
            JFrame frame=new JFrame("@b's metric calculator");
            //Color b=new Color(0,150,255);
            //JPanel Cr=new JPanel();
            final JTextField textField = new JTextField(10);
            //textField.setBackgound(0,255,220);
            JButton button=new JButton("Enter Centimeter");
            final JTextField textFiel= new JTextField("Your result will be here",20);
            String[] list = {"cm-inch","cm-meter","cm-feet","inch-feet"};
            /*The <string> added below is to avoid "unchecked or unsafe operations” warning in Java ,
            if passing integer set it <Integer>*/
            final JComboBox<String> list1 = new JComboBox<String>(list);
            list1.setSelectedIndex(0);
            JButton submit=new JButton("Submit");
            submit.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e) 
                {   
                //textFiel.setText(textField.getText());

                //following command converts textfild value to integer
                int centi=Integer.parseInt(textField.getText());
                //----------------------------------------------------
                //double area = 3.14*radius*radius;
                int cb = list1.getSelectedIndex();//to get the index of selected item(eg. 0,1,2..)
                if(cb==0)
                {   
                    Double inch = centi/2.54;
                    //following command converts double to string
                    String out = Double.toString(inch);
                    //-----------------------------------------
                    textFiel.setText(out);
                }
                else if(cb==1)
                {   
                    Double meter = centi/100.00;
                    String out = Double.toString(meter);
                    textFiel.setText(out);
                }
                else if(cb==2)
                {   
                    Double feet = centi/30.48;
                    String out = Double.toString(feet);
                    textFiel.setText(out);
                }
                else 
                {   
                    Double feet = centi/12.00;
                    String out = Double.toString(feet);
                    textFiel.setText(out);
                }
                }
            });
            //c.setBackground(b);
            frame.add(new Cr());
            Cr.add(button);
            Cr.add(textField);
            Cr.add(list1);
            Cr.add(submit);
            Cr.add(textFiel);
            button.setPreferredSize(new Dimension(150,30));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400,300);
            frame.setVisible(true);
            JOptionPane.showMessageDialog(frame,"Welcome \n enter centimeter in blank box\n Select your choice\n then press submit");
    }   
        class Cr extends JPanel{

            ImageIcon image = new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");
            public void paint( Graphics g ) {
            Dimension d = getSize();
            for( int x = 0; x < d.width; x += image.getIconWidth() )
            for( int y = 0; y < d.height; y += image.getIconHeight() )
            g.drawImage( image.getImage(), x, y, null, null );
            super.paint(g);
            }           
            } 


        public static void main(String[] args)
        {

            javax.swing.SwingUtilities.invokeLater(new Runnable()
             {
                        public void run() {
                                 panel1();
                                  }
            });
        }


}

problem code is this section,it started when i tried to add image to panel.

class Cr extends JPanel{

        ImageIcon image = new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");
        public void paint( Graphics g ) {
        Dimension d = getSize();
        for( int x = 0; x < d.width; x += image.getIconWidth() )
        for( int y = 0; y < d.height; y += image.getIconHeight() )
        g.drawImage( image.getImage(), x, y, null, null );
        super.paint(g);
        }           
        } 

can you pls help me guys ,pls say which all i have to change. it says error non-static variable can't be referenced from a static context. thks in advance. thks to every one and 'vedant1811' for the layout idea ,'mKorbel' for overriding paint and 'nIcE cOw' for putting my code on center ,i used it now i made my program finally working. thks

My final code

    import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JPanel{

    public Test() {

    setOpaque(false);
    setLayout(new FlowLayout());
    }
    public static void main(String[] args) {

        JFrame frame = new JFrame("@b's metric calculator"); 
        final JTextField textField = new JTextField(10);
        JButton button = new JButton("Enter Centimeter");
        final JTextField textFiel = new JTextField("Your result will be here", 20);
        String[] list = {"cm-inch", "cm-meter", "cm-feet", "inch-feet"};
        /*The <string> added below is to avoid "unchecked or unsafe operations” warning in Java ,
        if passing integer set it <Integer>*/
        final JComboBox<String> list1 = new JComboBox<String>(list);
        list1.setSelectedIndex(0);
        JButton submit = new JButton("Submit");
        Test Cr = new Test();
        submit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                //textFiel.setText(textField.getText());

                //following command converts textfild value to integer
                int centi = Integer.parseInt(textField.getText());
                //----------------------------------------------------
                //double area = 3.14*radius*radius;
                int cb = list1.getSelectedIndex();//to get the index of selected item(eg. 0,1,2..)
                if (cb == 0) {
                    Double inch = centi / 2.54;
                    //following command converts double to string
                    String out = Double.toString(inch);
                    //-----------------------------------------
                    textFiel.setText(out);
                } else if (cb == 1) {
                    Double meter = centi / 100.00;
                    String out = Double.toString(meter);
                    textFiel.setText(out);
                } else if (cb == 2) {
                    Double feet = centi / 30.48;
                    String out = Double.toString(feet);
                    textFiel.setText(out);
                } else {
                    Double feet = centi / 12.00;
                    String out = Double.toString(feet);
                    textFiel.setText(out);
                }
            }
        }); 
        frame.add(Cr);      
        Cr.add(button);
        Cr.add(textField);
        Cr.add(list1);
        Cr.add(submit);
        Cr.add(textFiel);
        button.setPreferredSize(new Dimension(150, 30));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
        JOptionPane.showMessageDialog(frame, "Welcome \n enter centimeter in blank box\n Select your choice\n then press submit");
    }   
    public void paint(Graphics g)
    {
        // Loads the background image and stores in img object.
        Image img = Toolkit.getDefaultToolkit().getImage("C:\\Users\\Administrator\\Documents\\JAVA\\My java programs\\hd_wall_11493.jpg");
        // Draws the img to the BackgroundPanel.
        g.drawImage(img,0,0,getSize().width,getSize().height,this);
        super.paint(g);
    }
    }      
Cœur
  • 37,241
  • 25
  • 195
  • 267
Tom C
  • 11
  • 2
  • When you are extending a `JPanel` never override it's `paint(...) method, inside always choose `paintComponent(...)`, that's is the way to go, as far as the [Java Docs](http://docs.oracle.com/javase/tutorial/uiswing/painting/problems.html) are concerned – nIcE cOw Jun 25 '12 at 11:06
  • Please do have a look at this example, for [How to put images in your Project](http://stackoverflow.com/questions/9864267/load-icon-image-exception/9866659#9866659). Moreover, in order to bring the frame to the center of the screen, simply write `frameObject.setLocationRelativeTo(null)`, before `frameObject.setVisible(true);`, that's it :-) – nIcE cOw Jun 25 '12 at 16:16
  • thks for the code for center screen. – Tom C Jun 25 '12 at 18:39
  • You're MOST WELCOME and KEEP SMILING :-) – nIcE cOw Jun 26 '12 at 02:15

2 Answers2

2

don't want to comment something

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test {

    public Test() {
        JFrame frame = new JFrame("@b's metric calculator");
        //Color b=new Color(0,150,255);
        //JPanel Cr=new JPanel();
        final JTextField textField = new JTextField(10);
        //textField.setBackgound(0,255,220);
        JButton button = new JButton("Enter Centimeter");
        final JTextField textFiel = new JTextField("Your result will be here", 20);
        String[] list = {"cm-inch", "cm-meter", "cm-feet", "inch-feet"};
        /*The <string> added below is to avoid "unchecked or unsafe operations” warning in Java ,
        if passing integer set it <Integer>*/
        final JComboBox<String> list1 = new JComboBox<String>(list);
        list1.setSelectedIndex(0);
        JButton submit = new JButton("Submit");
        submit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                //textFiel.setText(textField.getText());

                //following command converts textfild value to integer
                int centi = Integer.parseInt(textField.getText());
                //----------------------------------------------------
                //double area = 3.14*radius*radius;
                int cb = list1.getSelectedIndex();//to get the index of selected item(eg. 0,1,2..)
                if (cb == 0) {
                    Double inch = centi / 2.54;
                    //following command converts double to string
                    String out = Double.toString(inch);
                    //-----------------------------------------
                    textFiel.setText(out);
                } else if (cb == 1) {
                    Double meter = centi / 100.00;
                    String out = Double.toString(meter);
                    textFiel.setText(out);
                } else if (cb == 2) {
                    Double feet = centi / 30.48;
                    String out = Double.toString(feet);
                    textFiel.setText(out);
                } else {
                    Double feet = centi / 12.00;
                    String out = Double.toString(feet);
                    textFiel.setText(out);
                }
            }
        });
        //c.setBackground(b);
        Cr cr = new Cr();
        cr.add(button);
        cr.add(textField);
        cr.add(list1);
        cr.add(submit);
        cr.add(textFiel);
        button.setPreferredSize(new Dimension(150, 30));
        frame.add(cr);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
        JOptionPane.showMessageDialog(frame, "Welcome \n enter centimeter in blank box\n Select your choice\n then press submit");
    }

    class Cr extends JPanel {

        private static final long serialVersionUID = 1L;
        private ImageIcon image = new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");

        @Override
        public void paint(Graphics g) {
            Dimension d = getSize();
            for (int x = 0; x < d.width; x += image.getIconWidth()) {
                for (int y = 0; y < d.height; y += image.getIconHeight()) {
                    g.drawImage(image.getImage(), x, y, null, null);
                }
            }
            super.paint(g);
        }
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                Test test = new Test();
            }
        });
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • I have a feeling this might still pop up an error. Did you compile it? I may be wrong. :-) – Kazekage Gaara Jun 25 '12 at 06:40
  • Yes. I did mean that. Will have to do a bit of reading on it I suppose. :-) – Kazekage Gaara Jun 25 '12 at 07:06
  • thks for the reply the program works error free ,but i didn't understood "private static final long serialVersionUID = 1L;" ,what does this mean ,also the image is not showing only blank background ,could you pls help me once more. thks – Tom C Jun 25 '12 at 07:25
  • @TomC: see Bloch, _Effective Java_, Item 74: Implement Serializable judiciously. – trashgod Jun 25 '12 at 16:58
2

I'll explain you your error: Your test() method is a static method. It cannot access non-static methods/variables directly (this makes perfect programming sense, comment if you want me to elaborate). Static methods and variables can only access static members. You need to create an object of a static member and that object can access other non-static members.

As for the corrections required in your code, mKorbel's solution is perfect. However, to add an image to a JPanel, its best to "add" it as a JLabel, rather than to draw it. :

BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
frame.add( picLabel );//see javadocs for JLabel for more info

EDIT

But you need a background image. The following is the corrected code:

class Cr extends JPanel{
    //change here ('\\' is the escape sequence for '\') :
    ImageIcon image = new ImageIcon("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
    public void paint( Graphics g ) {
    Dimension d = getSize();
    for( int x = 0; x < d.width; x += image.getIconWidth() )
    for( int y = 0; y < d.height; y += image.getIconHeight() )
    g.drawImage( image.getImage(), x, y, null, null );
    super.paint(g);
    }           
} 
Vedant Agarwala
  • 18,146
  • 4
  • 66
  • 89
  • thks ,i am new to java ,so little knowledge in static stuffs . also mKorbel's solution is excellent ,but i didn't understood "private static final long serialVersionUID = 1L;" ,what does this mean ,also the image is not showing only blank background ,could you pls help me,image is located in 'C' drive -my pictures. – Tom C Jun 25 '12 at 08:36
  • "private static final long serialVersionUID = 1L;" is a variable that stores the serial Version of your program. It is redundant in your case (that was added by the IDE). you can delete it if you want. – Vedant Agarwala Jun 25 '12 at 08:44
  • it must be stupid for me to ask ,but i am a starter so please excuse me for asking ,should i use it in class cr instead of ImageIcon? – Tom C Jun 25 '12 at 09:00
  • use it in your panel1() method (where you have created the fame = new JFrame and added other components). that's where you have used your "frame" object, and only there will frame.add(picLabel); work – Vedant Agarwala Jun 25 '12 at 09:05
  • finally i found why my image was not loading ,it should be in my class folder ,thks for your hlp guys . thks to both vedant1811 and mKorbel for your assistance. – Tom C Jun 25 '12 at 09:42
  • ya i just realized you don't want to add an image, u want to use it as a background. Then the code you have is fine, except you will need to edit: ImageIcon image = new ImageIcon("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg"); i hope this is self-explanatory. You can use any path using this technique but it's better to use the default path for portability – Vedant Agarwala Jun 25 '12 at 09:50
  • i tried using buffered image and got this as output [link]http://i47.tinypic.com/c57jk.png -my new code i have shown above in my first post. Why is the background at top portion, not showing the image?also how can i show my frame at center of my monitor's screen, currently it is loaded at top-left corner. thks pls reply – Tom C Jun 25 '12 at 12:05
  • Yes that's because this the JLabel is taking the entire area of the frame. This isn't a discussion forum, since your question is answered you should get back to work and post new questions if you encounter further problems. For learning java Swing, see the http://docs.oracle.com/javase/tutorial/uiswing/index.html – Vedant Agarwala Jun 25 '12 at 12:19
  • Use the LayoutManager for your JFrame. – Vedant Agarwala Jun 25 '12 at 12:20