Java:根据各种操作在GUI中获取和设置像素

时间:2018-11-01 06:12:05

标签: java user-interface pixel

我搜寻了Internet,以更深入地了解GUI在Java中的行为,但是我仍然迷失了。我想做的是从500x500灰色背景开始,然后让turmite算法读取一个像素,根据颜色对其进行更改,然后移动(未尝试最后一位)。当我尝试在下面的代码中更改像素的颜色时,就会出现问题。

编辑:我真正需要的是一个可以从任何地方调用的函数,该函数可以将特定颜色的像素绘制到GUI。我想告诉我我编写的代码是如何不起作用的,这只是教育上的好处。

public void loop() 
{
    switch(canvas.getRGB(x, y)&0xFFFFFF)
    {
    case 0xFFFFFF: canvas.setRGB(x, y, calculations.L0[calculations.L1[0]]);break;
    case 0x000000: canvas.setRGB(x, y, calculations.L0[calculations.L1[1]]);d++;break;
    case 0xFF0000: canvas.setRGB(x, y, calculations.L0[calculations.L1[2]]);d+=2;break;
    case 0xFF8C00: canvas.setRGB(x, y, calculations.L0[calculations.L1[3]]);d+=3;break;
    case 0xFFD700: canvas.setRGB(x, y, calculations.L0[calculations.L1[4]]);d+=4;break;
    case 0x00FF00: canvas.setRGB(x, y, calculations.L0[calculations.L1[5]]);d+=5;break;
    case 0x0000FF: canvas.setRGB(x, y, calculations.L0[calculations.L1[6]]);d+=6;break;
    case 0xFF00FF: canvas.setRGB(x, y, calculations.L0[calculations.L1[7]]);d+=7;break;
    default: canvas.setRGB(x, y, calculations.L0[calculations.L1[0]]);break;
    }
}

我希望完整的代码是必要的,因此我将在此处包括:

Draw.java

package turmite;
import turmite.Window;
import turmite.Calculations;
//import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
//import java.awt.Color;
import java.awt.Dimension;
//import java.awt.Graphics;
//import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
//import javax.swing.BorderFactory;
import java.util.*;
import java.util.Random;
//import java.util.stream.Stream;
import java.lang.String;
//import java.util.ArrayList;
//import java.util.List;

@SuppressWarnings("serial")
public class Draw extends JFrame implements ActionListener{

private JButton calculate;
private Calculations calculations;
private Window window;

public Draw() /*throws AWTException*/ {

    window=new Window();
    calculate=new JButton("Calculate");
    calculate.addActionListener(this);
    calculate.setActionCommand("");
    calculations=new Calculations(this);
    this.getContentPane().setBackground(Color.GRAY);
    this.setLayout(new BorderLayout());
    this.add(window);
    this.add(calculate, BorderLayout.NORTH);
    this.setTitle("Draw");
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(new Dimension(500,500));
    this.setLocationRelativeTo(null);
//      Robot r = new Robot();

    Random rnd = new Random();

    calculations.x = 2 + rnd.nextInt(getWidth()-4);
    calculations.y = 2 + rnd.nextInt(getHeight()-4);
    System.out.println(calculations.x+" "+calculations.y);

    int I,a = 0;

    while(a < 7)
    {
        I = rnd.nextInt(8);

        if(!Arrays.toString(calculations.L0).contains(Integer.toString(I)))
        {
            calculations.L0[a] = I;
            a++;
        }

        System.out.println(Arrays.toString(calculations.L0)+","+I+" "+Arrays.toString(calculations.L0).contains(Integer.toString(I)));
    }

    System.out.println(Arrays.toString(calculations.L0)+" L0 Complete");
    a=0;

    while(a < 7)
    {
        I = rnd.nextInt(8);

        if(!Arrays.toString(calculations.L1).contains(Integer.toString(I)))
        {
            calculations.L1[a] = I;
            a++;
        }

        System.out.println(Arrays.toString(calculations.L1)+","+I+" "+Arrays.toString(calculations.L1).contains(Integer.toString(I)));
    }

    System.out.println(Arrays.toString(calculations.L1)+" L1 Complete");

    for(a=0;a<8;a++)
    {
        switch(calculations.L0[a])
        {
        case 0: calculations.L2[a] = "#FFFFFF";break;
        case 1: calculations.L2[a] = "#000000";break;
        case 2: calculations.L2[a] = "#FF0000";break;
        case 3: calculations.L2[a] = "#FF8C00";break;
        case 4: calculations.L2[a] = "#FFD700";break;
        case 5: calculations.L2[a] = "#00FF00";break;
        case 6: calculations.L2[a] = "#0000FF";break;
        case 7: calculations.L2[a] = "#FF00FF";break;
        default: System.out.println("Failure to assign color to L2["+a+"]");break;
        }
    }
}

@Override
public void actionPerformed(ActionEvent e)
{
    if(e.getActionCommand().equals(""))
    {

        calculations.calculate();
        window.setVisible(true);

    }
}


public static void main(String[] args)/* throws AWTException*/
{
    new Draw();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI(); 
        }
    });
}
private static void createAndShowGUI() {
    JPanel f = new JPanel();
    //Window window = new Window();
    f.add(new Window());
    //window.loop();
    f.setVisible(true);

}
}

