Java 将背景图像添加到我的jpanel时遇到问题,找不到错误,我也不理解错误

Java 将背景图像添加到我的jpanel时遇到问题,找不到错误,我也不理解错误,java,swing,Java,Swing,问题代码是这个部分,它是从我试图将图像添加到面板时开始的 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 Co

问题代码是这个部分,它是从我试图将图像添加到面板时开始的

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();
                                  }
            });
        }


}
你们能帮我吗,伙计们,请说出我要改变的一切。 它说错误非静态变量不能从静态上下文引用。这是事先准备好的。 thks to every one和“vedant1811”的布局理念,“mKorbel”用于覆盖绘画,“nIcE cOw”用于将我的代码放在中心,我现在使用它,我使我的程序终于工作了。thks

我的最终代码


我不想评论什么

    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);
    }
    }      

我不想评论什么

    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);
    }
    }      

我会向你解释你的错误: 您的测试方法是静态方法。它不能直接访问非静态方法/变量。这非常有意义,如果您想让我详细说明,请发表评论。静态方法和变量只能访问静态成员。您需要创建静态成员的对象,该对象可以访问其他非静态成员

至于代码中需要的更正,mKorbel的解决方案是完美的。但是,要将图像添加到JPanel,最好将其添加为JLabel,而不是绘制图像:

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();
            }
        });
    }
}
编辑

但是你需要背景图像。以下是更正的代码:

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

我会向你解释你的错误: 您的测试方法是静态方法。它不能直接访问非静态方法/变量。这非常有意义,如果您想让我详细说明,请发表评论。静态方法和变量只能访问静态成员。您需要创建静态成员的对象,该对象可以访问其他非静态成员

至于代码中需要的更正,mKorbel的解决方案是完美的。但是,要将图像添加到JPanel,最好将其添加为JLabel,而不是绘制图像:

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();
            }
        });
    }
}
编辑

但是你需要背景图像。以下是更正的代码:

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

我觉得这可能还是会出现错误。你编译了吗?我可能错了-对我是那个意思。我想我得读一读-thks用于回复程序工作时无错误,但我不理解私有静态final long serialVersionUID=1L,这意味着什么,而且图像不只是显示空白背景,请你再次帮助我。thks@TomC:参见Bloch,《有效的Java》,第74项:明智地实现可序列化。我感觉这可能仍然会弹出一个错误。你编译了吗?我可能错了-对我是那个意思。我想我得读一读-thks用于回复程序工作时无错误,但我不理解私有静态final long serialVersionUID=1L,这意味着什么,而且图像不只是显示空白背景,请你再次帮助我。thks@TomC:参见Bloch,《有效的Java》,第74项:明智地实现可序列化。thks,我对Java不熟悉,所以对静态内容知之甚少。另外,mKorbel的解决方案非常好,但我不了解私有静态final long serialVersionUID=1L,这意味着什么,而且图像不仅显示空白背景,请您帮助我,图像位于“C”驱动器中-我的图片。私有静态最终long serialVersionUID=1L;是存储程序串行版本的变量。在您的案例中,IDE添加的是冗余的。如果你想的话,你可以删除它。我这样问一定很愚蠢,但我是初学者,所以请原谅我这样问,我应该在cr类中使用它而不是ImageIcon吗?在你创建fame=new JFrame并添加其他组件的panel1方法中使用它。这就是您使用frame对象的地方,只有frame.addpicLabel;最后我找到了为什么我的图像没有加载,它应该在我的类文件夹中,thks为你们的hlp家伙。谢谢你的帮助。我是java新手,所以对静态知识知之甚少。另外,mKorbel的解决方案非常好,但我不了解私有静态final long serialVersionUID=1L,这意味着什么,而且图像不仅显示空白背景,请您帮助我,图像位于“C”驱动器中-我的图片。私有静态最终long serialVersionUID=1L;是存储程序串行版本的变量。在您的案例中,IDE添加的是冗余的。如果你想的话,你可以删除它。我这样问一定很愚蠢,但我是初学者,所以请原谅我这样问,我应该在cr类中使用它而不是ImageIcon吗?在你创建fame=new JFrame并添加其他组件的panel1方法中使用它。这就是您使用frame对象的地方,只有frame.addpicLabel;最后我找到了为什么我的图像没有加载,它应该在我的类文件夹中,thks为你们的hlp家伙。谢谢你的帮助。当你扩展一个JPanel时,千万不要覆盖它的油漆。。。方法,在内部始终选择paintComponent…`,这就是要走的路,只要是co
请看一下这个例子。此外,为了使框架位于屏幕中央,只需在frameObject.setVisibletrue;之前写入frameObject.setLocationRelativeTonull即可;,就是这样:-thks代表中央屏幕的代码。非常欢迎您并保持微笑:-当您扩展JPanel时,请不要覆盖它的绘画。。。方法,在内部始终选择paintComponent…`,这就是要走的路,就所关心的问题而言,请看一下这个示例。此外,为了使框架位于屏幕中央,只需在frameObject.setVisibletrue;之前写入frameObject.setLocationRelativeTonull即可;,就这样:-thks代表中央屏幕的代码。非常欢迎您并保持微笑:-