I am trying to add / draw a separate Graphics object to an existing JPanel. I generate 10 initial graphic objects randomly and place them on the panel, but I would like to add additional drawn objects once, a random size and place them as initial 10.
The AddNewDrawItem class does not currently create a new Graphics object.
Thanks for the input.
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; public class Painter{ private DrawingPanel dp = new DrawingPanel(); //constructor public Painter(){ buildGUI(); } private void buildGUI(){ JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.setTitle("Paint drawing demonstration"); JPanel headerPanel = new JPanel(); headerPanel.add(new JLabel("The drawing panel is below")); JButton addNew = new JButton("Add New Graphic"); addNew.addActionListener(new addNewClickHandler()); headerPanel.add(addNew); frame.add(BorderLayout.NORTH,headerPanel); frame.add(BorderLayout.SOUTH,this.dp); frame.pack(); frame.setVisible(true); } class DrawingPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); this.setBackground(Color.white); int x, posx, posy, width, height; for(x=0;x<=10;x++){ //even number differentiation if(x % 2 == 0){ g.setColor(Color.red); }else{ g.setColor(Color.blue); } Random rand = new Random(); posx = rand.nextInt(300); posy = rand.nextInt(300); width = rand.nextInt(40); height = rand.nextInt(40); //System.out.println("the ran x pos is: " + posx); g.fillRect(posx, posy, width, height); }//end for }//end paintComponent public Dimension getPreferredSize() { return new Dimension(400,400); } }// end DrawingPanel private class addNewClickHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ System.out.print("in addNew_click_handler click handler");//trace debug AddNewDrawItem newItem = new AddNewDrawItem(); newItem.repaint(); System.out.print("after repaint() in addNew_click_handler click handler");//trace debug } } class AddNewDrawItem extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); this.setBackground(Color.white); int posx, posy, width, height; Random rand = new Random(); posx = rand.nextInt(300); posy = rand.nextInt(300); width = rand.nextInt(40); height = rand.nextInt(40); g.setColor(Color.cyan); g.fillRect(posx, posy, width, height); }//end paintComponent }//end AddNewDrawItem public static void main(String args[]){ new Painter(); } }//end class Painter
source share