【问题标题】:Transparent JTextField and JLabel to show background image透明 JTextField 和 JLabel 显示背景图像
【发布时间】:2013-12-20 16:53:49
【问题描述】:

我在 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
    }

}

【问题讨论】:

    标签: java swing jframe jlabel jtextfield


    【解决方案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 确定组件需要重新绘制时,都可以调用绘制方法。创建类时应读取图像。

    【讨论】:

    • 你能详细说明绘画方法并可能给我一个例子吗?你能告诉我最有效的绘画方法编码方法吗?你能告诉我如何改变我的 JTextField 和 JLabel 的位置吗?
    • Swing 设计为与Layout Managers 一起使用。使用适当的布局管理器或具有不同布局管理器的面板来实现您想要的结果。
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2011-02-05
    相关资源
    最近更新 更多