【发布时间】:2015-03-07 09:16:07
【问题描述】:
我在使用矩形时遇到了一些问题
这里是我的代码:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class square
{
JFrame fr=new JFrame("square");
Random acak=new Random();
JScrollPane sc;
int tinggi,lebar;
JTabbedPane tab=new JTabbedPane();
square()
{
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLocation(0,0);
fr.setExtendedState(JFrame.MAXIMIZED_BOTH);
fr.setLayout(new GridLayout(1,1));
tab.addTab("Panel1",new panel1());
tab.addTab("Panel2",new panel2());
fr.add(tab);
fr.show();
}
public static void main(String[] args)
{
new square();
}
}
class panel1 extends JPanel
{
panel1()
{
}
public void paintComponent(Graphics g3)
{
int x=(int)(Math.random()*500);
int y=(int)(Math.random()*500);
g3.setColor(Color.red);
g3.fillRect(x,y,100,100);
}
}
class panel2 extends JPanel
{
panel2()
{
}
public void paintComponent(Graphics g2)
{
int x=(int)(Math.random()*500);
int y=(int)(Math.random()*500);
g2.setColor(Color.blue);
g2.fillRect(x,y,100,100);
}
}
我随机使用坐标和大小
如果我切换标签,矩形的坐标和大小总是会改变。
第一次怎么制作和协调???
【问题讨论】:
-
不要在
paintComponent方法中创建/更改绘制状态 (x, y)。像在构造函数中一样设置它,然后在paintComponent方法中使用它。 -
你能举个例子吗???
-
只需制作面板类的
int x, y字段,然后在构造函数public panel() { x = .., y = .. }中初始化它们,然后在paint方法中使用x和y。如果您不了解字段和构造函数,我强烈建议您在使用 GUI 之前先了解 Java 基础知识 -
抱歉,我的 IDE 没有打开。
标签: java swing paintcomponent rectangles