透明JTextField和JLabel显示背景图像

时间:2013-12-20 16:53:49

标签: java swing jframe jlabel jtextfield

我遇到JTextField和JLabel的问题,我的JFrame背景中没有出现图片。我使用.setOpaque(false)将不透明度设置为false;但它不起作用。感谢您的帮助。

package Game;

import javax.swing.*;

//window

public class Frame {

    public void window(){//window method

        JPanel jp = new JPanel();
        JLabel jl = new JLabel("Enter a Letter");
        JTextField tf = new JTextField(10);
        jl.setOpaque(false);  
        jl.setBorder(null);
        jp.add(jl);
        jp.add(tf);


    LoadImageApp i = new LoadImageApp();
    i.setOpaque(false);

    JFrame gameFrame = new JFrame();//declaration
    gameFrame.getContentPane().add(jp);
    gameFrame.add(i);//adds image to window
    gameFrame.setTitle("Hangman");//title of frame window
    gameFrame.setSize(850, 600);//set size of frame
    gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when 'x' button pressed
    gameFrame.setIconImage(new ImageIcon("Hangman-Game-grey.png").getImage());//set the frame icon to an image loaded from a file
    gameFrame.setLocationRelativeTo(null);//window centered over null(center)
    gameFrame.setResizable(false);
    //gameFrame.getContentPane().setBackground(Color.WHITE);
    gameFrame.setVisible(true);//display frame


}   
}





package Game;

//import statements

import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class LoadImageApp extends JPanel{
    private static final long serialVersionUID = 1L;
        private ImageIcon image;

        public void paintComponent (Graphics g){
            super.paintComponent(g);
            image = new ImageIcon("hangman.png");
            image.paintIcon(this, g, 0, 9);
        }
}





package Game;

//main class

public class GameMain {
    public static void main (String []args){
        Frame frame = new Frame();//declaration
        frame.window();//window call
    }

}

1 个答案:

答案 0 :(得分:1)

gameFrame.getContentPane().add(jp);
gameFrame.add(i);//adds image to window

上面的代码应该是这样的:

gameFrame.add(i); //adds background image to window
i.add( jp ); // add panel containing label to background image panel

此外,您不应该在任何绘画方法中进行I / O.只要Swing确定需要重新绘制组件,就可以调用绘制方法。创建类时应该读取图像。