Use java to write a program to display a progress meter as follows. 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 10:04:15 浏览: 82
Sure, here's a Java program that displays a progress meter as described:
```java
import javax.swing.*;
import java.awt.*;
public class ProgressMeter extends JFrame {
private JLabel[] steps;
private JLabel remaining;
public ProgressMeter() {
setTitle("Progress Meter");
setSize(200, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the labels for the progress steps
steps = new JLabel[10];
for (int i = 0; i < 10; i++) {
steps[i] = new JLabel(" ");
steps[i].setPreferredSize(new Dimension(100, 20));
steps[i].setOpaque(true);
steps[i].setBackground(Color.RED);
add(steps[i]);
}
// create the label for remaining activity
remaining = new JLabel("0%");
remaining.setPreferredSize(new Dimension(100, 20));
add(remaining, BorderLayout.SOUTH);
setVisible(true);
}
public void updateProgress(int percent) {
// update the progress steps
int stepsCompleted = percent / 10;
for (int i = 0; i < stepsCompleted; i++) {
steps[i].setBackground(Color.GREEN);
}
// update the remaining activity label
remaining.setText(percent + "%");
}
public static void main(String[] args) {
ProgressMeter meter = new ProgressMeter();
// simulate progress by updating the meter every second
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
meter.updateProgress(i);
}
}
}
```
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 steps and remaining activity label based on the given percentage. To simulate progress, the `main` method updates the meter every second for 100 seconds.
阅读全文