有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

下面的屏幕是应用程序中显示的两个屏幕之一。如你所见,它的顶部有一个红色圆圈的大空间。我无法摆脱它。我希望它很短,这样“清除”按钮就可以接触到框架的顶部

我试了很多,但都没用。有人能帮忙吗

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();
      }
    });
  }
}**

谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    “问题”是mainPanel。您似乎没有向它添加任何内容,但在“切换”视图时也没有删除它,因此它会保留并占用空间

    我“假设”你用它作为某种填充物,但你似乎忘记了它就在那里

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

    更新

    我可以预见一大堆关于用户界面是如何建立的,而不理解为什么会发生这种情况等等

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

    但是,当您删除所有其他组件时,这会将mainPanel推到顶部,再加上c.weighty = 1.0,使它想要占用其他组件剩余的可用空间

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