Window.java

package turmite;
import turmite.Calculations;
//import turmite.Draw;
//import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
//import javax.swing.border.TitledBorder;
//import java.awt.Robot;

@SuppressWarnings("serial")
public class Window extends JPanel {

BufferedImage canvas = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
private JPanel panel;
private Calculations calculations;
Random rnd = new Random();
int x = 2 + rnd.nextInt(496),y = 2 + rnd.nextInt(496),d=0;

public Window()
{
    //this.setBorder(new TitledBorder("Console:"));
    setBorder(BorderFactory.createLineBorder(Color.black));
    panel=new JPanel();
    this.setBackground(Color.GRAY);
    this.setLayout(new BorderLayout());
    //this.setVisible(true);
    this.add(panel);

}

public Dimension getPreferredSize()
{
    return new Dimension(500,500);
}

protected void paintComponent(Graphics g)
{   
    new Window();
    super.paintComponent(g);
    g.fillRect(0, 0, 500, 500);
    g.setColor(Color.GRAY);
    panel.setSize(500, 500);
    panel.setBackground(Color.GRAY);
    panel.repaint();
    panel.setVisible(true);
    //canvas = new BufferedImage(500,500,BufferedImage.TYPE_INT_RGB);
    this.repaint();

    //        switch(canvas.getRGB(x, y)&0xFFFFFF)
    //        {
    //        case 0xFFFFFF: canvas.setRGB(x, y, calculations.L0[calculations.L1[0]]);break;
    //        case 0x000000: canvas.setRGB(x, y, calculations.L0[calculations.L1[1]]);d++;break;
    //        case 0xFF0000: canvas.setRGB(x, y, calculations.L0[calculations.L1[2]]);d+=2;break;
    //        case 0xFF8C00: canvas.setRGB(x, y, calculations.L0[calculations.L1[3]]);d+=3;break;
    //        case 0xFFD700: canvas.setRGB(x, y, calculations.L0[calculations.L1[4]]);d+=4;break;
    //        case 0x00FF00: canvas.setRGB(x, y, calculations.L0[calculations.L1[5]]);d+=5;break;
    //        case 0x0000FF: canvas.setRGB(x, y, calculations.L0[calculations.L1[6]]);d+=6;break;
    //        case 0xFF00FF: canvas.setRGB(x, y, calculations.L0[calculations.L1[7]]);d+=7;break;
    //        default: canvas.setRGB(x, y, calculations.L0[calculations.L1[0]]);break;
    //        }


}
public void loop() /*throws AWTException*/
{

    //Robot r = new Robot();
    //System.out.println(r.getPixelColor(x, y));
    switch(canvas.getRGB(x, y)&0xFFFFFF)
    {
    case 0xFFFFFF: canvas.setRGB(x, y, calculations.L0[calculations.L1[0]]);break;
    case 0x000000: canvas.setRGB(x, y, calculations.L0[calculations.L1[1]]);d++;break;
    case 0xFF0000: canvas.setRGB(x, y, calculations.L0[calculations.L1[2]]);d+=2;break;
    case 0xFF8C00: canvas.setRGB(x, y, calculations.L0[calculations.L1[3]]);d+=3;break;
    case 0xFFD700: canvas.setRGB(x, y, calculations.L0[calculations.L1[4]]);d+=4;break;
    case 0x00FF00: canvas.setRGB(x, y, calculations.L0[calculations.L1[5]]);d+=5;break;
    case 0x0000FF: canvas.setRGB(x, y, calculations.L0[calculations.L1[6]]);d+=6;break;
    case 0xFF00FF: canvas.setRGB(x, y, calculations.L0[calculations.L1[7]]);d+=7;break;
    default: canvas.setRGB(x, y, calculations.L0[calculations.L1[0]]);break;
    }
}

}

Calculations.java

package turmite;
import turmite.Draw;
import turmite.Window;
//import java.awt.AWTException;
import java.util.Arrays;

