问题描述
在Java中,我一直在尝试创建一个可以接受带有滚动条的其他面板的面板.
In java, I have been trying to create a panel that can accept other panels with a scroll bar.
我尝试使用gridlayout,并且效果很好,除了以下事实:如果我仅添加几个面板,它将使这些面板增长到适合父面板的大小.
I tried using gridlayout, and this works fine, except for the fact that if I only add a few panels, it grows those panels to fit the size of the parent panel.
我尝试使用flowlayout,但是由于有滚动条,这会使面板水平流动.
I tried using flowlayout, but this makes the panels flow horizontally as there is a scroll bar.
如何做到这一点,以便可以从顶部开始将面板添加到父面板,并使它们始终具有相同的大小(或它们的首选大小).
How do I make it so I can add panels to the parent panel starting at the top and make them always the same size(or their preferred size).
此外,当我在事件发生后将面板添加到父面板时,直到我移动或调整表单大小后才会出现.我该如何重新粉刷?对其调用repaint()无效.
Also, when I add panels to the parent panel after an event, they do not appear until after I move or resize the form. How do I make it repaint? calling repaint() on it did not work.
推荐答案
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/** This lays out components in a column that is constrained to the
top of an area, like the entries in a list or table. It uses a GridLayout
for the main components, thus ensuring they are each of the same size.
For variable height components, a BoxLayout would be better. */
class ConstrainedGrid {
ConstrainedGrid() {
final JPanel gui = new JPanel(new BorderLayout(5,5));
gui.setBorder(new EmptyBorder(3,3,3,3));
gui.setBackground(Color.red);
JPanel scrollPanel = new JPanel(new BorderLayout(2,2));
scrollPanel.setBackground(Color.green);
scrollPanel.add(new JLabel("Center"), BorderLayout.CENTER);
gui.add(new JScrollPane(scrollPanel), BorderLayout.CENTER);
final JPanel componentPanel = new JPanel(new GridLayout(0,1,3,3));
componentPanel.setBackground(Color.orange);
scrollPanel.add(componentPanel, BorderLayout.NORTH);
JButton add = new JButton("Add");
gui.add(add, BorderLayout.NORTH);
add.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
componentPanel.add(new JTextField());
gui.validate();
}
});
Dimension d = gui.getPreferredSize();
d = new Dimension(d.width, d.height+100);
gui.setPreferredSize(d);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ConstrainedGrid cg = new ConstrainedGrid();
}
});
}
}
这篇关于使用滚动条动态显示面板的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!