在阅读了很多 java swing 文章后,我几乎失明了,仍然无法让面板工作。
当我添加 2 个 JLabel 时,它们很好地向左对齐,由 EmptyBorder 定义 5px 填充,就像我希望它们那样。
我发现在为填充添加带有额外边框的 ProgressBar 后,无法按预期工作,添加了 1 个面板,我在其中添加了 ProgressBar。进展看起来不错,但我所有的标签都被取代了。
最后它看起来像这样(红色背景用于调试,看看 JPanel 是如何绘制的):
问题1:如何解决这个问题?
问题2:摆动将面板与其他面板一起放置在其他面板内部以获得我想要的格式是否是标准方法?
来源:
public class AppInitProgressDialog {
private static final int VIEW_PADDING_VAL = 5;
private static final Border viewPaddingBorder = new EmptyBorder( VIEW_PADDING_VAL, VIEW_PADDING_VAL, VIEW_PADDING_VAL, VIEW_PADDING_VAL );
private JPanel view; // Dialog view
private JPanel panel;
private JPanel progressPanel;
private JLabel title;
private JLabel progressDesc;
private JProgressBar progressBar;
private void initPanel( int w, int h ) {
view = new JPanel();
view.setBorder( BorderFactory.createRaisedSoftBevelBorder() );
view.setBackground( Color.LIGHT_GRAY );
view.setSize( w, h );
view.setLayout( new BorderLayout() );
panel = new JPanel();
panel.setBorder( viewPaddingBorder );
panel.setLayout( new BoxLayout(panel, BoxLayout.PAGE_AXIS) );
//panel.setLayout( new SpringLayout() );
panel.setOpaque( false );
JFrame parent = AppContext.getMe().getAppWindow().getFrame();
int posx = (parent.getWidth() - w)/2;
int posy = (parent.getHeight() - h)/2;
view.add( panel, BorderLayout.CENTER );
view.setLocation( posx, posy );
}
private void initTitle() {
title = new JLabel( "Progress title" );
title.setAlignmentX( JComponent.LEFT_ALIGNMENT );
panel.add(title);
}
private void initProgress() {
progressPanel = new JPanel( new BorderLayout() );
progressPanel.setBackground( Color.LIGHT_GRAY );
progressPanel.setBorder( new EmptyBorder( 15, 30, 15, 30) );
progressPanel.setBackground( Color.RED );
progressBar = new JProgressBar(0, 10000);
progressBar.setStringPainted(true);
progressBar.setAlignmentX( JComponent.LEFT_ALIGNMENT );
progressPanel.add(progressBar);
panel.add( progressPanel );
progressDesc = new JLabel( "Progress description" );
panel.add(progressDesc);
}
public AppInitProgressDialog() {
initPanel( 400, 100 );
initTitle();
initProgress();
}
public JComponent getView() {
return view;
}
}