Java 透明JTextField和JLabel显示背景图像
我对JTextField和JLabel在JFrame的背景中没有出现图像感到困难。我已经使用.setOpaque(false)将不透明度设置为false;但它不起作用。提前谢谢你的帮助Java 透明JTextField和JLabel显示背景图像,java,swing,jframe,jlabel,jtextfield,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(); JLa
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
}
}
上述代码应类似于:
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的位置。Swing设计用于。使用适当的布局管理器或具有不同布局管理器的面板来实现所需的结果。
gameFrame.add(i); //adds background image to window
i.add( jp ); // add panel containing label to background image panel