I've created three classes (two JPanels and a JFrame) per the specifications of a homework assignment, but unfortunately, all my notes from the last week were lost in a computer crash. I know there's a simple solution, but I've been spending hours trying to remember what to look up.
Here's the frame (it's working fine):
import java.awt.*; import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class FrameClass extends JFrame { public FrameClass (int width, int height) { super(); this.setTitle("Assignment 05"); this.setSize(width,height); this.setLocationRelativeTo(null); this.setLayout(new BorderLayout(10, 2)); this.add(new graphicspanel(), BorderLayout.CENTER); this.add(new controlspanel(), BorderLayout.EAST); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { FrameClass fc = new FrameClass(750, 450); } }
Here's my first panel, which is also working fine (I can't make the timer or the start and stop methods static because I need to call a non-static method (repaint) from inside the timer later in the assignment):
package Assignment5; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.*; import ParticlePackage.particle; import MathVector.*; public class graphicspanel extends JPanel { private int width; private int height; public graphicspanel () { super(); this.setBackground(Color.gray); } Timer timer = new Timer (100, new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("tick"); } }); public void start() {timer.start();} public void stop() {timer.stop();} }
And finally, I desperately need a walkthrough of how to call the start and stop methods when the buttons in the following panel are pressed without making the methods static. The solution my professor gave us involved using the JFrame class somehow, but I've spent hours trying to recall what to look up with no luck.
package Assignment5; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Timer; import javax.swing.*; public class controlspanel extends JPanel { public controlspanel() { setLayout(new GridLayout(10,1,10,2)); JButton button1 = new JButton("Start"); button1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.out.println("Start"); start(); } } ); add(button1); JButton button2 = new JButton("Stop"); button2.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.out.println("Stop"); stop(); } } ); add(button2); } }