Java 将图像设置为 JPanel 背景的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19125707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simplest way to set image as JPanel background
提问by Joshua Martin
How would I add the backgroung image to my JPanel without creating a new class or method, but simply by inserting it along with the rest of the JPanel's attributes?
我如何将背景图像添加到我的 JPanel 而不创建新的类或方法,而只需将它与 JPanel 的其余属性一起插入?
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class.
我正在尝试使用图像设置 JPanel 的背景,但是,我发现的每个示例似乎都建议使用自己的类扩展面板。
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
我一直在寻找一种方法来简单地添加图像,而无需创建一个全新的类并在相同的方法中(试图使事情井井有条和简单)。
Here is an example of the method that sets my JPanel:
这是设置我的 JPanel 的方法示例:
public static JPanel drawGamePanel(){
//Create game panel and attributes
JPanel gamePanel = new JPanel();
Image background = Toolkit.getDefaultToolkit().createImage("Background.png");
gamePanel.drawImage(background, 0, 0, null);
//Set Return
return gamePanel;
}
回答by Maxim Shoustin
As I know the way you can do it is to override paintComponent
method that demands to inherit JPanel
据我所知,您可以这样做的paintComponent
方法是覆盖需要继承的方法JPanel
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // paint the background image and scale it to fill the entire space
g.drawImage(/*....*/);
}
The other way (a bit complicated) to create second custom JPanel
and put is as background for your main
创建第二个自定义JPanel
并放置的另一种方式(有点复杂)是您主要的背景
ImagePanel
图像面板
public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image = null;
private int iWidth2;
private int iHeight2;
public ImagePanel(Image image)
{
this.image = image;
this.iWidth2 = image.getWidth(this)/2;
this.iHeight2 = image.getHeight(this)/2;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
{
int x = this.getParent().getWidth()/2 - iWidth2;
int y = this.getParent().getHeight()/2 - iHeight2;
g.drawImage(image,x,y,this);
}
}
}
EmptyPanel
空面板
public class EmptyPanel extends JPanel{
private static final long serialVersionUID = 1L;
public EmptyPanel() {
super();
init();
}
@Override
public boolean isOptimizedDrawingEnabled() {
return false;
}
public void init(){
LayoutManager overlay = new OverlayLayout(this);
this.setLayout(overlay);
ImagePanel iPanel = new ImagePanel(new IconToImage(IconFactory.BG_CENTER).getImage());
iPanel.setLayout(new BorderLayout());
this.add(iPanel);
iPanel.setOpaque(false);
}
}
IconToImage
图标到图像
public class IconToImage {
Icon icon;
Image image;
public IconToImage(Icon icon) {
this.icon = icon;
image = iconToImage();
}
public Image iconToImage() {
if (icon instanceof ImageIcon) {
return ((ImageIcon)icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
/**
* @return the image
*/
public Image getImage() {
return image;
}
}
回答by Sage
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class
我正在尝试使用图像设置 JPanel 的背景,但是,我发现的每个示例似乎都建议使用自己的类扩展面板
yes you will have to extend JPanel
and override the paintcomponent(Graphics g)
function to do so.
是的,您必须扩展JPanel
和覆盖该paintcomponent(Graphics g)
功能才能这样做。
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
我一直在寻找一种方法来简单地添加图像,而无需创建一个全新的类并使用相同的方法(试图使事情井井有条和简单)。
You can use other component which allows to add image as icon directly e.g. JLabel
if you want.
您可以使用其他允许直接将图像添加为图标的组件,例如,JLabel
如果您愿意。
ImageIcon icon = new ImageIcon(imgURL);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
But again in the bracket trying to keep things organized and simple!! what makes you to think that just creating a new class will lead you to a messy world ?
但是再次在括号中试图保持组织和简单!是什么让你认为仅仅创建一个新类就会导致你进入一个混乱的世界?
回答by camickr
Simplest way to set image as JPanel background
将图像设置为 JPanel 背景的最简单方法
Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.
不要使用 JPanel。只需将 JLabel 与 Icon 一起使用,就不需要自定义代码。
See Background Panelfor more information as well as a solution that will paint the image on a JPanel with 3 different painting options:
有关更多信息以及将使用 3 种不同绘画选项在 JPanel 上绘制图像的解决方案,请参阅背景面板:
- scaled
- tiled
- actual
- 缩放
- 平铺
- 实际的
回答by javajon
Draw the image on the background of a JPanel that is added to the frame. Use a layout manager to normally add your buttons and other components to the panel. If you add other child panels, perhaps you want to set child.setOpaque(false).
在添加到框架的 JPanel 的背景上绘制图像。使用布局管理器通常将您的按钮和其他组件添加到面板。如果您添加其他子面板,也许您想设置 child.setOpaque(false)。
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
public class BackgroundImageApp {
private JFrame frame;
private BackgroundImageApp create() {
frame = createFrame();
frame.getContentPane().add(createContent());
return this;
}
private JFrame createFrame() {
JFrame frame = new JFrame(getClass().getName());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
private void show() {
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private Component createContent() {
final Image image = requestImage();
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String label : new String[]{"One", "Dois", "Drei", "Quatro", "Peace"}) {
JButton button = new JButton(label);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(Box.createRigidArea(new Dimension(15, 15)));
panel.add(button);
}
panel.setPreferredSize(new Dimension(500, 500));
return panel;
}
private Image requestImage() {
Image image = null;
try {
image = ImageIO.read(new URL("http://www.johnlennon.com/wp-content/themes/jl/images/home-gallery/2.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new BackgroundImageApp().create().show();
}
});
}
}
回答by Amit Tiwari
public demo1() {
initComponents();
ImageIcon img = new ImageIcon("C:\Users\AMIT TIWARI\Documents\NetBeansProjects\try\src\com\dd.jpeg"); //full path of image
Image img2 = img.getImage().getScaledInstance(mylabel.getWidth(), mylabel.getHeight(),1);
ImageIcon img3 = new ImageIcon(img2);
mylabel.setIcon(img3);
}
回答by Sathvik
class Logo extends JPanel
{
Logo()
{
//code
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
ImageIcon img = new ImageIcon("logo.jpg");
g.drawImage(img.getImage(), 0, 0, this.getWidth(), this.getHeight(), null);
}
}