问题描述
我在JPanel
中插入了背景图像 e,但是一些界面元素消失了.以下Java Swing元素不会出现:
I insert a background image into a JPanel
but some interface elements disappear. The following Java Swing elements do not appear:
- label_titulo
- label_usuario
- label_password
- button_acceder
**您可以使图像透明还是元素不透明(setOpaque(false)),即使将其放在这些元素上对我也不起作用.
**Can you make the image transparent or that the elements are not opaque (setOpaque (false)), even putting it to those elements does not work for me.
为什么某些元素具有矩形将其封装为灰色?**
Why do some elements have rectangles encapsulating them in gray?**
代码:
public class InicioSesion extends javax.swing.JFrame{
private Image imagenFondo;
private URL fondo;
public InicioSesion(){
initComponents();
try{
fondo = this.getClass().getResource("fondo.jpg");
imagenFondo = ImageIO.read(fondo);
}catch(IOException ex){
ex.printStackTrace();
System.out.print("Imagen no cargada.");
}
}
@Override
public void paint(Graphics g){
super.paint(g);
g.drawImage(imagenFondo, 0, 0, getWidth(), getHeight(), this);
}
}
加载"RUN"时,.java文件对我显示如下:
When loading "RUN" the .java file appears to me as follows:
最初的设计如下:
推荐答案
public void paint(Graphics g){
super.paint(g);
g.drawImage(imagenFondo, 0, 0, getWidth(), getHeight(), this);
}
不要覆盖paint().绘制方法负责绘制子组件.因此,您的代码会绘制子组件,然后在组件之上绘制图像.
Don't override paint(). The paint method is responsible for painting the child components. So your code paints the child components and then draws the image over top of the components.
相反,对于组件的自定义绘制,您可以覆盖JPanel
的paintComponent()
方法:
Instead, for custom painting of a component you override the paintComponent()
method of a JPanel
:
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(imagenFondo, 0, 0, getWidth(), getHeight(), this);
}
从深入了解绘制机制以获取更多信息.
从Custom Painting
的Swing教程中阅读整个部分.解决方案是在JPanel上进行自定义绘制,然后将面板添加到框架中.
Read the entire section from the Swing tutorial on Custom Painting
. The solution is to do the custom painting on a JPanel and then add the panel to the frame.
框架的内容窗格是JPanel.因此,您实际上将用绘制背景图像的自定义JPanel替换默认的内容窗格.将自定义面板的布局设置为BorderLayout
,它将像默认内容窗格一样工作.
The content pane of a frame is a JPanel. So you will in effect be replacing the default content pane with your custom JPanel that paints the background image. Set the layout of your custom panel to a BorderLayout
and it will work just like the default content pane.
这篇关于JPanel透明背景和显示元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!