[英]Show progress bar after an action
我想在一些動作后顯示進度條。 實際的代碼是復雜的,但我准備了一個樣本,我希望進度條填充框架的寬度,但我希望它具有特定/正常高度,而不是填充框架。 我怎樣才能做到這一點? 如果框架的布局沒有改變( BorderLayout
)會更好,因為它可能會破壞我實際代碼上的其他內容。 如果這無法避免,那么一定要改變它,我會看到它的結果。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
public class SwingControlDemo
{
public static int progress = 0;
private JFrame mainFrame;
public SwingControlDemo()
{
prepareGUI();
}
public static void main(String[] args)
throws Exception
{
//BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.osLookAndFeelDecorated;
// org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
new SwingControlDemo();
}
private void prepareGUI()
{
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new BorderLayout());
mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
showProgressBarDemo();
}
});
mainFrame.add(new JLabel("mplaaaaaaaaaaaaaaaaaaa"), BorderLayout.CENTER);
mainFrame.add(startButton, BorderLayout.SOUTH);
mainFrame.setVisible(true);
}
private void showProgressBarDemo()
{
final JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BorderLayout());
controlPanel.add(progressBar, BorderLayout.CENTER);
mainFrame.add(controlPanel);
mainFrame.revalidate();
mainFrame.repaint();
final Timer timer = new Timer(1000, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
progress++;
System.out.println(String.format("Completed %d%% of task.\n", progress));
progressBar.setValue(progress);
progressBar.setString(String.format("Completed %d%% of task.\n", progress));
}
});
timer.start();
}
}
但我希望它具有特定/正常高度
如果您希望它顯示在preferredSize
不是將其添加到使用FlowLayout的JPanel,然后使用JPanel將該JPanel添加到BorderLayout(如果您仍希望使用BorderLayout)。 請注意我自己,我會使用CardLayout交換組件。
實際的代碼是復雜的,但我准備了一個樣本,我希望進度條填充框架的寬度,但我希望它具有特定/正常高度,而不是填充框架。
例如,您可以使用GridBagLayout
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
controlPanel.add(progressBar, gbc);
有關更多詳細信息,請參見如何使用GridBagLayout
您可以考慮利用框架的“玻璃窗格”,這將允許您將內容放在contentPane
的頂部,但不會直接影響它。 如果您向其注冊了MouseListener
,您甚至可以阻止鼠標事件進入contentPane
本身。
有關更多詳細信息,請參閱如何使用根窗格
另外,根據您的需求,您也許能夠使用ProgressMonitor
, 例如
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.