[英]Layout for displaying panels dynamically with scroll bar
In java, I have been trying to create a panel that can accept other panels with a scroll bar. 在java中,我一直在尝试创建一个可以接受带滚动条的其他面板的面板。
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. 我尝试使用gridlayout,这很好用,除了我只添加几个面板的事实,它增长这些面板以适应父面板的大小。
I tried using flowlayout, but this makes the panels flow horizontally as there is a scroll bar. 我尝试使用flowlayout,但这会使面板水平流动,因为有一个滚动条。
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). 我如何制作它以便我可以从顶部开始向父面板添加面板并使它们始终具有相同的尺寸(或它们的首选尺寸)。
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.
在它上面调用repaint()不起作用。
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();
}
});
}
}
Assuming JScrollPane
, see Sizing a Scroll Pane . 假设
JScrollPane
,请参阅调整滚动窗格大小 。 For convenience, Scrollable
clients such as JTable
offer setPreferredScrollableViewportSize()
, but you can always set the viewport's size explicitly. 为方便起见,可
Scrollable
客户端(如JTable
提供setPreferredScrollableViewportSize()
,但您始终可以显式设置视口的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.