[英]JLabel as Background Image
I can't seem to figure this out. 我似乎无法弄清楚。
Please help I need this to work out to continue my project. 请帮助我解决这个问题以继续我的项目。
Awww I have to add this for allowing me to post Awww,我必须添加此内容才能发布
import javax.swing.*;
import java.awt.*;
@SuppressWarnings("serial")
public class MainFrame extends JFrame {
public static void Draw(){
DrawFrame();
}
public static void DrawFrame(){
int h = 600;
int w = 340;
JFrame frame = new JFrame();
JLabel background1 = new JLabel(new ImageIcon("/res/mariocraft_main.png"));
frame.setResizable(false);
frame.setSize(h, w);
frame.setTitle("MarioCraft");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(background1);
background1.setVisible(true);
background1.setIcon(new ImageIcon("/res/mariocraft_main.png"));
background1.setText("Background failed to load");
}
}
A JLabel always displays the image at its actual size so you should not be manually setting the size of the frame. JLabel始终以实际大小显示图像,因此您不应该手动设置框架的大小。
Instead the code should be something like: 相反,代码应类似于:
JLabel background1 = new JLabel(new ImageIcon("/res/mariocraft_main.png"));
JFrame frame = new JFrame();
frame.add(background1);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
You need to add the JLabel
instance to the JFrame
before you realize it (ie make it visible). 您需要在实现之前将JLabel
实例添加到JFrame
(即使其可见)。 Also, remove these three calls: 另外,删除这三个调用:
background1.setVisible(true);
background1.setIcon(new ImageIcon("/res/mariocraft_main.png"));
background1.setText("Background failed to load");
They are completely unnecessary. 它们是完全不必要的。 Also, another approach to setting a background image to a component is to override it's paintComponent
method and draw the image directly to it's Graphics
object. 另外,将背景图像设置为组件的另一种方法是重写其paintComponent
方法,然后将图像直接绘制到其Graphics
对象。
Do you want to set JLabel
as background image for the JFrame
. 是否要将JLabel
设置为JFrame
背景图像。 Then, 然后,
frame.setContentPane(new JLabel(new ImageIcon("someimage.jpg"));
See a sample code snippet taken for here 请参阅此处的示例代码片段
frame.setLayout(new BorderLayout());
frame.setContentPane(new JLabel(new ImageIcon("someimage.jpg")));
frame.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
frame.add(l1);
frame.add(b1);
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Mainframe extends JFrame
{
public JLabel image ;
public Container c;
public Mainframe()
{
c=this.getContentPane();
image=new JLabel(new ImageIcon("bg.jpg"));
image.setSize(500, 550);
c.setLayout(new FlowLayout());
c.add(image);
add(image);
this.setSize(500, 550);
this.show();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Mainframe();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.