簡體   English   中英

JPanel 填滿整個 JFrame

[英]JPanel fill the whole JFrame

我想在 JFrame 中的 100,50 位置放置一個大小為 300,200 的 JPanel,但以下代碼使整個 JFrame 被 JPanel 填充,我錯在哪里? 代碼:

public class Class1  {
      
    public static void main(String[] args) {
   
         JFrame frame = new JFrame();
         JPanel panel = new JPanel();
         
         frame.setSize(700, 500);              
         panel.setSize(300, 200);
         panel.setBackground(Color.green);
         panel.setCursor(new Cursor(java.awt.Cursor.HAND_CURSOR));
            
         frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);         
         frame.add(panel, BorderLayout.CENTER);                   
         frame.setVisible(true);
         frame.setLocationRelativeTo(null);
    }      
}

如果我更改 BorderLayout.SOUTH 或 NORTH,則 JPanel 看起來像 JFrame 底部或頂部的細線。 我也嘗試使用首選大小,但結果仍然相同。

在嘗試使用 Swing 進行任何操作之前,您需要了解布局管理器的基礎知識。

在這里學習教程https://docs.oracle.com/javase/tutorial/uiswing/layout/howLayoutWorks.html

如果您試圖用各種 Swing 控件構建一個表單,切勿使用絕對坐標來定位它們。 調整窗口大小應該根據您要使用的布局類型動態地重新定位您的控件。 如果您將面板用作繪圖畫布(這是我認為您所追求的),請查看下面的示例。

首先嘗試掌握一些基本布局,例如 BorderLayout 和 GridLayout。 一旦掌握,您可以通過將它們嵌套在一起來使用很少的東西來實現您想要的任何類型的布局。 還可以學習 ScrollPane 的基礎知識,以有效利用屏幕空間

至於您最初的問題,我創建了一個示例,說明 BorderLayout 的工作原理以及如何繪制到面板上的特定區域。 我還添加了一些代碼,以便您可以根據您是否位於給定面板中的較小區域來設置不同的光標。

嘗試這個:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class FrameDemo extends JFrame {
  private static final long serialVersionUID = 1L;

  public FrameDemo() {
    super("Frame Demo");
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    getContentPane().add(new CustomPanel(Color.RED), BorderLayout.NORTH);
    getContentPane().add(new CustomPanel(Color.GREEN), BorderLayout.SOUTH);
    getContentPane().add(new CustomPanel(Color.BLUE), BorderLayout.EAST);
    getContentPane().add(new CustomPanel(Color.YELLOW), BorderLayout.WEST);
    getContentPane().add(new JScrollPane(new CustomPanel(Color.BLACK)), BorderLayout.CENTER);

    pack();
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new FrameDemo();
        frame.setVisible(true);
      }
    });
  }
}

class CustomPanel extends JPanel implements MouseMotionListener {
  private static final long serialVersionUID = 1L;

  private static final Dimension PANEL_SIZE = new Dimension(200, 100);
  private static final int HAND_CURSOR_INDEX = 1;
  private static final int DEFAULT_CURSOR_INDEX = 0;
  private static final Cursor[] _cursors = new Cursor[] {
    Cursor.getDefaultCursor(),
    Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
    };

  // I want to place a JPanel with 300,200 size at 100,50 location in a JFrame
  private static final Rectangle _rectangle = new Rectangle(50, 10, 40, 50);

  public CustomPanel(Color color) {
  setBackground(color);
    addMouseMotionListener(this);
  }

  public Dimension getPreferredSize() {
    return PANEL_SIZE;
  }

  public Dimension getMinimumSize() {
    return PANEL_SIZE;
  }

