Use java to write a program to display a progress meter . The meter consists of a window with a column of 11 labels. The first 10 labels indicate progress steps of 10% and are initially red. The bottom label shows the amount of activity remaining as a textual percentage, and is initially set to “0%”.
时间: 2024-02-07 18:04:15 浏览: 76
显示百分比的进度条
Certainly! Here's a Java program that creates a progress meter as described:
```java
import javax.swing.*;
import java.awt.*;
public class ProgressMeter extends JFrame {
private JLabel[] progressSteps;
private JLabel remainingLabel;
public ProgressMeter() {
super("Progress Meter");
setSize(200, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the progress step labels
progressSteps = new JLabel[10];
for (int i = 0; i < progressSteps.length; i++) {
progressSteps[i] = new JLabel();
progressSteps[i].setPreferredSize(new Dimension(100, 20));
progressSteps[i].setOpaque(true);
progressSteps[i].setBackground(Color.RED);
add(progressSteps[i]);
}
// create the remaining activity label
remainingLabel = new JLabel("0%");
remainingLabel.setPreferredSize(new Dimension(100, 20));
add(remainingLabel, BorderLayout.SOUTH);
setVisible(true);
}
public void updateProgress(int percentComplete) {
// update the progress step labels
int numProgressSteps = progressSteps.length;
int numCompletedSteps = (int) Math.ceil(percentComplete * numProgressSteps / 100.0);
for (int i = 0; i < numCompletedSteps; i++) {
progressSteps[i].setBackground(Color.GREEN);
}
// update the remaining activity label
remainingLabel.setText(percentComplete + "%");
}
public static void main(String[] args) throws InterruptedException {
ProgressMeter progressMeter = new ProgressMeter();
// simulate progress
int percentComplete = 0;
while (percentComplete <= 100) {
progressMeter.updateProgress(percentComplete);
Thread.sleep(1000);
percentComplete += 10;
}
}
}
```
This program creates a `JFrame` with a column of 10 `JLabel`s representing the progress steps, and a bottom `JLabel` showing the remaining activity as a percentage. The `updateProgress` method updates the progress step labels and remaining activity label based on the given percentage. The `main` method simulates progress by updating the progress meter every second for 10 iterations, with each iteration representing 10% progress.
阅读全文