我正在尝试使用Java添加9种不同颜色的正方形,这就是我在做的:
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
public class GUI{
private JFrame frame;
private ArrayList<Blocks> squares;
public static void main(String[] args) {
new GUI();
}
public GUI(){
frame = new JFrame("Blocks");
frame.setLayout(new GridLayout(3,3));
squares = new ArrayList<Blocks>();
squares.add(new Blocks(100,200,150,20,10));
squares.add(new Blocks(120,100,50,100,10));
squares.add(new Blocks(70,255,0,180,10));
squares.add(new Blocks(150,150,150,20,70));
squares.add(new Blocks(100,100,100,100,70));
squares.add(new Blocks(0,0,0,180,70));
squares.add(new Blocks(220,200,50,20,130));
squares.add(new Blocks(110,80,150,100,130));
squares.add(new Blocks(90,235,195,180,130));
frame.setBounds(850,300,300,260);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.getContentPane().setLayout(new GridLayout());
for(int i = 0; i<squares.size(); i++){
frame.add(squares.get(i));
}
frame.setVisible(true);
}
}
class Blocks extends JComponent{
private JLabel label;
private int r;
private int g;
private int b;
private int x;
private int y;
public Blocks(int r,int g,int b, int x, int y){
super();
this.r = r;
this.g = g;
this.b = b;
this.x = x;
this.y = y;
//label = new JLabel(s);
//setLayout(new BorderLayout());
//add(label, BorderLayout.CENTER);
//setLocation(20,10);
//setSize(80,60);
}
public void paintComponent(Graphics G){
super.paintComponent(G);
G.setColor(new Color(r,g,b));
G.fillRect(x,y,80,60);
}
}
因此,只有一个正方形显示,但是当我展开框架时,所有正方形都会显示出来,但是它们之间存在巨大的差距,我试图使它们彼此相邻,就像我的x和y值一样,我想在300*260框架中让所有它们彼此相邻,每个正方形为80*60。
编辑所有组件都显示不仅显示出来,而且它们仅在我扩展框架时显示出来,而且它们相距不远,因为我想要它们,我认为它们会起作用。不重复。
问题在于您正在从组件的(x,y)进行自定义绘画。您应该从组件的(0,0)进行绘画。
您使用的是布局管理器将组件定位在网格中,因此您只需让Layout Manager确定每个组件的(X,Y)位置,然后您只需填充组件即可。根据其大小。
您还应该覆盖组件的getPreferredSize()
方法,以便布局管理器可以在使用包装时确定组件的初始大小。
我想要框架和组件之间的间隙,它们正在填充整个帧
在父面板上使用空订单。阅读有关如何使用边框以获取更多信息的Swing教程中的部分。
更改paintcomponent():
public void paintComponent(Graphics G) {
super.paintComponent(G);
G.setColor(new Color(r, g, b));
G.fillRect(0, 0, getWidth(), getHeight());
}
如果您想要它们的空白:
public void paintComponent(Graphics G) {
super.paintComponent(G);
G.setColor(new Color(r, g, b));
G.fillRect(0, 0, getWidth() * 9 / 10, getHeight() * 9 / 10);
}