I am currently trying to draw a figure by clicking a button. My problems occurs when I click the button and it does not show up in the panel, but I know it's drawing because it runs through the loop.
The drawing will occur when I request the panel to draw it inside the constructor, but not inside the button, inside the constructor
If i put the code in the method "stuff()" inside the constructor it will draw everything just fine.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainFrame{
public static void main(String[]args){
MainFrame f = new MainFrame();
}
public JFrame frame = new JFrame();
public JPanel panel = new JPanel(new BorderLayout());
public MainFrame(){
JButton button1 = new JButton("Shweet Button");
button1.setBounds(185, 10, 130, 20);
frame.setBounds(1680/4,1050/4,500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
panel.setBackground(Color.black);
frame.setVisible(true);
frame.getContentPane().setLayout(null);
frame.add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stuff();
}
});
}
public void stuff(){
for(int i = 0;i<1000;i++){
panel.add(new paintComponent());
panel.setBackground(Color.black);
frame.repaint();
try {
Thread.sleep(80);
} catch (InterruptedException e1){e1.printStackTrace();}
}
}
static class paintComponent extends JComponent{
public int options;
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.white);
if(options == 0){
options = 1;
g2.drawOval(50, (JFrame.HEIGHT/2)+100, 50, 50);
g2.drawOval(60, (JFrame.HEIGHT/2)+110, 8, 8);
g2.fillOval(60, (JFrame.HEIGHT/2)+110, 8, 8);
g2.drawOval(80, (JFrame.HEIGHT/2)+110, 8, 8);
g2.fillOval(80, (JFrame.HEIGHT/2)+110, 8, 8);
g2.drawArc(65, (JFrame.HEIGHT/2)+130, 100, 0, 140, 30);
g2.drawLine(75, (JFrame.HEIGHT/2)+150, 75, (JFrame.HEIGHT/2)+220);
g2.drawLine(75, (JFrame.HEIGHT/2)+180, 100, (JFrame.HEIGHT/2)+160);
g2.drawLine(75, (JFrame.HEIGHT/2)+180, 65, (JFrame.HEIGHT/2)+210);
g2.drawLine(75, (JFrame.HEIGHT/2)+220, 50, (JFrame.HEIGHT/2)+260);
g2.drawLine(75, (JFrame.HEIGHT/2)+220, 100, (JFrame.HEIGHT/2)+260);
}else if(options == 1){
options = 0;
g2.drawOval(50, (JFrame.HEIGHT/2)+100, 50, 50);
g2.drawOval(60, (JFrame.HEIGHT/2)+110, 8, 8);
g2.fillOval(60, (JFrame.HEIGHT/2)+110, 8, 8);
g2.drawOval(80, (JFrame.HEIGHT/2)+110, 8, 8);
g2.fillOval(80, (JFrame.HEIGHT/2)+110, 8, 8);
g2.drawArc(65, (JFrame.HEIGHT/2)+130, 100, 0, 140, 30);
g2.drawLine(75, (JFrame.HEIGHT/2)+150, 75, (JFrame.HEIGHT/2)+220);
g2.drawLine(75, (JFrame.HEIGHT/2)+180, 100, (JFrame.HEIGHT/2)+180);
g2.drawLine(75, (JFrame.HEIGHT/2)+180, 65, (JFrame.HEIGHT/2)+210);
g2.drawLine(75, (JFrame.HEIGHT/2)+220, 50, (JFrame.HEIGHT/2)+260);
g2.drawLine(75, (JFrame.HEIGHT/2)+220, 100, (JFrame.HEIGHT/2)+260);
}
}
}
}
You are blocking the Event Dispatching Thread, which is responsible for, amongst other things, processing paint requests.
You should never do anything like this...
for(int i = 0;i<1000;i++){
panel.add(new paintComponent());
panel.setBackground(Color.black);
frame.repaint();
try {
Thread.sleep(80);
} catch (InterruptedException e1){e1.printStackTrace();}
}
Within the EDT. Apart from the fact you are adding multiple new components to your UI every 80 milliseconds, you are also blocking the thread that is responsible for updating your screen...
Check out Concurrency in Swing for more details.
Animation of this type should be handled by a javax.swing.Timer.
Custom painting should be performed in the paintComponent method, as a general rule. You should also be calling super.paintXxx first as a matter of course. There's a lot of working going in the background that needs to be taken care of, especially if the component is transparent.
Check out Performing Custom Painting and Painting in AWT and Swing for more details.
Save your sanity and learn how to use layout managers, they will make your life easier in the long run.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MainFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
MainFrame f = new MainFrame();
}
});
}
public JFrame frame = new JFrame();
public JPanel panel = new JPanel(new BorderLayout());
private WavePane waver;
public MainFrame() {
waver = new WavePane();
JButton button1 = new JButton("Shweet Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setBackground(Color.black);
frame.add(button1, BorderLayout.SOUTH);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stuff();
}
});
panel.add(waver);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void stuff() {
// for (int i = 0; i < 1000; i++) {
// panel.add(new paintComponent());
// panel.setBackground(Color.black);
// frame.repaint();
// try {
// Thread.sleep(80);
// } catch (InterruptedException e1) {
// e1.printStackTrace();
// }
// }
waver.walk(!waver.isWaving());
}
public class WavePane extends JComponent {
private int options;
private Timer timer;
public WavePane() {
setOpaque(false);
timer = new Timer(80, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("tick");
options++;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void walk(boolean walk) {
if (walk) {
timer.start();
} else {
timer.stop();
}
}
public boolean isWaving() {
return timer.isRunning();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
int height = getHeight();
if (options % 2 == 0) {
g2.drawOval(50, 100, 50, 50);
g2.drawOval(60, 110, 8, 8);
g2.fillOval(60, 110, 8, 8);
g2.drawOval(80, 110, 8, 8);
g2.fillOval(80, 110, 8, 8);
g2.drawArc(65, 130, 100, 0, 140, 30);
g2.drawLine(75, 150, 75, 220);
g2.drawLine(75, 180, 100, 160);
g2.drawLine(75, 180, 65, 210);
g2.drawLine(75, 220, 50, 260);
g2.drawLine(75, 220, 100, 260);
} else {
g2.drawOval(50, 100, 50, 50);
g2.drawOval(60, 110, 8, 8);
g2.fillOval(60, 110, 8, 8);
g2.drawOval(80, 110, 8, 8);
g2.fillOval(80, 110, 8, 8);
g2.drawArc(65, 130, 100, 0, 140, 30);
g2.drawLine(75, 150, 75, 220);
g2.drawLine(75, 180, 100, 180);
g2.drawLine(75, 180, 65, 210);
g2.drawLine(75, 220, 50, 260);
g2.drawLine(75, 220, 100, 260);
}
}
}
}
You shouldn't be using JFrame.HEIGHT this actually has nothing to do with the frames height, but is part of the ImageObserver support... or any type of magic number for that matter
Related
I tried, adding the flowlayout as seen in other answers, but it still doesn't work.
I've also tried moving around my JLabel code into a constructor but that doesn't work either.
public class Paint {
public static void main(String[] args) {
JFrame frame = new JFrame("Paint");
frame.setSize(500,500);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
Draw draw = new Draw();
frame.add(draw);
frame.setVisible(true);
}
}
public class Draw extends JPanel{
public Draw(){
JLabel one = new JLabel("12",JLabel.CENTER);
setLayout(new FlowLayout());
add(one);
}
public void paint(Graphics g){
g.drawOval(70, 60, 190, 190);
g.setColor(Color.BLACK);
g.drawLine(90, 160, 170, 160);
g.drawLine(120, 190,170 , 160);
g.setColor(Color.GRAY);
g.fillOval(155, 153, 20, 20);
}
}
Change paint to override paintComponent
Call super.paintComponent before doing any custom painting
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Paint {
public static void main(String[] args) {
JFrame frame = new JFrame("Paint");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
Draw draw = new Draw();
frame.add(draw);
frame.setVisible(true);
}
public static class Draw extends JPanel {
public Draw() {
JLabel one = new JLabel("12", JLabel.CENTER);
setLayout(new FlowLayout());
add(one);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(70, 60, 190, 190);
g.setColor(Color.BLACK);
g.drawLine(90, 160, 170, 160);
g.drawLine(120, 190, 170, 160);
g.setColor(Color.GRAY);
g.fillOval(155, 153, 20, 20);
}
}
}
for my program I currently want to use the open button to open a JFileChooser and select an image and then draw it on the JPanel on the left side of the applet, I know that the file is being retrieved but when i go to repaint the graphics context nothing happens. Thanks in advance.
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.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
public class FinalProject390 {
public static void main(String[] args) {
createAndShowGUI();
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Final Project");
f.setSize(1025, 520);
f.add(new GraphicsPanel());
f.add(new MainPanel());
f.setVisible(true);
}
}
class MainPanel extends JPanel implements ActionListener {
JButton openButton = new JButton("Open");
JButton newButton = new JButton("New");
JButton saveButton = new JButton("Save");
JButton saveAsButton = new JButton("Save As");
JButton drawLineButton = new JButton("Draw Line");
JButton drawRectangleButton = new JButton("Draw Rectangle");
JButton drawOvalButton = new JButton("Draw Oval");
JButton drawArcButton = new JButton("Draw Arc");
JButton extractPixelDataButton = new JButton("Extract Pixel Data");
JButton convoluteButton = new JButton("Convolute");
JTextField xPosStartField = new JTextField("x-Position Start");
JTextField yPosStartField = new JTextField("y-Position Start");
JTextField xPosEndField = new JTextField("x-Position End");
JTextField yPosEndField = new JTextField("y-Position End");
JTextField angleStartField = new JTextField("Angle Start");
JTextField angleSizeField = new JTextField("Angle Size");
public MainPanel() {
openButton.setBounds(660, 50, 100, 30);
openButton.addActionListener(this);
newButton.setBounds(780, 50, 100, 30);
saveButton.setBounds(900, 50, 100, 30);
drawLineButton.setBounds(660, 110, 160, 30);
drawRectangleButton.setBounds(840, 110, 160, 30);
drawOvalButton.setBounds(660, 155, 160, 30);
drawArcButton.setBounds(840, 155, 160, 30);
extractPixelDataButton.setBounds(660, 220, 160, 30);
convoluteButton.setBounds(840, 220, 160, 30);
xPosStartField.setBounds(660, 280, 100, 30);
yPosStartField.setBounds(660, 320, 100, 30);
xPosEndField.setBounds(660, 380, 100, 30);
yPosEndField.setBounds(660, 420, 100, 30);
angleStartField.setBounds(900, 280, 100, 30);
angleSizeField.setBounds(900, 320, 100, 30);
setLayout(null);
setBackground(Color.green);
setBounds(641, 0, 370, 480);
add(openButton);
add(newButton);
add(saveButton);
add(drawLineButton);
add(drawRectangleButton);
add(drawOvalButton);
add(drawArcButton);
add(extractPixelDataButton);
add(convoluteButton);
add(xPosStartField);
add(yPosStartField);
add(xPosEndField);
add(yPosEndField);
add(angleStartField);
add(angleSizeField);
}
#Override
public void actionPerformed(ActionEvent e) {
javax.swing.JFileChooser fileChooser = new JFileChooser();
BufferedImage bin = null, bi = null;
GraphicsPanel gPanel = new GraphicsPanel();
fileChooser.setCurrentDirectory(new File(System
.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: "
+ selectedFile.getAbsolutePath());
try {
bin = ImageIO.read(new File(selectedFile.getAbsolutePath()));
} catch (IOException e1) {
e1.printStackTrace();
}
gPanel.setImg(bin);
}
}
}
class GraphicsPanel extends JPanel {
BufferedImage bi = null, bin = null;
public GraphicsPanel() {
setLayout(null);
setBackground(Color.blue);
setSize(640, 480);
setLocation(0, 0);
}
public void setImg(BufferedImage b) {
this.bi = b;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
}
This looks like a homework assignment, so rather than an outright answer with code, instead please consider the following:
In your method createAndShowGUI() you instantiate a GraphicsPanel object and add it to a JFrame
In your actionPerformed() method, you instantiate another GraphicsPanel object (which is never added to the JFrame) and you call setImage().
Your image does not display because the GraphicsPanel control that has been added to your JFrame is not the same GraphicsPanel control that you set the image on.
I hope this will be enough to help you fix your code.
Im trying to make an application that will change the state of a traffic light in the click of a button.
My code: Main
import javax.swing.*;
public class PP416
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Traffic light");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TrafficPanel());
frame.pack();
frame.setVisible(true);
}
}
JPanel Class:
import javax.swing.*;
import java.awt.*;
import java.awt.Event;
public class TrafficPanel extends JPanel
{
private JButton button;
private int indicator = 0; // Light is off
public TrafficPanel()
{
button = new JButton("Change");
this.add(button);
}
public void paint(Graphics g)
{
if (indicator == 0)
{
g.drawOval(30, 40, 30, 30);
g.drawOval(30, 70, 30, 30);
g.drawOval(30, 100, 30, 30);
}
}
}
the button just not appearing , just the ovalls.
anyone can help me with this?
Don't override paint but rather paintComponent and Most important, call the super's method. Your lack of a super call may be preventing your JPanel from drawing its child components well.
e.g.,
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (indicator == 0) {
g.drawOval(30, 40, 30, 30);
g.drawOval(30, 70, 30, 30);
g.drawOval(30, 100, 30, 30);
}
}
I have two classes in my project, Client and Card. When I try to import an image into the Card class, the paintComponent method in the client does not start. The timer still fires, and and outputs after repaint in the timer listener still print. The cause of this problem appears to be the try catch in the constructor of the card.
package card;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Card {
BufferedImage cardImage;
Point loc = new Point(50, 50);
int scale = 1;
public Card(){
try {
cardImage = ImageIO.read(new File("Penguins.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void draw(Graphics2D g2){
g2.setColor(Color.GRAY);
if(cardImage == null)
g2.fillRect(loc.x, loc.y, 150, 225);
else
g2.drawImage(cardImage, loc.x, loc.y, 50, 150, null);
}
}
New class
package core;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import card.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Client extends JPanel {
ArrayList<Card>[] board;
Card card;
Timer timer;
static Client player;
public static void main(String[] args) {
JFrame window = new JFrame("Game");
window.setSize(1080, 720);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
window.setLocation(50, 50);
window.setBackground(Color.GREEN);
player = new Client();
window.setContentPane(player);
}
public Client() {
//board = new ArrayList<Card>[4];
card = new Card();
ActionListener game = new TimerListener();
timer = new Timer(100, game);
timer.start();
}
public class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(5));
g2.drawOval(15, 75, 200, 200);
g2.drawOval(15, 350, 200, 200);
g2.drawRoundRect(355, -10, 450, 60, 15, 15);
g2.drawRoundRect(230, 75, 700, 90, 20, 20);
g2.drawRoundRect(230, 190, 700, 90, 20, 20);
g2.drawRoundRect(230, 350, 700, 90, 20, 20);
g2.drawRoundRect(230, 475, 700, 90, 20, 20);
g2.drawRoundRect(355, 590, 450, 90, 15, 15);
g2.drawRoundRect(950, 75, 90, 90, 10, 10);
g2.drawRoundRect(950, 190, 90, 90, 10, 10);
g2.drawRoundRect(950, 350, 90, 90, 10, 10);
g2.drawRoundRect(950, 475, 90, 90, 10, 10);
card.draw(g2);
}
}
MAJOR EDIT: I have tried a different approach with 1 class and implementation of Runnable to try and print the "moles". I no longer have a second class. The new issue is making the BufferedImage userInterface print at the desired coordinates, then printing "moles" randomly at the correct coordinates. The mole should disappear when the next mole is drawn.
Current Problems:
If the userInterface is alone (no for-loop that is seen below it in the code) then it will appear. If I change the coordinates from 0,0 then it no longer appears.
When I added the for-loop that prints the "moles" (a.k.a mario, hence Whack-A-Mario) then the userInterface ceases to appear at all even if its coords are still 0,0 AND the moles get printed at the random coordinates. The problem here is that the UI no longer appears and the marios keep being printed without the previous ones disappearing.
I am programming a Whack-A-Mole game for my computer programming class, however, I have been having quite a bit of trouble making the images of "moles" appear and disappear.
First, I do not want to use any sort of JButton system for the moles. I have seen it used but I want to use my .png's if possible.
Second, I have concluded that I do not know what I am doing. A major problem is that I also do not really know how to organize the program. The moles will be appearing at a slowly increasing rate and the character will be clicking on the screen. If the user's mouse click is within the area of one of the moles when they are up, the user's score will increase. I have no idea if I should one class or two classes (I have seen people do it in one). I don't exactly know what I am going to do about the updating score either. I want the score to update independently from the repainting of the moles too.
Note: The BufferedImage mario is called mario because I am making "Wack-A-Mario". The moles are images of Mario I drew and the music/effects will all be from Mario. Also please excuse my horrid imports. They have increased over the past couple hours as I tried various things. I no longer know what does what and they will be cleaned up.
Main Class:
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.lang.reflect.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.*;
import javax.swing.Timer;
public class WhackAMario extends JFrame implements Runnable
{
int xCoord[] = new int[] {25, 171, 317, 463, 609, 25, 171, 317, 463, 609, 25, 171, 317, 463, 609, 25, 171, 317, 463, 609};
int yCoord[] = new int[] {275, 275, 275, 275, 275, 395, 395, 395, 395, 395, 515, 515, 515, 515, 515, 635, 635, 635, 635, 635,};
Random coordGen = new Random();
int x,y,element;
BufferedImage userInterface, mario;
private Thread thread;
private static JFrame frame = new JFrame();
private static Graphics g;
private static Graphics2D g2;
public void randomCoord()
{
element = coordGen.nextInt(20);
x = xCoord[element];
y = yCoord[element];
}
public void run()
{
g = frame.getGraphics();
try
{
userInterface = ImageIO.read(new File("UserInterface.png"));
}
catch(IOException e)
{
e.printStackTrace();
}
g.drawImage(userInterface, 0, 0, null);
for(int i=0; i<25; i++)
{
randomCoord();
try
{
mario = ImageIO.read(new File("Mario Up.png"));
}
catch(IOException e)
{
e.printStackTrace();
}
g.drawImage(mario, x, y, null);
try
{
Thread.sleep(1000);
repaint();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
final WhackComponent whackComponent = new WhackComponent();
class Mouse implements MouseListener
{
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(796, 818);
frame.setVisible(true);
WhackAMario whack = new WhackAMario();
whack.thread = new Thread(whack);
whack.thread.start();
MouseListener listener = new Mouse();
frame.addMouseListener(listener);
//Timer t = new Timer(100, whackComponent);
//t.start();
//
// ImageIcon img = new ImageIcon("Hole.png");
// JLabel label1 = new JLabel(img);
// JPanel panel = new JPanel();
// panel.setLayout(null);
//
// label1.setLocation(400, 400);
//frame.add(label1);
//frame.setVisible(true);
}
}
Main Class Before "MAJOR EDIT"
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.lang.reflect.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.*;
import javax.swing.Timer;
public class WhackAMario extends JFrame implements Runnable
{
int xCoord[] = new int[] {25, 171, 317, 463, 609, 25, 171, 317, 463, 609, 25, 171, 317, 463, 609, 25, 171, 317, 463, 609};
int yCoord[] = new int[] {275, 275, 275, 275, 275, 395, 395, 395, 395, 395, 515, 515, 515, 515, 515, 635, 635, 635, 635, 635,};
Random coordGen = new Random();
int x,y,element;
BufferedImage userInterface, mario;
private Thread thread;
private static JFrame frame = new JFrame();
private static Graphics g;
private static Graphics2D g2;
public void randomCoord()
{
element = coordGen.nextInt(20);
x = xCoord[element];
y = yCoord[element];
}
public void run()
{
g = frame.getGraphics();
// try
// {
// userInterface = ImageIO.read(new File("UserInterface.png"));
// }
// catch(IOException e)
// {
// e.printStackTrace();
// }
// g.drawImage(userInterface, 0, 50, null);
// for(int i=0; i<25; i++)
// {
// randomCoord();
// try
// {
// mario = ImageIO.read(new File("Mario Up.png"));
// }
// catch(IOException e)
// {
// e.printStackTrace();
// }
// g.drawImage(mario, x, y, null);
// try
// {
// Thread.sleep(1000);
// repaint();
// }
// catch (InterruptedException e)
// {
// e.printStackTrace();
// }
// }
}
public static void main(String[] args)
{
final WhackComponent whackComponent = new WhackComponent();
class Mouse implements MouseListener
{
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(796, 818);
frame.setVisible(true);
frame.add(whackComponent);
// WhackAMario whack = new WhackAMario();
// whack.thread = new Thread(whack);
// whack.thread.start();
MouseListener listener = new Mouse();
frame.addMouseListener(listener);
//Timer t = new Timer(100, whackComponent);
//t.start();
//
// ImageIcon img = new ImageIcon("Hole.png");
// JLabel label1 = new JLabel(img);
// JPanel panel = new JPanel();
// panel.setLayout(null);
//
// label1.setLocation(400, 400);
//frame.add(label1);
//frame.setVisible(true);
}
}
Component Class:
import java.awt.*;
import javax.swing.*;
import java.util.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.concurrent.TimeUnit;
public class WhackComponent extends JComponent
{
int xCoord[] = new int[] {25, 171, 317, 463, 609, 25, 171, 317, 463, 609, 25, 171, 317, 463, 609, 25, 171, 317, 463, 609};
int yCoord[] = new int[] {275, 275, 275, 275, 275, 395, 395, 395, 395, 395, 515, 515, 515, 515, 515, 635, 635, 635, 635, 635,};
BufferedImage userInterface, mario;
Random coordGen = new Random();
Thread thread;
int element;
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
try
{
userInterface = ImageIO.read(new File("UserInterface.png"));
}
catch(IOException e)
{
e.printStackTrace();
}
g2.drawImage(userInterface, null, 0, 0);
for(int i=0; i<25; i++)
{
element = coordGen.nextInt(20);
try
{
mario = ImageIO.read(new File("Mario Up.png"));
}
catch(IOException e)
{
e.printStackTrace();
}
g2.drawImage(mario, null, xCoord[element], yCoord[element]);
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public void enterMove()
{
}
public void releaseMove()
{
}
public void actionPerformed(ActionEvent event)
{
}
}
It's supposed to work this way: you provide the drawing logic inside paintComponent(Graphics) and the system will call you back when it detects the screen needs to be refreshed. In Swing applications the trigger is tipically the user interacting with the computer, for example by pressing a key or clicking the mouse, while in your application you need a game engine with its own main loop, that shows/hides moles, interacts with the music engine and processes input events depending on the state of the world. In Swing, layout hierarchies are invalidated with a call to .invalidate().
Note that JButton's and others Swing components are just a convenient way for you to draw things (especially wrt screen size with the help of layout managers) and process events, but you can certainly program a simple game by using a single JComponent like in your example (I think this may help)
Random tip: paintComponent must be fast, and I mean really fast, so you can't read a PNG from the filesystem and convert it to a bitmap. The loading must occur exactly one time when the game is initialized