簡體   English   中英

Java Swing應用程序-如何在面板中設置組件的高度(和寬度)

[英]java swing application - how to set the height (and width) of a component in a panel

我正在編寫一個Java swing應用程序,請問一個初學者的問題。

下面的屏幕是應用程序中顯示的兩個屏幕之一。 如您所見,在其頂部有一個大的圓圈,上面用紅色圈出。 我不能擺脫它。 我希望它很短,以便“清除”按鈕可以觸及框架的頂部。

我已經嘗試了很多,但是沒有用。 有人可以幫忙嗎?

在此處輸入圖片說明

這是java代碼:

**import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ContainerEventDemo extends JPanel implements ContainerListener, ActionListener {
  JTextArea displayResource;

  JTextArea displayGateway;

  GridBagLayout gridbag = (GridBagLayout) getLayout();

  GridBagConstraints c = new GridBagConstraints();
  JScrollPane inputScrollPane;

  JScrollPane scrollPaneGateway;
  JScrollPane scrollPaneResource;
  JTextArea inputArea;
  JPanel mainPanel;
  JButton listReadButton, insertButton, deleteButton, updateButton, clearButton, allButton;
  Vector<JButton> buttonList;
  static final String LIST_READ = "list_read";

  static final String UPDATE = "update";

  static final String INSERT = "insert";
  static final String DELETE = "delete";
//  static final String REMOVE = "remove";
  static final String ALL = "all";
  static final String CLEAR = "clear";
  static final String newline = "\n";
  public ContainerEventDemo() {
    super(new GridBagLayout());
    // create all the components.
    listReadButton = new JButton("List and Read");
    listReadButton.setActionCommand(LIST_READ);
    listReadButton.addActionListener(this);
    insertButton = new JButton("Insert");
    insertButton.setActionCommand(INSERT);
    insertButton.addActionListener(this);
    deleteButton = new JButton("Delete");
    deleteButton.setActionCommand(DELETE);
    deleteButton.addActionListener(this);

    updateButton = new JButton("Update");
    updateButton.setActionCommand(UPDATE);
    updateButton.addActionListener(this);

    allButton = new JButton("All");
    allButton.setActionCommand(ALL);
    allButton.addActionListener(this);

    mainPanel = new JPanel(new GridLayout(1, 1));
//    mainPanel.setSize(400, 100);
//    mainPanel.setPreferredSize(new Dimension(400, 5));
    mainPanel.addContainerListener(this);
    inputArea = new JTextArea();
    inputArea.setEditable(true);
    inputScrollPane = new JScrollPane(inputArea);
//    inputScrollPane.setSize(200, 175); // x, y
//    inputScrollPane.setPreferredSize(new Dimension(200, 75)); // x, y
    clearButton = new JButton("Clear");
    clearButton.setActionCommand(CLEAR);
    clearButton.addActionListener(this);
    addComponents();
    setPreferredSize(new Dimension(800, 800));  //  X, Y
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  }
  public void componentAdded(ContainerEvent e) {
//    displayMessage(" added to ", e);
  }
  public void componentRemoved(ContainerEvent e) {
 //   displayMessage(" removed from ", e);
  }
//  void displayMessage(String action, ContainerEvent e) {
//    displayGateway.append(((JButton) e.getChild()).getText() + " was" + action
//        + e.getContainer().getClass().getName() + newline);
//    displayGateway.setCaretPosition(displayGateway.getDocument().getLength());
//  }


  public void addComponents() {
        c.fill = GridBagConstraints.BOTH; // Fill entire cell.
        c.weighty = 22.0; // Button area and message area have equal height.
        c.gridwidth = GridBagConstraints.REMAINDER; // end of row
    //    c.gridheight = 40;
        gridbag.setConstraints(inputScrollPane , c);
        add(inputScrollPane);
        c.weighty = 0.0;
        c.weightx = 1.0; // Add/remove buttons have equal width.
        c.gridwidth = 1; // NOT end of row
        gridbag.setConstraints(listReadButton, c);
        add(listReadButton);
        c.gridwidth = GridBagConstraints.REMAINDER; // end of row
        gridbag.setConstraints(insertButton, c);
        add(insertButton);
        c.gridwidth = GridBagConstraints.REMAINDER; 
        c.gridwidth = 1; // NOT end of row
        gridbag.setConstraints(deleteButton, c);
        add(deleteButton);

        c.gridwidth = GridBagConstraints.REMAINDER; // end of row
        gridbag.setConstraints(updateButton, c);
        add(updateButton);
        c.gridwidth = GridBagConstraints.REMAINDER; // end of row
        gridbag.setConstraints(allButton, c);
        add(allButton);

        c.weighty = 1.0; // Button area and message area have equal height.
        gridbag.setConstraints(mainPanel, c);
        add(mainPanel);
  };
  /*
   * This could have been implemented as two or three classes or objects, for
   * clarity.
   */
  public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
    if (LIST_READ.equals(command) || UPDATE.equals(command) || INSERT.equals(command) || DELETE.equals(command) || ALL.equals(command)) {

        remove(inputScrollPane);
        remove(listReadButton);
        remove(insertButton);
        remove(deleteButton);
        remove(updateButton);
        remove(allButton);
//      mainPanel.revalidate(); // Make the button show up.
//      mainPanel.repaint(); // Make the button show up.

        c.fill = GridBagConstraints.BOTH; // Fill entire cell.
        c.gridwidth = GridBagConstraints.REMAINDER; // end of row
        c.weighty = 0.0;
        gridbag.setConstraints(clearButton, c);
        add(clearButton);
//      aKI
        displayGateway = new JTextArea();
        displayGateway.setEditable(false);
        scrollPaneGateway = new JScrollPane(displayGateway);
        scrollPaneGateway.setPreferredSize(new Dimension(200, 75));
        c.fill = GridBagConstraints.BOTH; // Fill entire cell.
        c.weighty = 1.0; // Button area and message area have equal height.
        c.gridwidth = GridBagConstraints.REMAINDER; // end of row
        gridbag.setConstraints(scrollPaneGateway, c);
        add(scrollPaneGateway);
        displayResource = new JTextArea();
        displayResource.setEditable(true);
        displayResource.setText("hahaha");
        scrollPaneResource = new JScrollPane(displayResource);
        scrollPaneResource.setPreferredSize(new Dimension(200, 75));
        c.fill = GridBagConstraints.BOTH; // Fill entire cell.
        c.weighty = 1.0; // Button area and message area have equal height.
        c.gridwidth = GridBagConstraints.REMAINDER; // end of row
        gridbag.setConstraints(scrollPaneResource, c);
        add(scrollPaneResource);
        mainPanel.revalidate(); // Make the button show up.


    } /*else if (REMOVE.equals(command)) {
      int lastIndex = buttonList.size() - 1;
      try {
          mainPanel.remove(displayResource);

        JButton nixedButton = buttonList.elementAt(lastIndex);
        mainPanel.remove(nixedButton);
 //       buttonList.removeElementAt(lastIndex);
        mainPanel.revalidate(); // Make the button disappear.
        mainPanel.repaint(); // Make the button disappear.
      } catch (ArrayIndexOutOfBoundsException exc) {
      }
    }*/ else if (CLEAR.equals(command)) {
        remove(displayResource);
        remove(displayGateway);
        remove(scrollPaneResource);
        remove(scrollPaneGateway);
        remove(clearButton);
        hello();
        inputArea.setText("");
        displayGateway.setText("");
        displayResource.setText("");
      mainPanel.revalidate(); // Make the button disappear.
      mainPanel.repaint(); // Make the button disappear.
    }
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
      hello();
  }
  public static void hello () {
        // Create and set up the window.
        JFrame frame = new JFrame("ContainerEventDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Create and set up the content pane.
        JComponent newContentPane = new ContainerEventDemo();
        newContentPane.setOpaque(true); // content panes must be opaque
        frame.setContentPane(newContentPane);
        // Display the window.
        frame.pack();
        frame.setVisible(true);

  }

  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}**

謝謝你的幫助。

“問題”是mainPanel 您似乎沒有在其中添加任何內容,但是在“切換”視圖時也不會刪除它,因此它仍然存在並占用空間。

我“假設”您正在使用它作為某種填充物,但是您似乎忘記了它的存在。

我的建議是停止像這樣“手動”操作UI,將“視圖”分成單獨的類,以便它們可以有重點的布局並彼此隔離地進行管理,並使用CardLayout在它們之間進行切換

更新

我可以預見一堆關於如何建立UI的陳述,而不是理解為什么以這種方式發生等...

基本上,您將使用c.gridwidth = GridBagConstraints.REMAINDER建立核心UI的布局。 好的,這很好。

但是,當您刪除所有其他組件時,這會將mainPanel推到頂部,並結合c.weighty = 1.0 ,使其想要占用其他組件剩下的剩余可用空間。

這基本上是您的核心問題。 因此,將視圖分為幾個單獨的類並作為“整體”進行管理,它將立即解決大多數關鍵問題

暫無
暫無

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

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