调整JPanel的大小

时间:2013-06-18 06:06:16

标签: java swing resize jpanel

我有关于调整JPanel大小的问题。

我有一个JSlider,可以动态调整JPanel的大小。当我更改Height()的值JPanel时,面板的大小会从上到下减小或增加,效果为curtain,但当我更改值Width()时,它不会影响curtain,Panel会从中心调整大小,同时减少或增加双方。

亲爱的专家,请告诉我如何从左到右或向后调整面板宽度?

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class Swipe extends JFrame {

    static JPanel panel = null;
    static JPanel panel2 = null;
    static JPanel panel3 = null;
    static JLabel label1 = null;
    static JLabel label2 = null;
    static JSlider slider = null;
    static JToolBar bar = null;
    ImageIcon img;

    public Swipe(ImageIcon img1, ImageIcon img2) {
        JFrame frame = new JFrame();
        bar = new JToolBar();
        bar.add(slider(img1));
        frame.add(bar, BorderLayout.NORTH);
        label1 = new JLabel();
        label1.setLayout(null);
        label1.setMaximumSize(new Dimension(img2.getIconWidth(), img2.getIconHeight()));
        label1.setIcon(img1);

        panel = new JPanel();
        panel.add(label1, new GridBagConstraints());

        label2 = new JLabel();
        label2.setPreferredSize(new Dimension(img2.getIconWidth(), img2.getIconHeight() + 20));
        label2.setMaximumSize(new Dimension(img2.getIconWidth(), img2.getIconHeight()));
        label2.setIcon(img2);
        frame.setLayout(new FlowLayout());
        label2.setLayout(new FlowLayout());
        label2.add(panel);
        frame.add(label2);
        frame.setSize(img2.getIconWidth() + 50, img2.getIconHeight() + 50);
        frame.setVisible(true);
        frame.pack();
    }

    public JSlider slider(final ImageIcon im) {
        slider = new JSlider();
        slider.setMaximum(im.getIconHeight());
        slider.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                // TODO Auto-generated method stub
                int value = slider.getValue();
                //panel.setPreferredSize(new Dimension(im.getIconWidth(),value));
                panel.setPreferredSize(new Dimension(value, im.getIconHeight()));
                panel.repaint();
                panel.updateUI();
            }
        });
        return slider;
    }
}

1 个答案:

答案 0 :(得分:1)

虽然肯定可以按照您的方式行事,但使用JSplitPane实现更简单,更容易实现我认为可比较的目标:

new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
  componentOnLeft, Component componentOnRight);
如果您需要以编程方式调整两个组件的大小,

JSplitPane也有setDividerLocation个方法(一个绝对,一个比例)。