public class Calculations {


@SuppressWarnings("unused")
private Draw parent;
private Window window;
int x=0,y=0;
int[] L0 = new int[8],L1 = new int[8];
String[] L2 = new String[8];


public Calculations(Draw f){
    parent=f;
}

public void calculate() /*throws AWTException*/{
    new Thread(new Runnable() {
        @Override 
        public void run() 
        {

            for (int i = 0; i <= 100; i++) {
                try
                {
                    Thread.sleep(50);

                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

//                  switch(window.canvas.getRGB(window.x, window.y)&0xFFFFFF)
//                  {
//                  case 0xFFFFFF: window.canvas.setRGB(window.x, window.y, L0[L1[0]]);break;
//                  case 0x000000: window.canvas.setRGB(window.x, window.y, L0[L1[1]]);window.d++;break;
//                  case 0xFF0000: window.canvas.setRGB(window.x, window.y, L0[L1[2]]);window.d+=2;break;
//                  case 0xFF8C00: window.canvas.setRGB(window.x, window.y, L0[L1[3]]);window.d+=3;break;
//                  case 0xFFD700: window.canvas.setRGB(window.x, window.y, L0[L1[4]]);window.d+=4;break;
//                  case 0x00FF00: window.canvas.setRGB(window.x, window.y, L0[L1[5]]);window.d+=5;break;
//                  case 0x0000FF: window.canvas.setRGB(window.x, window.y, L0[L1[6]]);window.d+=6;break;
//                  case 0xFF00FF: window.canvas.setRGB(window.x, window.y, L0[L1[7]]);window.d+=7;break;
//                  default: window.canvas.setRGB(window.x, window.y, L0[L1[0]]);break;
//                  }

                //window.loop();
            }

        }   
    }).start();
    window.loop();
    System.out.println(/*Color.decode(""+*/window.canvas.getRGB(10, 10));
    System.out.println(Arrays.toString(L2));


}

}

感谢您提供的任何见解;我是Java的新手,弗兰肯斯坦(Frankenstein)活泼的工作可能告诉我,我对自己的工作一无所知。

1 个答案:

答案 0 :(得分:0)

经过大约一周半的随机试验和错误,我设法整理了代码的工作版本并自己解决了问题,同时还大大降低了复杂性。

固定代码:(这次仅一个文件)

package turmite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;

@SuppressWarnings("serial")
public class Base extends JPanel implements ActionListener {

    int x = 200        ,
        y = 200        ,
        d = 0          ,
        X = width  - 1 , 
        Y = height - 1 ;

    Color blk = Color.BLACK ,
          wht = Color.WHITE ,
          c                 ;

    private JButton Button;

    public static void main(String[] args)
    {
        new Base();
    }

    final static int width  = 400;
    final static int height = 400;

    BufferedImage img;

    JFrame frame = new JFrame();

    Base() 
    {
        Button = new JButton("Start Loop");
        Button.setPreferredSize(new Dimension(400,20));
        Button.addActionListener(this);
        Button.setActionCommand("");

        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);

        setPreferredSize(new Dimension(width, height));

        frame.setBackground(wht);
        frame.setLayout(new BorderLayout());
        frame.add(Button, BorderLayout.SOUTH);
        frame.add(this);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    void loop()
    {
        while(true)
        {
            switch (d) 
            {
            case 0 : x++;       break;
            case 1 :      y++;  break;
            case 2 : x--;       break;
            case 3 :      y--;  break;
            default:            break;
            }

            //for 8-directions
            /*switch (d)
            {
            case 0 : x++;       break;
            case 1 : x++; y++;  break;
            case 2 :      y++;  break;
            case 3 : x--; y++;  break;
            case 4 : x--;       break;
            case 5 : x--; y--;  break;
            case 6 :      y--;  break;
            case 7 : x++; y--;  break;
            default: d = 0;     break;
            }*/

            if (x < 0)  x = X;
            if (x > X)  x = 0;
            if (y < 0)  y = Y;
            if (y > Y)  y = 0;

            if (wht.getRGB() == img.getRGB(x , y))
            {
                c = blk;

                if (d == 3)
                    d =  0;
                else 
                    d++;
            }
            else
            { 
                c = wht;

                if (d == 0)
                    d =  3;
                else 
                    d--;
            }

            Graphics g = img.getGraphics();

            g.setColor(c);  //set color
            g.drawRect(x, y, 0, 0);//set pixel
            g.dispose();

            frame.repaint();
            update(getGraphics());
        }

    }

    @Override
    public void paintComponent(Graphics g)
    {
        g.drawImage(img, 0, 0, null);
    }

    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        loop();
    }

}

这里要注意的重要一件事是update(getGraphics());是使程序实时写入屏幕的要素。它比例如for()内的public void actionPerformed(ActionEvent arg0)循环(执行嵌套void loop()的所有操作(显然是嵌套的while(true)循环)要重复数千次但要慢得多,但速度要慢得多。仅在完成后更新。但是,我的程序是为实时效果而设计的,因此,我只提及速度变慢以供参考。

此外,我很高兴听到此程序中是否有任何可以优化/改进的内容!