Write code that uses a JList to hold three shape names – Rectangle, Square, and
ID: 3817888 • Letter: W
Question
Write code that uses a JList to hold three shape names – Rectangle, Square, and Circle, as well as an open area to the left of the JList. When a user clicks on the GUI to the left of the JList, the code should draw a shape of the chosen type (from the list) in that position. The dimensions used should be random on each click, between 50 and 300 pixels wide. When a new shape is drawn, the old one should disappear. Below is an example of the GUI, but looking close enough is good enough:
Simple Drawing GUI Rectangle Square ircleExplanation / Answer
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DisposeShapes{
JLabel label = new JLabel();
JButton addRectangle;
JButton addSquare;
JButton addCircle;
Rectangle rectangle;
Graphics2D g2;
JPanel panel;
public void paintComponent(Graphics g)
{
g2 = (Graphics2D)g;
rectangle = new Rectangle(100,100,100,100);
}
public DisposeShapes()
{
JFrame frame = new JFrame("Dispose shapes");
panel = new JPanel();
addRectangle = new JButton("Add Rectangle");
addRectangle.setSize(50, 100);
addRectangle.addActionListener(new ButtonListener());
addSquare = new JButton("Add Square");
addSquare.setSize(50,100);
addSquare.addActionListener(new ButtonListener());
addCircle = new JButton("Add Circle");
addCircle.setSize(50,100);
addCircle.addActionListener(new ButtonListener());
panel.setLayout(new FlowLayout());
panel.add(addRectangle);
panel.add(addSquare);
panel.add(addCircle);
panel.add(label);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == addRectangle)
{
}
else if (e.getSource() == addSquare)
{
}
else if(e.getSource() == addCircle)
{
}
}
}
public static void main(String[] args)
{
DisposeShapes disposeShapes = new DisposeShapes();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.