【问题标题】:Background Images With JFrame带有 JFrame 的背景图像
【发布时间】:2015-06-20 14:51:49
【问题描述】:

这是我正在使用的 Yahtzee 游戏的一部分。我正在尝试将背景设置为项目文件夹中的 yahtzee.png 文件。 我评论了我这样做的尝试,因为它不适合我。有没有更好的方法来设置它?

     ExFrame(int numPlayers)
  { 
      frame = new JFrame();
      frame.setSize(450+150*numPlayers,700);

        frame.setTitle("YAHTZEE!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.numPlayers = numPlayers;
        this.numGridRows = 20;
        this.buttonWidth = 140;
        this.numCreateButLabCalls = 0;
        this.component = new DiceComponent(buttonWidth*2);
        this.cButtons = new JButton[numGridRows];
        this.cButtonsText = new String[numGridRows];
        this.cLabels = new JLabel[numPlayers][numGridRows];
        this.statusLabel = new JLabel("<html>New game has been started!<br>Please select the dice that you wish to hold or click on a scoring button</html>");
        this.score = new YahtzeeScore[numPlayers];

        //populate score array
        for(int k = 0; k < numPlayers; k++)
        {
            score[k] = new YahtzeeScore(cButtons,cLabels, statusLabel, component.getDieArray(), cButtonsText, numGridRows, k);
        }

        statusLabel.setPreferredSize(new Dimension(buttonWidth*2, 100));
        centerPanel = new JPanel(new GridLayout(numGridRows,numPlayers+1)); //columns based on numPlayers

        component.rollDice(true);
        popCenterPanel();
        for(int k = 0; k < numPlayers; k++)
            score[k].reset();
        addListeners();

        frame.setLayout(null);
        frame.add(component);
        frame.add(statusLabel);
        frame.add(centerPanel);
    //  frame.add(new JLabel(new ImageIcon("/YahtzeeAgain/yahtzee.png")));
        Insets insets = frame.getInsets();
        Dimension size = statusLabel.getPreferredSize();
        statusLabel.setBounds(100+ insets.left,insets.top,size.width,size.height);
        size = component.getPreferredSize();
        component.setBounds(insets.left, 150 + insets.top,
                 size.width, size.height);
        size = centerPanel.getPreferredSize();
        centerPanel.setBounds(290 + insets.left, 140 + insets.top,
                 size.width, size.height);
    centerPanel.setBackground(Color.gray);
    frame.add(this);
    frame.setVisible(true); 


    }

【问题讨论】:

  • 你能用绝对路径检查并分享结果吗?
  • 如果可以,请避免使用 JLabel 作为背景组件,它不会根据其子组件计算其首选大小,而是基于图标和文本属性。而是创建一个自定义组件并重写它的paintComponent方法,对于example,虽然稍微复杂一点,但更灵活

标签: java swing


【解决方案1】:

最好的方法:

将您的背景 JLabel 添加到 Frame 的内容窗格中(就像您正在做的那样),然后对其执行 setLayout(null),并将所有其他组件添加到您的背景 JLabel

【讨论】:

  • 请注意,JLabel 不会根据子组件的需要计算其首选大小,而是会使用标签的图标和文本属性,这可能会在不同平台上出现问题...
【解决方案2】:

怎么样

frame.setContentPane(new JLabel(new ImageIcon("/YahtzeeAgain/yahtzee.png")));

【讨论】:

  • 当我这样做时,它会将整个屏幕设置为灰色,并且似乎覆盖了所有其他 JPanel。有趣...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-13
  • 2011-02-08
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
相关资源
最近更新 更多