我的目标是创建一个简单的包装器,用于将任意像素绘制到窗口。
不幸的是我总是收到错误:
Traceback (most recent call last):
File "test.py", line 11, in <module>
canvas = window( 'Test', WINDOW_WIDTH, WINDOW_HEIGHT)
File "..\painter.py", line 16, in __init__
my_jframe.getContentPane().add( my_image)
TypeError: add(): 1st arg can't be coerced to java.awt.Component, java.awt.PopupMenu
问题是什么???
感谢您的建议!
卢卡斯。
作为来电者我使用以下内容:
# (test.py)
#! /usr/bin/env jython
import time
import random
from painter import window
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
canvas = window( 'Test', WINDOW_WIDTH, WINDOW_HEIGHT)
print( 'fuck1')
for x in range( WINDOW_WIDTH):
for y in range ( WINDOW_HEIGHT):
rgba = [ random.randint( 0, 255), random.randint( 0, 255), random.randint( 0, 255), 255]
print( x, y, rgba)
canvas.paint_pixel( x, y, rgba)
time.sleep( 1)
被调用的模块如下所示:
# (painter.py)
#! /usr/bin/env jython
import javax.swing
import java.awt
class window( object):
def __init__( self, window_title, window_width, window_height):
my_jframe = javax.swing.JFrame( window_title)
my_image = java.awt.image.BufferedImage(
window_width,
window_height,
java.awt.image.BufferedImage.TYPE_INT_ARGB
)
my_jframe.getContentPane().add( my_image)
my_jframe.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE)
my_jframe.setSize( window_width, window_height)
my_jframe.setLocationRelativeTo( None) # center window
my_jframe.show()
def paint_pixel( self, x, y, rgba):
c = java.awt.Color( rgba[0], rgba[1], rgba[2], rgba[3])
self.my_image.setRGB( x, y, c)
答案 0 :(得分:0)
我认为Swing不允许动态更改BufferedImage
,但您可以使用以下内容:
test.py
的修改版本:
# (test2.py)
#! /usr/bin/env jython
import time
import random
from painter2 import window
from java.awt import Color
from java.util import Random
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
canvas = window( 'Test', WINDOW_WIDTH, WINDOW_HEIGHT)
randomNumbers = Random(123456)
for x in range( WINDOW_WIDTH):
for y in range ( WINDOW_HEIGHT):
color = Color(randomNumbers.nextInt(2 ** 24))
#print( x, y, color)
canvas.add_pixel( x, y, color)
#time.sleep( 1)
canvas.repaint()
painter.py
的修改版本:
# (painter2.py)
#! /usr/bin/env jython
import javax.swing
import java.awt
from colored_pixel import colored_pixel
class window( javax.swing.JPanel):
def __init__( self, window_title, window_width, window_height):
my_jframe = javax.swing.JFrame( window_title)
my_jframe.getContentPane().add( self, java.awt.BorderLayout.CENTER)
self.pixels = []
my_jframe.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE)
my_jframe.setSize( window_width, window_height)
my_jframe.setLocationRelativeTo( None) # center window
my_jframe.setVisible( True)
print self.getWidth()
print self.getHeight()
def add_pixel( self, x, y, color):
self.pixels.append( colored_pixel( x, y, color))
def paintComponent( self, graphics):
for pixel in self.pixels:
graphics.setColor( pixel.color)
graphics.drawRect( pixel.x, pixel.y, 1, 1)
用于存储像素位置和颜色的小类:
class colored_pixel( object):
def __init__( self, x, y, color):
self.x = x
self.y = y
self.color = color