gpt4 book ai didi

java - 如何调整 JScrollPane 中绑定(bind)的 JTextPane 组件的大小

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:29 25 4
gpt4 key购买 nike

在带有 GridBagLayout 的 JPanel 中,我创建了与 JscrollPane 组件绑定(bind)的 JTextPane 组件列表。不幸的是,组件的大小似乎是固定的:当我减小 JFrame 大小时,我想强制组件动态地适应 JFrame 的大小。例如,当主窗口大小减小到 20 像素时,我希望组件的大小也更改为 20 像素。

这是我的代码:

import java.awt.*;
import javax.swing.*;

public class ScrollbarTest {

private JFrame frame;
private JPanel panel;
private JScrollPane [] scrollpane = new JScrollPane[4];
private JTextArea [] textPane = new JTextArea[4];
private JScrollPane scrollbar;


ScrollbarTest() {
//initialize jtextarea
for(int i=0;i<textPane.length;i++) {
textPane[i]=new JTextArea();
textPane[i].setText("xxxx xxxx xxxx xxxx xxxx xxxx xxxx | ");
scrollpane[i] = new JScrollPane(textPane[i]);
scrollpane[i].setMinimumSize(new Dimension(100,100));
}

panel = new JPanel();
frame = new JFrame();

createList(panel);
scrollbar = new JScrollPane(panel);

frame.add(scrollbar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(new Dimension(400,400));
} //constructor

//method to easily add components to GridBags
static void addComponent(JPanel panel,
GridBagLayout gbl,
Component c,
int x, int y,
int width, int height,
double weightx, double weighty) {

GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = width; gbc.gridheight = height;
gbc.weightx = weightx; gbc.weighty = weighty;
gbl.setConstraints( c, gbc );
panel.add( c );
}//addComponent

public void createList(JPanel panel) {
//setting layout: "GridBagLayout"
GridBagLayout gbl = new GridBagLayout();
panel.setLayout(gbl);

//put created components to the gridbags of gridbaglayout
// x y w h wx wy
addComponent( panel, gbl, scrollpane[0] , 0, 1, 1, 1, 1 ,1 );
addComponent( panel, gbl, scrollpane[1] , 0, 2, 1, 1, 1 ,1 );
addComponent( panel, gbl, scrollpane[2] , 1, 1, 1, 1, 1 ,1 );
addComponent( panel, gbl, scrollpane[3] , 1, 2, 1, 1, 1 ,1 );
} //createList

public static void main (String[] args) {
new ScrollbarTest();
} //main

} //end of class

如何动态调整组件的大小?

非常感谢!

最佳答案

使用GridBagLayout时,您必须始终关注子组件的preferredSize。添加类似内容

textPane[i].setPreferredSize(new Dimension(10, 15));

到构造函数中的 for 循环。

此外,您还将 AWT 与 Swing 混合在一起 - 使用更轻量级的 JComponent 而不是 Component

关于java - 如何调整 JScrollPane 中绑定(bind)的 JTextPane 组件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786605/

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