Use java to write a program to display a progress meter as follows. The meter consists of a windowCreate functionality to simulate steps of 10% progress. For this the user repeatedly presses return on the console inside Eclipse (use a Scanner object for this). Every time, the top-most red label is changed to green and the progress label value is incremented by 10 until that value is 100%. Make sure that no errors occur if the user tries to go past 100%. 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-13 15:00:58 浏览: 78
Sure, here's an example program in Java that implements the progress meter functionality you described:
```java
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.GridLayout;
public class ProgressMeter {
private static final int NUM_STEPS = 10;
private static final String[] STEP_LABELS = {"0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"};
private static final Color RED = Color.RED;
private static final Color GREEN = Color.GREEN;
private JFrame frame;
private JLabel[] stepLabels;
private JLabel progressLabel;
private int currentStep;
public ProgressMeter() {
frame = new JFrame("Progress Meter");
JPanel panel = new JPanel(new GridLayout(NUM_STEPS + 1, 1));
stepLabels = new JLabel[NUM_STEPS];
for (int i = 0; i < NUM_STEPS; i++) {
JLabel label = new JLabel(STEP_LABELS[i], JLabel.CENTER);
label.setForeground(RED);
panel.add(label);
stepLabels[i] = label;
}
progressLabel = new JLabel("0%", JLabel.CENTER);
panel.add(progressLabel);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
currentStep = 0;
}
public void updateProgress() {
if (currentStep < NUM_STEPS) {
stepLabels[currentStep].setForeground(GREEN);
currentStep++;
progressLabel.setText(currentStep * 10 + "%");
}
}
public static void main(String[] args) {
ProgressMeter meter = new ProgressMeter();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Press enter to simulate progress...");
scanner.nextLine();
meter.updateProgress();
}
}
}
```
This program creates a `ProgressMeter` class that encapsulates the progress meter GUI and functionality. The constructor initializes the GUI with 11 `JLabel` components arranged in a `GridLayout`, with the first 10 labels representing the progress steps and the bottom label representing the progress percentage. The `updateProgress` method updates the GUI by changing the color of the current step label to green, incrementing the current step count, and updating the progress label text. The `main` method creates a new `ProgressMeter` instance and repeatedly waits for the user to press enter before calling the `updateProgress` method to simulate progress.
阅读全文