Java - 颜色或图像不能设置为背景

时间:2016-01-01 15:09:05

标签: java swing colors

基本上我创建了两个类; Main和JFrameOptions。 但是,似乎我无法绘制背景是否使用JLabel,setContentPane或setBackground它们都不起作用。我做错了什么?

主:

package game;

public class Main{

public static void main(String[] args) {
JFrameOptions.Options();
TSDTDir.Directory();
}
}

JFrameOptions:

package game;

import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JFrame;


public class JFrameOptions{

 static String setTitle = ("Game");;

 public static int width = 920;
 public static int height = 517;

public static void Options() {
    JFrame window = new JFrame(setTitle);
    window.setSize(width, height);
    window.setVisible(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setResizable(false);
    window.setLocationRelativeTo(null);
    window.toFront();
    window.setBackground(Color.black);
}
}

编辑:

我得到了解决问题的基本要点:window.getContentPane().setBackground( Color.PINK );

但是,如何加载必须具有登录字段功能的图像呢?

编辑2: 它不起作用。背景不画画。

public static void Options() {

        //Displays the title 
        JFrame window = new JFrame(setTitle);
        window.setSize(width, (int) height);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setIconImage(favIcon);
        window.setResizable(false);
        window.setLocationRelativeTo(null);
        window.toFront();

        //window.getContentPane().setBackground(Color.black);


        BufferedImage img = null;
    try {
        img = ImageIO.read(new File("Background.png"));
        window.setContentPane(new JLabel(new ImageIcon(img)));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

当然,Background.png文件位于游戏文件夹的目录中:http://prntscr.com/9kxc4i

图像文件位置图像:
enter image description here

控制台图片:
enter image description here

运行GUI图像:
enter image description here

1 个答案:

答案 0 :(得分:1)

这是一个常见问题,您在建立UI之前调用setVisible。当涉及到对UI进行更改时,Swing很懒,要求您决定何时应该更新UI,这是为了保持效率而故意和完成(想象在UI中添加十几个新组件,你不会&#39 ;我希望重新验证和更新用户界面,直到你完成,否则你会浪费很多时间)

简单的解决方案是,最后致电setVisible ......

public static void Options() {

    //Displays the title 
    JFrame window = new JFrame(setTitle);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setIconImage(favIcon);

    //window.getContentPane().setBackground(Color.black);
    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("Background.png"));
        window.setContentPane(new JLabel(new ImageIcon(img)));
    } catch (IOException e) {
        e.printStackTrace();
    }
    window.setResizable(false);
    window.pack();
    window.setLocationRelativeTo(null);
    window.setVisible(true);
    window.toFront();
}

请注意,JLabel默认情况下没有布局管理器,即使您应用了布局管理器,它也不会使用它来计算preferredSize,只依赖于icon }和text属性。

查看this discussion了解更多详情和替代方案