I'm trying to learn how to create classes in Processing, but I can't get the Capture class to work with the same code I would use in the main file of the program.
import processing.video.*;
class Game{
Capture video;
void videoFunction()
{
video = new Capture(this, width, height, 30);
video.start();
}
}
The error I'm getting is that the constructor Capture(filename.Game, int, int, int) is undefined
I'm guessing the problem is either with using this or with using the width and height variables. I can see that in the error message this is printed as the filename of the class, and not the filename of the main PDE.
How do I get the class to recognise this as the main filename, or width, and height as the width and height of the main program?
Is your Game class inside the Processing sketch, or is it in its own tab?
If it's inside the main sketch tab, then you can use the name of the sketch to specify what you mean by "this". Something like this:
void setup(){
Test2 t = new Test2();
t.printClass();
}
class Test2{
void printClass(){
print(TestSketch.this.getClass());
}
}
Note that in the above example, the name of my sketch is TestSketch.
If it's in its own tab, then you need to pass an instance of the Processing sketch into the Game class via its constructor. Something like this:
From the main sketch tab:
void setup(){
Test t = new Test(this);
t.printClass();
}
And in its own tab called Test:
class Test{
TestSketch testSketch;
public Test(TestSketch testSketch){
this.testSketch = testSketch;
}
void printClass(){
print(testSketch.getClass());
}
}
Related
how to destroy an object in unity?
I know you have to type the command
Destroy();
but what I'm saying is that I don't know what to put between brackets.
I have tried many different ways:
public GameObject motor;
Destroy(motor);
but it does not work
using System.Collections;
using UnityEngine;
public class LogRotation : MonoBehaviour
{
[System.Serializable] //this will allow us to edit it in the editor
//a custom class representing a single rotation "element" of the log's rotation pattern
private class RotationElement
{
//to get rid of an obnoxious warning about these fields not being initialized
#pragma warning disable 0649
public float Speed;
public float Duration;
#pragma warning restore 0649
}
[SerializeField] //attribute making private fields editable in the Unity Editor
//the aforemention full rotation pattern of the log
private RotationElement[] rotationPattern;
//this will be set to the Wheel Joint 2D from the LogMotor object
private WheelJoint2D wheelJoint;
//something has to actually apply a force to the log through the Wheel Joint 2D
private JointMotor2D motor;
private void Awake()
{
//setting fields
wheelJoint = GetComponent<WheelJoint2D>();
motor = new JointMotor2D();
//starting an infinitely looping coroutine defined below right when this script loads (awakes)
StartCoroutine("PlayRotationPattern");
}
private IEnumerator PlayRotationPattern()
{
int rotationIndex = 0;
//infinite coroutine loop
while (true)
{
//working with physics, executing as if this was running in a FixedUpdate method
yield return new WaitForFixedUpdate();
motor.motorSpeed = rotationPattern[rotationIndex].Speed;
//hard coded 10000, feel free to experiment with other torques if you wish
motor.maxMotorTorque = 10000;
//set the updated motor to be the motor "sitting" on the Wheel Joint 2D
wheelJoint.motor = motor;
//let the motor do its thing for the specified duration
yield return new WaitForSecondsRealtime(rotationPattern[rotationIndex].Duration);
rotationIndex++;
//infinite loop through the rotationPattern
rotationIndex = rotationIndex < rotationPattern.Length ? rotationIndex : 0;
}
}
}
TLDR; Destroy(motor.gameObject), but it will not work if JointMotor2D doesn't inherit MonoBehaviour.
Destroy(obj) can be used to destroy a component too.You need reference it to the game-object to destroy it.
Destroy(GetComponent<RigidBody>()) would remove the RigidBody out of the game-object, rather than removing the object itself.
Destroy(motor.gameObject) should do the trick.
But upon seeing your code, it may not.As it seems like JointMotor2D isn't a MonoBehaviour, aka it doesn't exists in the game-world, hence you can't destroy it.
Depending on what your trying to destroy, you have to find a reference to it.
Simplest way is to reference it in the inspector. Or destroy itself if that is already the object you want to destroy:
// Drag-drop the object in the inspector
[SerializeField]
private GameObject toDestroyLater;
private void DestroyObject() {
Destroy(toDestroyLater);
// Destroys self
// (Aka, whatever game-object this script is attached to)
Destroy(this.gameObject);
}
Language: Kotlin,
GUI Library: Swing,
IDE: IntelliJ IDEA
I know that there are similarly phrased questions, but note that I want to add multiple images, not just one, to any type of JComponent that holds other components. For example, I am not concerned with adding an image to a JLabel, I already know how to do that. I want to know how to add an image to a JFrame, JPanel, Container, etc.; all things that hold other Components (and have an add(Component) function). Finally, I don't want that workaround where you add the image to a JLabel with no text and then add that to the container. I would like to just use the Image class or a subset like BufferedImage or URL.
I want to be able to call the add() method from the Container class, jFrame.add(component) for example, where component is some sort of image. I want this to result in an image being displayed on the screen.
The ImageIcon class is not a Component so this can't be input on its own. I think I would have to create some sort of custom Image class that extends from Component or JComponent, but I don't know what I would have to override to get that to display an image on screen when added to another JComponent. There are multiple solutions to this, but to clarify, I don't want some kind of "middle man" where I add a JLabel or JButton or something that only contains an Icon. I don't want to display icons anyway, I want to display full-sized images anywhere on the screen. I will provide a possible example of what I want the final result to look like.
class MyApp() {
fun init() {
var jFrame = JFrame()
jFrame.add(Image("filepath/image.png"))
//Some other JFrame boiler plate
jFrame.isVisible = true
}
}
fun main() {
MyApp().init()
}
The unclear part is the Image class, and whether that's a custom class that inherits JImage, or some already defined class or method I don't know about. I know about ImageIO and BufferedImage and ImageIcon, but none of them directly go into this method, as they don't inherit Component or JComponent.
EDIT:
I tried using Camickr's second solution, but it didn't work. I will post the code to see if a made a simple mistake.
import java.awt.Image as AWTImage
import java.awt.Image.*
//Including these imports as I used name alias so I had to say what it was from.
open class JImage(var point: Point = Point(0, 0), image: AWTImage): JComponent() {
var image: ImageIcon = ImageIcon(image)
override fun paintComponent(g: Graphics?) {
super.paint(g)
g?.drawImage(image.image, point.x.toInt(), point.y.toInt(), null)
}
}
class SplashScreen(image: JImage): Frame() {
init {
//jFrame.isUndecorated = true
jFrame.add(image)
}
}
class MyApp {
fun init() {
var jFrame = SplashScreen(JImage(image = ImageIO.read(Loader().getClassLoader().getResourceAsStream("resources/images/splashscreen/SplashScreen.png"))).getScaledInstance(Size(1000, 1000*3/5)))
jFrame.isVisible = true
}
}
fun main() {
MyApp().init()
}
FINAL EDIT:
Okay, so I did make a simple mistake when trying this solution. I overrode paintComponent() but then inside it, I called super.paint(). Additionally, I realized I didn't have to use the ImageIcon class, which I didn't want to do anyway. This is the Image class I have come up with.
open class JImage(var point: Point = Point(0, 0), var image: AWTImage): JComponent() {
fun getScaledInstance(size: Size, scalingMethods: ScalingMethods = ScalingMethods.DEFAULT): JImage {
val scale: Int = when(scalingMethods) {
ScalingMethods.DEFAULT -> SCALE_DEFAULT
ScalingMethods.FAST -> SCALE_FAST
ScalingMethods.AREA_AVERAGING -> SCALE_AREA_AVERAGING
ScalingMethods.REPLICATE -> SCALE_REPLICATE
ScalingMethods.SMOOTH -> SCALE_SMOOTH
}
return JImage(point, image.getScaledInstance(size.width.toInt(), size.height.toInt(), scale))
}
override fun paintComponent(g: Graphics?) {
super.paintComponent(g)
g?.drawImage(image, point.x.toInt(), point.y.toInt(), null)
}
}
I want to know how to add an image to a JFrame, JPanel, Container, etc.
You don't add an image to a JFrame, JPanel etc. As you said an image is not a component. You add the image to a JLabel and add the label to the panel. This is the easiest and more direct way to display an image at its actual size.
Don't know if Kotlin is any different, but the other option is to do custom painting and paint the image on a JPanel by overriding the paintComponent(…) method and using the Graphics.drawImage(…) method and then add the panel to the frame. Read the Swing tutorial on Custom Painting for painting basics.
You can also check out Background Panel for an example that paints an image as a background of the panel. The image can be:
painted at its real size
scaled to fill the panel
tiled to fill the panel
Just note that the image should NOT be read in the paintComponent() method as painting code should be efficient.
I want to have 3 objects doing different things, so I want to get the source of the caller.
I am using lambda for that, and I am not using key frame, the animation is the same and cyclic so I don't need to specify different behavior for a different key frame.
Maybe I am doing something wrong with the lambda?
this is my code:
class MyClock extends ClockPane //clockpane extends pane
{
Timeline animation;
int id;
EventHandler<ActionEvent> eventHandler = e ->
{//startAnimationById();
System.out.println(e.getSource()==clockControl1.myclock.animation);
};
public MyClock(int c,int id)
{
super(c);
this.id=id;
animation = new Timeline(new KeyFrame(Duration.millis(1000),eventHandler));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
}
the startanimationbyid method works using the id I defined to avoid this problem, but it surely does bug me.
I have 3 different objects of this type, each one is nested ina clockcontrol class
(in other words I have clockcontrol1 clockcontrol2 and 3 each one of these having a MyClock myclock in them)
The print I have there returns false for all the the clocks I have (total of 3) while as it is currently written I'd expect to get true for the first clock...I tried different variations of this, the one I post here is only the last variation, but I got false for all of my attempts.
Where did I mess things up?
The API for KeyFrame doesn't specify what the source of the ActionEvent will be. You could just do System.out.println(e.getSource()) to see (it seems that the source of the event is the KeyFrame object, not the animation), but there's no real guarantee it would always be what you expect.
If you want different instances of MyClock to behave differently, you can provide a parameter for the different behavior. In this case, you could use a Runnable to execute different code in the event handler:
class MyClock extends ClockPane //clockpane extends pane
{
Timeline animation;
// int id;
public MyClock(int c, Runnable handler)
{
super(c);
EventHandler<ActionEvent> eventHandler = e -> handler.run() ;
animation = new Timeline(new KeyFrame(Duration.millis(1000),eventHandler));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
}
}
Then you can instantiate these as you need:
public class Controller1 {
// ...
MyClock clock = new MyClock(..., () -> {
// code to execute for this clock
});
}
and
public class Controller2 {
// ...
MyClock clock = new MyClock(..., () -> {
// code to execute for this clock
});
}
class Robot extends Canvas
{
public Robot() //constructor method - sets up the class
{
setSize(800,600);
setBackground(Color.WHITE);
setVisible(true);
}
public void paint( Graphics window )
{
window.setColor(Color.BLUE);
window.drawString("Robot LAB ", 35, 35 );
//call head method
//call other methods
}
public void head( Graphics window )
{
window.setColor(Color.YELLOW);
window.fillRect(300, 100, 200, 100);
//add more code here
}
How exactly do I call the head method?
I've tried multiple times, but I just can't seem to get it.
head(); window.head(); hasn't worked for me?
Sorry, I'm really new to this.
You need to use
head(window);
This is just how you call a method with parameters in Java (and most other languages), you put the parameters as a comma-separated list in the parentheses that follow the method name. Note that the parantheses are there even without any parameters.
methodWithNoParameters();
someOtherObject.methodWithNoParameters();
this.methodWithOneParameter("foo");
SomeClass.staticMethodWithFiveParameters(1,two,3,4, "five");
The number, order and types of the parameters must match what the method declaration has for its formal parameters. In your case public void(Graphics window) means there is just one.
Finally, you should make this method private if you only call it from inside paint (and not from outside of the class itself).
I wrote a wxPython program that I am translating to wxWidgets. The program has a scrolled window that displays an image. Following Rappin, wxPython In Action (Listing 12.1), I used a StaticBitmap within a panel. While surfing the latest wxWidgets documentation, I found a dire warning that wxStaticBitmap should only be used for very small images. It says, "... you should use your own control if you want to display larger images portably." Okay. Show me. I don't have my "own control."
Was Rappin wrong, or is the documentation out of date?
The question - a newbie one, no doubt - is what is the right way to do a simple image-view window in wxWidgets? A drop-in replacement for wxStaticBitmap would be nice. I looked into the "image" program in the wxWidgets "samples" directory. It's as long a War and Peace. Surely there must be a canned class or a simple recipe.
Don't let the size of the "image" sample fool you, only a few lines of code are necessary to do what you want.
Search for the MyImageFrame class in the image.cpp file, it is nothing more than a class with a private bitmap field, a custom constructor to set the bitmap and the window client size, and an event handler for EVT_PAINT:
void OnPaint(wxPaintEvent& WXUNUSED(event))
{
wxPaintDC dc( this );
dc.DrawBitmap( m_bitmap, 0, 0, true /* use mask */ );
}
Since you don't want a frame class here's your recipe: You create a simple descendant of wxWindow that has a similar constructor, paint handler and duplicates the methods of wxStaticBitmap that you use in your code. Maybe simply one method to set a new bitmap and resize the control to the new bitmap dimensions.
// A scrolled window for showing an image.
class PictureFrame: public wxScrolledWindow
{
public:
PictureFrame()
: wxScrolledWindow()
, bitmap(0,0)
{;}
void Create(wxWindow *parent, wxWindowID id = -1)
{
wxScrolledWindow::Create(parent, id);
}
void LoadImage(wxImage &image) {
bitmap = wxBitmap(image);
SetVirtualSize(bitmap.GetWidth(), bitmap.GetHeight());
wxClientDC dc(this);
PrepareDC(dc);
dc.DrawBitmap(bitmap, 0, 0);
}
protected:
wxBitmap bitmap;
void OnMouse(wxMouseEvent &event) {
int xx,yy;
CalcUnscrolledPosition(event.GetX(), event.GetY(), &xx, &yy);
event.m_x = xx; event.m_y = yy;
event.ResumePropagation(1); // Pass along mouse events (e.g. to parent)
event.Skip();
}
void OnPaint(wxPaintEvent &event) {
wxPaintDC dc(this);
PrepareDC(dc);
dc.DrawBitmap(bitmap, 0,0, true);
}
private:
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(PictureFrame,wxScrolledWindow)
EVT_PAINT(PictureFrame::OnPaint)
EVT_MOUSE_EVENTS(PictureFrame::OnMouse)
END_EVENT_TABLE()