Java,BorderLayout.CENTER,获取JPanel的宽度和高度 [英] Java, BorderLayout.CENTER, getting the width and height of the JPanel

查看:230
本文介绍了Java,BorderLayout.CENTER,获取JPanel的宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swing和AWT(用于侦听器)制作一个小程序.我有一个关于获取我的JPanel(名为Chess的类)的大小的问题. 我的布局:

I am using Swing and AWT (for the listeners) to make a small program. I have a problem concerning getting the size of my JPanel (the class named Chess). My Layout:

public class Main extends JFrame implements MouseListener, ActionListener{

    Chess chessPanel = new Chess ();
    JButton newGameButton = new JButton ("New Game");
    JButton loadGameButton = new JButton ("Load Game");
    JButton saveGameButton = new JButton ("Save Game");
    JButton exitButton = new JButton ("Exit");

    public static void main (String [] args) {
        new Main();
    }

    Main () {
        super ("Chess");
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(dim);
        setLocation(0,0);
        setUndecorated(true);

        chessPanel.addMouseListener(this);
        add(chessPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());


        newGameButton.addActionListener(this);
        loadGameButton.addActionListener(this);
        saveGameButton.addActionListener(this);
        exitButton.addActionListener(this);

        buttonPanel.add(newGameButton);
        buttonPanel.add(loadGameButton);
        buttonPanel.add(saveGameButton);
        buttonPanel.add(exitButton);

        add(buttonPanel, BorderLayout.SOUTH);

        setVisible(true);
    }

    // ... Code ...
}

如代码所示,我在CENTER中有一个JPanel,几乎占据了所有屏幕.在底部,我有另一个JPanel(SOUTH),其中有一排按钮.

As you can see by the code, I have one JPanel in the CENTER, which takes nearly all the screen. In the bottom I have another JPanel (SOUTH), which has a row of buttons.

我需要的是CENTER中的JPanel占用的大小.当我调用从JPanel继承的getWidth(),getHeight()或getBounds()方法时,由于BorderLayout的原因,它们都返回0. 知道如何获得真实价值吗?

What I need is the size that the JPanel in the CENTER takes. When I call the getWidth(), getHeight() or getBounds() methods inherited from JPanel, they all return 0, because of the BorderLayout. Any idea how to get the real values?

PS:屏幕始终占据整个屏幕,并且如果有帮助,将永远不会调整大小.

PS: The screen always takes up the entire screen, and will never be resized, if that helps.

推荐答案

您可能会在呈现JPanel之前调用getWidth,因此它将为0.解决方案是在之后获得的大小渲染,例如在保存此JPanel的根容器上调用pack()或setVisible(true)之后.

You're likely calling getWidth before the JPanel has been rendered, and so it will be 0. The solution is to get the size after rendering, for instance after pack() or setVisible(true) has been called on the root container that holds this JPanel.

此外,我建议不要在任何对象上调用setSize(),因为大多数标准布局管理器都会观察组件的首选大小,而不是组件的大小,并且当您调用pack()告诉布局管理器执行其操作时,集合大小通常会被忽略.您可能希望通过覆盖其setPreferredSize方法(如果它需要一定的大小)来使位于中心的JPanel设置自己的大小.然后,当您调用pack时,让JFrame及其容纳的容器根据其布局管理器来设置下注适合的大小.

Also, I recommend against calling setSize() on anything since most of the standard layout managers observe the preferred size of a component, not the size, and when you call pack() telling the layout managers to do their thing, the set sizes are usually ignored. You may want to make your JPanel that is in the center set its own size by overriding its setPreferredSize method if it needs to be a certain size. Then let the JFrame and its held containers set the bet fit size based on the their layout managers when you call pack.

例如

import java.awt.*;
import javax.swing.*;

public class Main extends JFrame {

   Chess chessPanel = new Chess();
   JButton newGameButton = new JButton("New Game");
   JButton loadGameButton = new JButton("Load Game");
   JButton saveGameButton = new JButton("Save Game");
   JButton exitButton = new JButton("Exit");

   public static void main(String[] args) {
      new Main();
   }

   Main() {
      super("Chess");
      add(chessPanel, BorderLayout.CENTER);

      JPanel buttonPanel = new JPanel();
      buttonPanel.setLayout(new FlowLayout());

      buttonPanel.add(newGameButton);
      buttonPanel.add(loadGameButton);
      buttonPanel.add(saveGameButton);
      buttonPanel.add(exitButton);

      System.out.printf("chessPanel Size before rendering: %s%n", chessPanel.getSize());
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      add(buttonPanel, BorderLayout.SOUTH);
      pack();
      System.out.printf("chessPanel Size after rendering: %s%n", chessPanel.getSize());
      setLocationRelativeTo(null);
      setVisible(true);
   }

   // ... Code ...
}

@SuppressWarnings("serial")
class Chess extends JPanel {
   private static final int CHESS_WIDTH = 600;
   private static final int CHESS_HEIGHT = CHESS_WIDTH;
   private static final int MAX_ROW = 8;
   private static final int MAX_COL = 8;
   private static final Color LIGHT_COLOR = new Color(240, 190, 40);
   private static final Color DARK_COLOR = new Color(180, 50, 0);

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(CHESS_WIDTH, CHESS_HEIGHT);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      int panelWidth = getWidth();
      int panelHeight = getHeight();
      int sqrWidth = panelWidth / MAX_ROW;
      int sqrHeight = panelHeight / MAX_COL;
      for (int row = 0; row < MAX_ROW; row++) {
         for (int col = 0; col < MAX_COL; col++) {
            Color c = (row % 2 == col % 2) ? LIGHT_COLOR : DARK_COLOR;
            g.setColor(c);
            int x = (row * panelWidth) / MAX_ROW;
            int y = (col * panelHeight) / MAX_COL;
            g.fillRect(x, y, sqrWidth, sqrHeight);
         }
      }
   }
}

这篇关于Java,BorderLayout.CENTER,获取JPanel的宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