Hello everyone!
I've tried to create objects from classes and it worked until I wanted to draw the new objects I created.
package objectclasstrain; import javax.swing.SwingUtilities; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Dimension; import java.awt.Color; import java.awt.Graphics; public class ObjectClassTrain { public static void main(String[] args) { square squareRed = new square(); System.out.println(squareRed.returnXposition()); System.out.println(squareRed.returnYposition()); SwingUtilities.invokeLater(new Runnable(){ @Override public void run(){ createAndShowGUI(); } }); } public static void createAndShowGUI(){ JFrame f = new JFrame("JFrame test"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setResizable(false); f.add(new myPanel()); f.pack(); f.setVisible(true); } } class myPanel extends JPanel{ int room_width = 640; int room_height = 480; public myPanel(){ } @Override public Dimension getPreferredSize(){ return new Dimension(room_width, room_height); } @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(squareRed.returnXposition(), 0, room_width, room_height); } } class square{ int room_width = 640; int room_height = 480; double Xposition; double Yposition; public square(){ Xposition = (int) (Math.random() * room_width); Yposition = (int) (Math.random() * room_height); } public double returnXposition(){ return Xposition; } public double returnYposition(){ return Yposition; } }
I don't really know how I could get access to the squareRed's Xposition variable.
oh, and another problem is that there is only one line of code which will paint the objects, and I want to be able, for example,
to click on the screen to create an object which is automatically be painted on the screen. And to do that I can't just create new lines
of code for every object that could be created.
What should I do?