如何将值传递给paint方法

问题描述 投票:0回答:1

我刚刚开始使用Java编码,到目前为止,我可以解决我在互联网上寻找解决方案的问题,但这次我只是坚持了下来。我想创建一个填充矩形的网格(图案),它工作正常,但后来我想改变特定位置的矩形颜色,这部分不起作用。我不明白为什么,我做错了什么?

// **file : MainWindow.java **
import java.util.Scanner;
import javax.swing.JFrame;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

public class MainWindow {

    JFrame frame = new JFrame();
    int pos_X;
    int pos_Y;

    // constructor for frame
    public MainWindow (String title) {

    frame.setSize(1000, 1000);
    frame.setTitle(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    for (int i=0;i<26;i++){ // works fine
        for (int j=0;j<26;j++){         
        Shape shape = new Shape (110+i*20,110+j*20,19,19,5,100,220); //(x,y, width,height, R-colour, G-colour, B-colour)
        frame.add(shape);
        frame.setVisible(true); }}  

    pos_X= 15;
    pos_Y = 15;
    Shape shape = new Shape (110+pos_X*20,110+pos_Y*20,19,19,250,0,20); // it doesn't work ???
    frame.add(shape);   
    frame.setVisible(true);
    }

    public static void main(String[] args){
        new MainWindow(" my window ");
        }
}

// **file : Shape.java **
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Color.*;
import javax.swing.JComponent;

public class Shape extends JComponent{
    int width, height, xcoord, ycoord, col_r, col_g,col_b;

    //constructor
public Shape (int x, int y ,int w,int h, int k, int l, int m) 
{
        this.width = w;
        this.height = h;
        this.xcoord = x;
        this.ycoord = y;
        this.col_r = k;
        this.col_g = l;
        this.col_b = m;
}
    public void paintComponent(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        Color x= new Color( col_r,col_g, col_b );
        g.setColor(x);
        g.fillRect(xcoord, ycoord, width, height);
    }
}
graphics jframe paint
1个回答
0
投票

如果我理解正确,你可以做什么来确保在网格之后绘制形状,所以

pos_X= 15;
pos_Y = 15;
Shape shape = new Shape (110+pos_X*20,110+pos_Y*20,19,19,250,0,20); // it doesn't work ???
frame.setComponentZOrder(shape,0)
frame.add(shape);   
frame.setVisible(true);
        ...

请注意

frame.setComponentZOrder(shape,0)

确保彩色形状被绘制在其他形状之上。在替代你的

附:如果它不起作用尝试frame.setComponentZOrder(shape,frame.getComponentCount())

另请参阅here

© www.soinside.com 2019 - 2024. All rights reserved.