简体   繁体   English

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

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

I'm writing a java swing application and I have a beginner's question, please. 我正在编写一个Java swing应用程序,请问一个初学者的问题。

The screen below is one of the 2 screens shown in the application. 下面的屏幕是应用程序中显示的两个屏幕之一。 As you can see, there is a big space circled in red on the top of it. 如您所见,在其顶部有一个大的圆圈,上面用红色圈出。 I can't get rid of it. 我不能摆脱它。 I'd like it to be very short so that the "clear" button would touch the top of the frame. 我希望它很短,以便“清除”按钮可以触及框架的顶部。

I've tried a lot, but it didn't work. 我已经尝试了很多,但是没有用。 Can someone help? 有人可以帮忙吗?

在此处输入图片说明

This is the java code: 这是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();
      }
    });
  }
}**

Thanks for any help. 谢谢你的帮助。

The "problem" is mainPanel . “问题”是mainPanel You don't seem to be adding anything to it, but neither are you removing it when you "switch" views, so it remains and takes up space. 您似乎没有在其中添加任何内容,但是在“切换”视图时也不会删除它,因此它仍然存在并占用空间。

I'm "assuming" you're using it as a filler of some kind, but you seem to have forget that it's there. 我“假设”您正在使用它作为某种填充物,但是您似乎忘记了它的存在。

My recommendation is to stop "manually" manipulating the UI like this, seperate your "views" into individual classes, so that they can have a focused layout and managed in isolation from each other and use a CardLayout to switch between them 我的建议是停止像这样“手动”操作UI,将“视图”分成单独的类,以便它们可以有重点的布局并彼此隔离地进行管理,并使用CardLayout在它们之间进行切换

Updated 更新

I can foresee a bunch of statements about how the UI was established and not understanding why this happening this way etc... 我可以预见一堆关于如何建立UI的陈述,而不是理解为什么以这种方式发生等...

Basically, you're establishing the layout of the core UI using c.gridwidth = GridBagConstraints.REMAINDER . 基本上,您将使用c.gridwidth = GridBagConstraints.REMAINDER建立核心UI的布局。 Okay this is fine. 好的,这很好。

But, when you remove all the other components, this pushes mainPanel to the top, combined with c.weighty = 1.0 , makes it want to occupy the remaining available space left over by the other components. 但是,当您删除所有其他组件时,这会将mainPanel推到顶部,并结合c.weighty = 1.0 ,使其想要占用其他组件剩下的剩余可用空间。

This is basically you core problem. 这基本上是您的核心问题。 So, break down the view's into separate classes and manage them as a "whole", it will solve most of the key problems immediately 因此,将视图分为几个单独的类并作为“整体”进行管理,它将立即解决大多数关键问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM