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

时间:2018-02-18 21:40:02

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

“问题”是mainPanel。您似乎没有添加任何内容,但是当您“切换”视图时,它们都没有删除它,因此它仍然存在并占用空间。

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

我的建议是停止“手动”操作这样的UI,将你的“视图”分成单独的类,这样他们就可以拥有一个专注的布局,并相互隔离地管理,并使用CardLayout来在它们之间切换

更新

我可以预见一堆关于如何建立用户界面的陈述,而不是理解为什么会这样发生......等等。

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

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

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