62,635
社区成员




import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorRectPanel extends JPanel
{
public ColorRectPanel()
{
super();
setLayout(null); //用绝对布局会更简单点
}
public void addPanel(final int x, final int y, final int width, final int height, final Color color)
{
Panel panel = new Panel();
panel.setBackground(color);
panel.setBounds(x, y, width, height);
panel.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent event)
{
//点击的事件,我只打印了该矩形的信息
System.out.println("x:" + x + " y:" + y + " width:" + width + " height:" + height + " color:" + color);
}
});
add(panel);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
ColorRectPanel panel = new ColorRectPanel();
frame.add(panel);
panel.addPanel(0, 0, 200, 200, Color.BLUE);
panel.addPanel(100, 100, 200, 200, Color.GREEN);
frame.setSize(800, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ColorRectsPanel extends JPanel
{
private ArrayList<ColorRect> colorRects = new ArrayList<ColorRect>(); //用于存储矩形
public ColorRectsPanel()
{
super();
}
//定义添加矩形的方法
public void addRect(int x, int y, int width, int height, Color color)
{
ColorRect colorRect = new ColorRect();
colorRect.x = x;
colorRect.y = y;
colorRect.width = width;
colorRect.height = height;
colorRect.color = color;
colorRects.add(colorRect);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (ColorRect colorRect : colorRects) //画矩形
{
g.setColor(colorRect.color);
g.fillRect(colorRect.x, colorRect.y, colorRect.width, colorRect.height);
}
}
//定义一个数据结构
private class ColorRect
{
public int x;
public int y;
public int width;
public int height;
public Color color;
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
ColorRectsPanel panel = new ColorRectsPanel();
frame.add(panel);
//在panel中添加矩形
panel.addRect(0, 0, 200, 200, Color.BLUE);
panel.addRect(100, 100, 200, 200, Color.GREEN);
frame.setSize(800, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}