3

我有 10 个 JProgressbar,我试图将所有内容放在相同的位置,以便它看起来像目标中所示,但是当我按照它运行时,如失败部分所示。

在此处输入图像描述

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.*;

public class YumYumYum {

  private static JFrame f = new JFrame();
  private static JPanel panelFirst;

  public JProgressBar createJP(int input) {
    JProgressBar jp = new JProgressBar(JProgressBar.VERTICAL);
    jp.setPreferredSize(new Dimension(10, input));    
    return jp;
  }

  public YumYumYum() {
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.setLayout(new FlowLayout());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);

    // Main Menu
    panelFirst = new JPanel();        
    panelFirst.setBackground(Color.BLACK);    
    panelFirst.setLayout(new FlowLayout(FlowLayout.LEFT, 5,30));    
    panelFirst.setVisible(true);

    panelFirst.add(createJP(10));
    panelFirst.add(createJP(20));
    panelFirst.add(createJP(30));
    panelFirst.add(createJP(40));
    panelFirst.add(createJP(50));
    panelFirst.add(createJP(60));
    panelFirst.add(createJP(70));
    panelFirst.add(createJP(80));
    panelFirst.add(createJP(90));
    panelFirst.add(createJP(100));

    f.getContentPane().add(panelFirst);    
    f.pack();
    f.setVisible(true);

  }

  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        YumYumYum s = new YumYumYum();
      }
    });
  }

}
4

2 回答 2

1
  public JProgressBar createJP(int input) {
    JProgressBar jp = new JProgressBar(JProgressBar.VERTICAL, 0, 100);
    //jp.setPreferredSize(new Dimension(10, 100));
    //Why do you use PreferedSize if you want the size to be fixed?
    jp.setSize(new Dimension(10, 100));
    jp.setValue(input);  
    jp.setBackground(Color.BLACK);
    setBorderPainted(false);  
    return jp;
  }
于 2012-07-18T11:48:11.993 回答
0

您可以使用更灵活的 LayoutManager,例如MigLayout或 GridBagLayout。

这给了我(大致)想要的结果:

MigLayout mig = new MigLayout(null, null, "[align bottom]");
getContentPane().setLayout(mig);
for (int i = 1; i <= 10; i++) {
    getContentPane().add(createJP(i*10));
}
于 2012-07-18T12:14:14.157 回答