  public Dimension getMaximumSize() {
    return PANEL_SIZE;
  }


  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.WHITE);
    g.fillRect(
        (int)_rectangle.getX(),
        (int)_rectangle.getY(),
        (int)_rectangle.getWidth(),
        (int)_rectangle.getHeight());
  }

  @Override
  public void mouseDragged(MouseEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void mouseMoved(MouseEvent e) {
    int cursorIndex = _rectangle.contains(e.getPoint()) ?
        HAND_CURSOR_INDEX :
        DEFAULT_CURSOR_INDEX;
        setCursor(_cursors[cursorIndex]);
  }
}

在此處輸入圖片說明

如果您希望面板占據 JFrame (contentpane) 的一部分,您可以使用其他布局管理器。 他是一個使用 GroupLayout 的例子:

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Class1  {

    public static void main(String[] args) {

         JFrame frame = new JFrame();
         JPanel panel = new JPanel();

         frame.getContentPane().setPreferredSize(new Dimension(700, 500) );
         panel.setPreferredSize(new Dimension(300, 200));
         panel.setBackground(Color.green);
         panel.setCursor(new Cursor(java.awt.Cursor.HAND_CURSOR));

         frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
         groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(104)
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, 493, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(103, Short.MAX_VALUE))
         );
         groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(100)
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, 301, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(99, Short.MAX_VALUE))
         );
         frame.getContentPane().setLayout(groupLayout);
         frame.pack();
         frame.setVisible(true);
         frame.setLocationRelativeTo(null);
    }


}

輸出:在此處輸入圖片說明

另一個使用 BorderLayout 和 4 個附加“占位符”或觸角面板的示例:

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;

public class Class1  {

    public static void main(String[] args) {

        JFrame frame = new JFrame();

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout(0, 0));

        JPanel centerPanel = new JPanel();
        centerPanel.setPreferredSize(new Dimension(300, 200));
        centerPanel.setBackground(Color.green);
        centerPanel.setCursor(new Cursor(java.awt.Cursor.HAND_CURSOR));
        frame.getContentPane().add(centerPanel);

        JPanel northPanel = new JPanel();
        northPanel.setBackground(Color.RED);
        northPanel.setForeground(Color.BLACK);
        northPanel.setPreferredSize(new Dimension(0, 150));
        frame.getContentPane().add(northPanel, BorderLayout.NORTH);

        JPanel westPanel = new JPanel();
        westPanel.setBackground(Color.MAGENTA);
        westPanel.setPreferredSize(new Dimension(200, 0));
        frame.getContentPane().add(westPanel, BorderLayout.WEST);

        JPanel southPanel = new JPanel();
        southPanel.setBackground(Color.YELLOW);
        southPanel.setPreferredSize(new Dimension(0, 150));
        frame.getContentPane().add(southPanel, BorderLayout.SOUTH);

        JPanel eastPanel = new JPanel();
        eastPanel.setBackground(Color.BLUE);
        eastPanel.setPreferredSize(new Dimension(200, 0));
        frame.getContentPane().add(eastPanel, BorderLayout.EAST);

        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }


}

輸出 :在此處輸入圖片說明

import javax.swing.*;
import java.awt.*;
public class Class1  {

    public static void main(String[] args) {

         JFrame frame = new JFrame();
         JPanel panel = new JPanel();
         JPanel another = new JPanel();
         JPanel emptyPanel = new JPanel();
         emptyPanel.setPreferredSize(new Dimension(700, 50));
         frame.setSize(700, 500); 


         panel.setMaximumSize(new Dimension(300, 200));
         panel.setMinimumSize(new Dimension(300, 200));
         panel.setPreferredSize(new Dimension(300, 200));
         panel.setBackground(Color.green);
         panel.setCursor(new Cursor(java.awt.Cursor.HAND_CURSOR));

         frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

         another.add(emptyPanel, BorderLayout.NORTH);
         another.add(panel, BorderLayout.CENTER);         
         
         frame.add(another);
         frame.setVisible(true);
         frame.setLocationRelativeTo(null);
    }


}

創建的圖像如下所示在此處輸入圖片說明

在我看來,JFrame 的直接子容器已調整為 JFrame(頂級容器)本身的大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM