java jpanel.add_java – 尝试在按钮单击时在JPanel中添加动...

我试图将一个Graphics对象添加/绘制到现有的JPanel.我正在生成10个随机大小的初始Graphics对象并放置在面板中,但是想要一次添加额外的绘制对象,随机调整大小并放置像初始10.

目前,AddNewDrawItem类不呈现新的Graphics对象.

谢谢你的意见.

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

参与评论 您还未登录,请先 登录 后发表或查看评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:游动-白 设计师:我叫白小胖 返回首页

打赏作者

DanteXue

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值