gpt4 book ai didi

java - 调整 JPanel 大小

转载 作者:行者123 更新时间:2023-12-01 14:26:14 26 4
gpt4 key购买 nike

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

我有一个 JSlider,它可以动态调整 JPanel 的大小。当我更改JPanel的值Height()时,面板的大小从上到下减小或增大,效果与窗帘一样,但是当我更改值 Width() 时,它不会影响 curtain,面板从中心调整大小,并同时减小或增大两侧。

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

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;
}
}

最佳答案

虽然肯定可以按照您的方式进行,但它更简单、更容易使用 JSplitPane实现我认为类似的目标:

new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
componentOnLeft, Component componentOnRight);

JSplitPane 还具有 setDividerLocation方法(一种绝对,一种比例)如果您需要以编程方式调整两个组件的大小。

关于java - 调整 JPanel 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17161603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com