a) Many GUI applications have metres that indicate the progress made so far towards completing an activity as a percentage of the anticipated total activity. Write a program to display a progress metre as follows. The metre 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%”. (Correct layout: 0.25P, Class extends JFrame: 0.25P, Class follows OOP principles: 0.25P, Global set-up in main method: 0.25P)2 b) Create 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%.怎么做?
时间: 2024-02-04 07:03:40 浏览: 105
C Programming
以下是实现上述功能的 Java 代码:
```java
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class ProgressMeter extends JFrame {
private JLabel[] steps;
private JLabel progressLabel;
private int progress;
public ProgressMeter() {
setTitle("Progress Meter");
setSize(200, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(11, 1));
// Create the steps labels
steps = new JLabel[10];
for (int i = 0; i < 10; i++) {
JLabel stepLabel = new JLabel((i + 1) * 10 + "%");
stepLabel.setForeground(Color.RED);
add(stepLabel);
steps[i] = stepLabel;
}
// Create the progress label
progressLabel = new JLabel(progress + "%");
progressLabel.setForeground(Color.BLACK);
add(progressLabel);
setVisible(true);
}
public void updateProgress() {
if (progress < 100) {
steps[progress / 10].setForeground(Color.GREEN);
progress += 10;
progressLabel.setText(progress + "%");
}
}
public static void main(String[] args) {
ProgressMeter meter = new ProgressMeter();
Scanner scanner = new Scanner(System.in);
while (meter.progress < 100) {
System.out.print("Press Enter to make progress: ");
scanner.nextLine();
meter.updateProgress();
}
}
}
```
这个程序使用了 Java 的 Swing 库创建了一个窗口,包含一个由 11 个标签组成的表,其中前 10 个标签表示进度的 10% 步骤,初始颜色为红色,最后一个标签用于显示剩余的活动量,初始值为 “0%”。程序的主要逻辑在 `updateProgress()` 方法中,它将更新进度,并将相应的标签从红色更改为绿色。在主方法中,我们使用 Scanner 对象读取用户的输入,并在每次输入时调用 `updateProgress()` 方法来更新进度。
阅读全文