import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Pyramid extends JFrame implements ActionListener
{
private JPanel panel;
// private Random random;
private JTextField pyramidHeightField;
private JLabel pyramidHeightLabel;
private JButton buildPyramidButton;
public static void main (String[] args)
{
Pyramid frame = new Pyramid();
frame.setSize(400, 500);
frame.setTitle("Pyramid");
frame.createGUI();
frame.setVisible(true);
}
private void createGUI()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout() );
panel = new JPanel();
panel.setPreferredSize(new Dimension(400, 400));
panel.setBackground(Color.white);
window.add(panel);
pyramidHeightLabel = new JLabel("Enter Pyramid height from 1 to 100 ");
window.add(pyramidHeightLabel);
pyramidHeightField = new JTextField(10);
window.add(pyramidHeightField);
buildPyramidButton = new JButton("Build Pyramid");
window.add(buildPyramidButton);
buildPyramidButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
int pyramidHeight, brickSize, random;
int x = 0, y = 400, hLoop = 1, vLoop = 1, endWhile = 0;
String diagText1, diagText2, diagText3, diagString;
pyramidHeight = Integer.parseInt(pyramidHeightField.getText());
if (pyramidHeight < 1 || pyramidHeight > 100)
{
pyramidHeight = 50;
}
brickSize = 400 / pyramidHeight;
Graphics paper = panel.getGraphics();
//*********************************
paper.clearRect(0,0,400,400);
//*********************************
for (vLoop = 1; vLoop <= pyramidHeight; vLoop++)
{
y = y - brickSize;
diagText1 = (Integer.toString(vLoop));
diagText2 = (Integer.toString(x));
diagText3 = (Integer.toString(y));
endWhile = ((pyramidHeight + 1) - vLoop);
while (hLoop <= endWhile)
{
// paper.setColor(Color.yellow);
// paper.fillRect(x, y, brickSize, brickSize);
drawBrick(paper, x, y, brickSize);
// paper.setColor(Color.black);
// paper.drawRect(x, y, brickSize, brickSize);
x += brickSize;
hLoop++;
}
hLoop = 1;
// diagText1 = (Integer.toString(vLoop));
// diagText2 = (Integer.toString(x));
// diagText3 = (Integer.toString(y));
x = (brickSize / 2) * vLoop;
JOptionPane.showMessageDialog (null,
diagString = "vLoop = " + diagText1 + " x = " + diagText2 + " y = " + diagText3);
}
}
private void drawBrick(Graphics drawingArea, int xPos, int yPos, int size)
{
drawingArea.setColor(Color.yellow);
drawingArea.fillRect(xPos, yPos, size, size);
drawingArea.setColor(Color.black);
drawingArea.drawRect(xPos, yPos, size, size);
}
}