java swing jScrollpane删除多余的空间

时间:2017-07-01 21:57:38

标签: java swing jscrollpane

我今天正在使用JScrollPane,这是我到目前为止所做的事情

package it.polimi.ingsw.ps11.view.graphicView;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class TestIt2 extends JPanel {
   private static final Dimension BUTTON_SIZE = new Dimension(170, 150);
   private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
   private JPanel buttonPanel = new JPanel();

   public TestIt2() {
       buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
      JPanel holderPanel = new JPanel(new BorderLayout());
      holderPanel.add(buttonPanel, BorderLayout.NORTH);
      holderPanel.add(Box.createGlue(), BorderLayout.CENTER);

      setLayout(new BorderLayout());
      add(new JScrollPane(holderPanel,
              JScrollPane.VERTICAL_SCROLLBAR_NEVER,
              JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS), BorderLayout.CENTER);
      createButton();
   }

   public class addButton implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        createButton();     
    }
   }

   protected void createButton() {
      JButton button = new JButton("click me");
      button.addActionListener(new addButton());
      button.setPreferredSize(BUTTON_SIZE);
      buttonPanel.add(button);
      revalidate();
      repaint();
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(screen.width / 10 * 2,
            screen.height / 10 * 2);
   }

   private static void createAndShowGui() {
      TestIt2 mainPanel = new TestIt2();

      JFrame frame = new JFrame("TestIt2");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}`

问题是,滚动窗格在我创建的按钮右侧增加了很多空间,即使还有空间。 如何修改我的代码,以便它不会占用所有可用空间,而是我的最后一个按钮就在scrollPane的边框上,而每个新按钮只占用它所需的空间?谢谢你们所有人

0 个答案:

没有答案