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

本文介绍了一个使用Java Swing和AWT库创建的简单绘图应用示例。该应用能够在面板上随机生成不同颜色和大小的矩形,并提供按钮来添加新的图形元素。文章通过具体的代码实现了基本图形的绘制及动态更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我试图将一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值