如题。
界面的上面是一个JPanel,用来放一个文本框等等,下面的全部区域就用来显示矩形图。下面也是个JPanel,可是如果下面JPanel没有指定布局管理器时,加入的矩形JPanel就看不到,所以我就加了个GridLayout,就可以看到矩形了,可是矩形所在的坐标与我指定的不一样。
具体怎么搞 ?swing头疼,求解!
界面的上面是一个JPanel,用来放一个文本框等等,下面的全部区域就用来显示矩形图。下面也是个JPanel,可是如果下面JPanel没有指定布局管理器时,加入的矩形JPanel就看不到,所以我就加了个GridLayout,就可以看到矩形了,可是矩形所在的坐标与我指定的不一样。
具体怎么搞 ?swing头疼,求解!
Class C extends JComponent {
int x,y;
Color bgc,fontc;
C(int m,int n,Color c0,Color,c1){
x=m;y=n;bgc=c0;fontc=c1;
}
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setColor(bgc);
g2.fillRect(x,y,150,150);
}
}
可能是因为后面的JPanel覆盖了前面的JPanel,导致只能显示一个矩形,其实你可以在JPanel里面定义一个方法用来添加矩形,然后在paintComponet方法中将这些矩形都打印出来
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);
}
}
可以用(getWidth(), getHeight());
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);
}
}