I have my Java project (link down there) and i want to add two custom components. I have tried adding them to panels, adding them to panels with layout, but nothing worked. I don't want layouts, since I am placing my components in special positions, which you can see in code. So here's code:
import javax.swing.*;
import java.awt.*;
class Screen extends JFrame
{
public Cube cube;
public Cube cube2;
public Boolean running = true;
public Screen()
{
JPanel panel = new JPanel(new BorderLayout());
cube = new Cube(75, 75, 50, 50);
cube2 = new Cube(10,950,1900,50,50);
//setLayout(new FlowLayout());
panel.add(cube);
panel.add(cube2);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Thread main = new MainThread();
main.run();
}
void paintComponent(Graphics g)
{
cube.paint(g);
cube2.paint(g);
}
public float Gravity = .00000000000881f;
public void Gravity()
{
cube.AddVelocity(0f,Gravity);
}
public static void main(String[] args) {
new Screen();
}
class MainThread extends Thread
{
public void run()
{
try{
sleep(2000);
} catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Starting");
while(running){
//System.out.println("cube: " + cube.x + "," + cube.y);
//System.out.println("cube2: " + cube2.x + "," + cube2.y);
cube.UpdateMethod();
Gravity();
repaint();
}
}
}
}
public class Cube extends JComponent {
float x, y, sizex, sizey, shift;
public Cube(int x, int y, int size, int shift) {
this.x = x;
this.y = y;
this.sizex = size;
this.sizey = size;
this.shift = shift;
}
public Cube(int x, int y, int sx, int sy, int shift) {
this.x = x;
this.y = y;
this.sizex = sx;
this.sizey = sy;
this.shift = shift;
}
Vector2 Velocity = new Vector2(0,0);
public void AddVelocity(float a, float b)
{
Velocity.x += a;
Velocity.y += b;
}
public void MoveBy(Float x, float y)
{
this.x+=x;
this.y+=y;
repaint();
}
public void UpdateMethod()
{
MoveBy(Velocity.GetX(), Velocity.GetY());
}
protected void paintComponent(Graphics g) {
int nx = (int) x;
int ny = (int) y;
int nsx = (int) sizex;
int nsy = (int) sizey;
g.drawRect(nx, ny, nsx, nsy);
}
Boolean CheckCollision(Cube other)
{
if(x < other.x + other.sizex &&
x + sizex > other.x &&
y < other.y + other.sizey &&
sizey + sizey > other.y)
{
return true;
}
return false;
}
}
class Vector2
{
public float x,y;
public Vector2(int a, int b)
{
x=a;
y=b;
}
public float GetX()
{
return x;
}
public float GetY()
{
return y;
}
}