use Java swing, not the ACM libraries to solve the following problems. Draw a py
ID: 3731626 • Letter: U
Question
use Java swing, not the ACM libraries to solve the following problems.
Draw a pyramid. A stack of blocks should fit “exactly” into a centered rectangle that is 80% of the window’s width and height. Use a constant to indicates the number of rows to be placed in the rectangle. Unlike the book’s version, the width and height of each brick are directly related to the current size of the window. You may start at either the top or bottom of the pyramid – it can be built in either direction. Make the background white, the background centered rectangle blue and the bricks orange with red outlines.
Explanation / Answer
import java.awt.*;
import javax.swing.*;
public class Tester {
public static void main(String... args) {
int rows = 15;
int width = 30;
int height = 10;
SwingUtilities.invokeLater( () -> new Tester(width, height, rows));
}
public Tester(int w, int h, int rows) {
JPanel panel = new JPanel(new GridLayout(0, 1));
for (int i = 1; i <= rows; i++) panel.add(createPanel(i, w, h));
JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel(int labels, int width, int height) {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
panel.setBackground(Color.BLUE);
for (int i = 0; i < labels; i++) panel.add(createLabel(width, height));
return panel;
}
private JLabel createLabel(int width, int height) {
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(width, height));
label.setOpaque(true);
label.setBackground(Color.ORANGE);
label.setBorder(BorderFactory.createLineBorder(Color.RED));
return label;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.