java swing 应用程序 - 如何设置面板中组件的高度(和宽度)

标签 java swing

我正在编写一个 java swing 应用程序,我有一个初学者的问题。

下面的屏幕是应用程序中显示的 2 个屏幕之一。可以看到,它的顶部有一个用红圈圈起来的大空间。我无法摆脱它。我希望它非常短,以便“清除”按钮能够接触到框架的顶部。

我已经尝试了很多,但没有成功。有人可以帮忙吗?

enter image description here

这是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。您似乎没有向其中添加任何内容,但是当您“切换” View 时也没有删除它,因此它仍然存在并占用空间。

我“假设”您正在使用它作为某种填充物,但您似乎忘记了它的存在。

我的建议是停止像这样“手动”操作 UI,将您的“ View ”分成单独的类,以便它们可以有一个集中的布局并相互隔离管理,并使用 CardLayout在它们之间切换

已更新

我可以预见到一堆关于 UI 是如何建立的陈述,但不明白为什么会这样……

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

但是,当您删除所有其他组件时,这会将 mainPanel 推到顶部,与 c.weighty = 1.0 结合,使其想要占用剩余的可用空间其他组件留下的空间。

这基本上是你的核心问题。因此,将 View 分解为单独的类并将它们作为一个“整体”进行管理,它将立即解决大多数关键问题

关于java swing 应用程序 - 如何设置面板中组件的高度(和宽度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48856883/

相关文章:

java - REST如何返回接口(interface)列表

java - 在 Retrofit baseUrl 中使用模拟器 ip 地址 10.0.2.2

java - 油漆组件 : paint different geometric shapes after delay each time

java - JTableCell 中的图像图标

java - 当请求的页面或方法找不到时如何定义全局页面?

java - 遍历所有已安装应用程序的 AndroidManifest.xml 文件?

java - 在 swing 中显示 HTML5

java - 如何创建出现在程序最顶部的 Swing 菜单栏?

java - 为什么 java.io.File 没有实现 Autocloseable?

java - JTable:看不到列名