JComponent not draggable under GridBagConstraints - java

I'm currently making a puzzle game, my design is to have the puzzle(a 3*3 Board)show up on top, and my nine pieceComponents on the bottom in a row as my original state, I want to be able to drag my pieceComponents on to the board so I have them in side the same JPanel. I was suggested to use GridBagConstraints for this to happen, however, for my puzzle board this is a giant space on top, and only the last PieceComponent I added to the screen shows up, also the I believe it is the GridBagConstraints that prevented me from using my mouse to drag the PieceComponents(which I have made draggable),
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
public class Display extends JComponent {
private PuzzleDisplay puzzle;
private JFrame frame;
private static List<PieceComponent> pieces = new ArrayList<PieceComponent>();
private JPanel puzzlePanel;
private GridBagConstraints gbc = new GridBagConstraints();
/**
* Launch the application.
*/
public static void main(String[] args) {
Display d = new Display();
d.GUI();
}
/**
* Create the application.
*/
public Display() {
puzzle = new PuzzleDisplay();
}
private void PuzzlePanel() {
puzzlePanel = new JPanel();
puzzlePanel.setLayout(new GridBagLayout());
gbc.gridx=0;
gbc.gridy =0;
puzzlePanel.add(puzzle, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
puzzlePanel.add(puzzle.getPieces().get(0), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
puzzlePanel.add(puzzle.getPieces().get(0), gbc);
gbc.gridx = 2;
gbc.gridy = 1;
puzzlePanel.add(puzzle.getPieces().get(0), gbc);
gbc.gridx = 3;
gbc.gridy = 1;
puzzlePanel.add(puzzle.getPieces().get(0), gbc);
puzzlePanel.setVisible(true);
}
public void GUI() {
frame = new JFrame("Puzzle");
frame.setVisible(true);
frame.setSize(850, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PuzzlePanel();
frame.add(puzzlePanel, BorderLayout.CENTER);
}
}
this is my PieceComponent class, I made it draggable.
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Component;
public class PieceComponent extends JComponent {
private Piece piece;
private BufferedImage myImage;
private volatile int screenX = 0;
private volatile int screenY = 0;
private volatile int myX = 0;
private volatile int myY = 0;
public PieceComponent(Side top, Side right, Side bottom, Side left, String path) {
piece = new Piece(top, right, bottom, left);
try {
myImage = ImageIO.read((new FileInputStream(path)));
} catch (IOException exp) {
exp.printStackTrace();
}
addMouseListener(new MouseListener() {
#Override
public void mousePressed(MouseEvent e) {
screenX = e.getXOnScreen();
screenY = e.getYOnScreen();
myX = getX();
myY = getY();
}
#Override
public void mouseClicked(MouseEvent e) {
piece.rotateClockwise();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
int deltaX = e.getXOnScreen() - screenX;
int deltaY = e.getYOnScreen() - screenY;
setLocation(myX + deltaX, myY + deltaY);
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
//returns the chosen side
public Side getSide(Direction direction) {
return piece.getSide(direction);
}
public Piece getPiece() {
return piece;
}
public int getHeight() {
return myImage.getHeight();
}
public int getWidth() {
return myImage.getWidth();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (myImage != null) {
AffineTransform trans = new AffineTransform();
trans.translate(getWidth() / 2, getHeight() / 2);
trans.rotate(piece.getOrientation() * Math.PI / 2);
trans.translate(-myImage.getWidth() / 2, -myImage.getHeight() / 2);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(myImage, trans, null);
}
}
public void rotateClockwise() {
piece.rotateClockwise();
}
This is my PuzzleDisplay
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
public class PuzzleDisplay extends JComponent{
private Puzzle puzzle;
private JFrame frame;
private List<PieceComponent> pieceComponents = new ArrayList<PieceComponent>();
private List<Piece> pieces = new ArrayList<Piece>();
/**
* Create the application.
*/
public PuzzleDisplay() {
pieceComponents.add(new PieceComponent(Side.SPADE_OUT, Side.HEART_OUT, Side.DIAMOND_IN, Side.SPADE_IN, "res/piece_1.png"));
pieceComponents.add(new PieceComponent(Side.CLUB_OUT, Side.DIAMOND_OUT, Side.CLUB_IN, Side.HEART_IN, "res/piece_2.png"));
pieceComponents.add(new PieceComponent(Side.HEART_OUT, Side.CLUB_OUT, Side.CLUB_IN, Side.SPADE_IN, "res/piece_3.png"));
pieceComponents.add(new PieceComponent(Side.CLUB_OUT, Side.DIAMOND_OUT, Side.SPADE_IN, Side.SPADE_IN, "res/piece_4.png"));
pieceComponents.add(new PieceComponent(Side.CLUB_OUT, Side.CLUB_OUT, Side.HEART_IN, Side.SPADE_IN, "res/piece_5.png"));
pieceComponents.add(new PieceComponent(Side.HEART_OUT, Side.DIAMOND_OUT, Side.DIAMOND_IN, Side.HEART_IN, "res/piece_6.png"));
pieceComponents.add(new PieceComponent(Side.CLUB_OUT, Side.DIAMOND_OUT, Side.HEART_IN, Side.DIAMOND_IN, "res/piece_7.png"));
pieceComponents.add(new PieceComponent(Side.SPADE_OUT, Side.HEART_OUT, Side.CLUB_IN, Side.HEART_IN, "res/piece_8.png"));
pieceComponents.add(new PieceComponent(Side.DIAMOND_OUT, Side.SPADE_OUT, Side.SPADE_IN, Side.DIAMOND_IN, "res/piece_9.png"));
for(int i=0; i<pieceComponents.size(); i++) {
pieces.add(pieceComponents.get(i).getPiece());
}
puzzle = new Puzzle(3, pieces);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int imageSize = pieceComponents.get(0).getHeight();
int boardBuffer = (getWidth()-3*imageSize)/2;
for(int i=0; i<puzzle.getCols(); i++) {
for(int j=0; j<puzzle.getRows(); j++) {
g2d.drawRect(i*imageSize, j*imageSize, imageSize, imageSize);
}
}
}
//returns the list of all pieces
public List<PieceComponent> getPieces(){
return pieceComponents;
}
//Fills the puzzle with the correct solution
public void solve() {
puzzle.solve();
}
//Determines whether the puzzle has been completed
public boolean isSolved() {
return puzzle.isSolved();
}
//Determines whether a piece will fit at the specified
//location
public boolean doesFit(PieceComponent pc, int row, int col) {
return puzzle.doesFit(pc.getPiece(), row, col);
}
//returns the Piece at the specified location
public Piece getPiece(int row, int col) {
return puzzle.getPiece(row, col);
}
//replaces a Piece at the given location and returns the old Piece
public Piece setPiece(Piece piece, int row, int col) {
return puzzle.setPiece(piece, row, col);
}
//removes and returns the Piece at the given location
public Piece removePiece(int row, int col) {
return removePiece(row, col);
}
//Clears the board and puts all pieces back into the piece list
public void reset() {
puzzle.reset();
}
//returns a List of any pieces not already on the board
public List<Piece> getUnused(){
return puzzle.getUnused();
}
//returns the number of rows
public int getRows() {
return puzzle.getRows();
}
//returns the number of columns
public int getCols() {
return puzzle.getCols();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(pieceComponents.get(0).getHeight()*3, pieceComponents.get(0).getHeight()*3);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
PuzzleDisplay d = new PuzzleDisplay();
JFrame frame = new JFrame("Puzzle");
frame.setVisible(true);
frame.setSize(1250, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(d);
}
}

Related

Setting up javax.swing.Timer

Ok I'm doing a project and the image is supposed to move around randomly and when the user clicks on the image it's supposed to count how many times the click on it. From there on it keeps moving until they x out. However, I made the mistake of making the image move AFTER they click on it, so when the program starts the image isn't already moving. I need it to move from the beginning of the program.
Attached here because for whatever reason, stack overflow keeps saying I formatted wrong.
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
// Zombie class
public class Zombie {
//declare variables
private int x;
private int y;
private int size;
private Image image;
//constructor
public Zombie(int xIn, int yIn, String imagePath) {
x = xIn;
y = yIn;
size = Settings.DEFAULT_SIZE;
setImage(imagePath);
}
//getter for x
public int getX() {
return x;
}
//getter for y
public int getY() {
return y;
}
//setter for x
public void setX(int x) {
this.x = x;
}
//setter for y
public void setY(int y) {
this.y = y;
}
//drawImage method
public void update(Graphics g) {
g.drawImage(image, x, y, size, size, null);
}
//try catch exception, if image isn't found
public void setImage(String imagePath) {
try {
image = ImageIO.read(new File(imagePath));
} catch (IOException ioe) {
System.out.println("Unable to load image file.");
}
}
}
public class Settings {
//adjusts the width and height of the creature
public static final int WIDTH = 500;
public static final int HEIGHT = 300;
public static final int DEFAULT_SIZE = 50;
//image name
public static final String ZOMBIE_IMAGE = "zombie.png";
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.util.Random;
class Controller implements MouseListener {
//declares variables
Zombie zombie;
View view;
private int count = 0;
Controller() {
//System.out.println ("Controller()");
}
public void addZombie(Zombie z){
//System.out.println("Controller: adding zombie");
this.zombie = z;
}
public void addView(View v){
//System.out.println("Controller: adding view");
this.view = v;
}
public void mousePressed(MouseEvent e) {
//System.out.println("Controller sees mouse pressed: acting on Model");
int prevX = e.getX();
int prevY = e.getY();
prevX -= zombie.getX();
prevY -= zombie.getY();
if((prevX > 0 && prevX < Settings.DEFAULT_SIZE) &&
(prevY > 0 && prevY < Settings.DEFAULT_SIZE)) {
//System.out.println("Got Zombie.");
Random r = new Random();
zombie.setX(r.nextInt(view.getWidth() - Settings.DEFAULT_SIZE));
zombie.setY(r.nextInt(view.getHeight() - Settings.DEFAULT_SIZE));
++count;
}
}
public int getCount() {
return count;
}
//mouse events
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void update(Graphics g) {
zombie.update(g);
}
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.util.Random;
public class View implements ActionListener {
private JFrame frame;
Controller controller;
public static void main(String[] args) {
Zombie zombie = new Zombie(Settings.WIDTH/2, Settings.HEIGHT/2, Settings.ZOMBIE_IMAGE);
View view = new View();
Controller myController = new Controller();
myController.addZombie(zombie);
myController.addView(view);
view.addController(myController);
new Timer(500, view).start();
}
private class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
controller.update(g);
revalidate();
}
}
private MyPanel panel;
View() {
//System.out.println("View()");
frame = new JFrame("Catch The Zombie");
// Create a panel to contain a label, a text box, and a button
panel = new MyPanel();
frame.add(panel);
frame.setSize(Settings.WIDTH, Settings.HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
// TODO Auto-generated method stub
System.out.println("Zombie was caught " + controller.getCount() + "times");
}
});
}
public void revalidate() {
}
public void addController(Controller controller){
//System.out.println("View : adding controller");
this.controller = controller;
frame.getContentPane().addMouseListener((MouseListener) controller);
}
public int getWidth() {
return frame.getWidth();
}
public int getHeight() {
return frame.getHeight();
}
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
}

Mouse listener not working with JPanel

The paintcomponent works fine, the image shows up, no problems on that end or with the JFrame. I want to implement zooming and panning but not getting any luck as the added mouse listener isn't responding.
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class map extends JPanel {
public int moz = 100;
public void map()
{
addMouseListener(
new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
moz = moz +100;
repaint();
}
}
);
}
public void paintComponent(Graphics g){
.....
g.drawLine( 0, moz, 100, 0 );
}
}
Your class doesn't have a real constructor but rather has a "pseudo" constructor since it has a return type -- yes void counts. So get rid of the void return type by changing:
// this is not a constructor
public void map()
to:
// this is a real constructor
public map()
Also as a side recommendation, change your variable and class names to conform with Java naming conventions: class names all start with an upper-case letter and method/variable names with a lower-case letter.
So in your case you'd name your class Map, and in playing with the code could have something like:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class Map extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private static final Color DRAW_RECT_COLOR = new Color(200, 200, 255);
public static final Stroke IMAGE_STROKE = new BasicStroke(3f);
public static final Color IMAGE_COLOR = Color.RED;
private BufferedImage image = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
private Rectangle drawRectangle = null;
private List<Color> colors = new ArrayList<>();
private Random random = new Random();
public Map() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
for (int r = 0; r < 4; r++) {
int r1 = (r * 255) / 3;
for (int g = 0; g < 4; g++) {
int g1 = (g * 255) / 3;
for (int b = 0; b < 4; b++) {
int b1 = (b * 255) / 3;
colors.add(new Color(r1, g1, b1));
}
}
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
Graphics2D g2 = (Graphics2D) g;
if (drawRectangle != null) {
g.setColor(DRAW_RECT_COLOR);
g2.draw(drawRectangle);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouse extends MouseAdapter {
Point p1 = null;
#Override
public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent e) {
if (p1 == null) {
return;
}
Point p2 = e.getPoint();
drawRectangle = createDrawRect(p2);
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
Rectangle rectangle = createDrawRect(e.getPoint());
Graphics2D g2 = image.createGraphics();
g2.setStroke(IMAGE_STROKE);
Color c = colors.get(random.nextInt(colors.size()));
g2.setColor(c);
g2.draw(rectangle);
g2.dispose();
p1 = null;
drawRectangle = null;
repaint();
}
private Rectangle createDrawRect(Point p2) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int w = Math.abs(p1.x - p2.x);
int h = Math.abs(p1.y - p2.y);
return new Rectangle(x, y, w, h);
}
}
private static void createAndShowGui() {
Map mainPanel = new Map();
JFrame frame = new JFrame("Map");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

ConvertPoint Java Does Not Work [duplicate]

newbie programmer here.
I'm making a program that renders user-inputted equations in a Cartesian coordinate system. At the moment I'm having some issues with letting the user move the view around freely in the coordinate. Currently with mouseDragged the user can drag the view around a bit, but once the user releases the mouse and tries to move the view again the origin snaps back to the current position of the mouse cursor. What is the best way to let the user move around freely? Thanks in advance!
Here's the code for the drawing area.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JPanel;
public class DrawingArea extends JPanel implements MouseMotionListener {
private final int x_panel = 350; // width of the panel
private final int y_panel = 400; // height of the panel
private int div_x; // width of one square
private int div_y; // height of one square
private int real_y;
private int real_x;
private Point origin; // the origin of the coordinate
private Point temp; // temporary point
private static int y = 0;
private static int x = 0;
DrawingArea() {
setBackground(Color.WHITE);
real_x = x_panel;
real_y = y_panel;
setDivisionDefault();
setOrigin(new Point((real_x / 2), (real_y / 2)));
setSize(x_panel, y_panel);
addMouseMotionListener(this);
}
DrawingArea(Point origin, Point destination) {
this.origin = origin;
this.destination = destination;
panel = new JPanel();
panel.setSize(destination.x, destination.y);
panel.setLocation(origin);
this.panel.setBackground(Color.red);
panel.setLayout(null);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D line = (Graphics2D) g;
temp = new Point(origin.x, origin.y);
line.setColor(Color.red);
drawHelpLines(line);
line.setColor(Color.blue);
drawOrigin(line);
line.setColor(Color.green);
for (int i = 0; i < 100; i++) { // This is a test line
//temp = this.suora();
temp.x++;
temp.y++;
line.drawLine(temp.x, temp.y, temp.x, temp.y);
}
}
public void setOrigin(Point p) {
origin = p;
}
public void drawOrigin(Graphics2D line) {
line.drawLine(origin.x, 0, origin.x, y_panel);
line.drawLine(0, origin.y, x_panel, origin.y);
}
public void drawHelpLines(Graphics2D line) {
int xhelp= origin.x;
int yhelp= origin.y;
for (int i = 0; i < 20; i++) {
xhelp+= div_x;
line.drawLine(xhelp, 0, xhelp, y_panel);
}
xhelp= origin.x;
for (int i = 0; i < 20; i++) {
xhelp-= div_x;
line.drawLine(xhelp, 0, xhelp, y_panel);
}
for (int i = 0; i < 20; i++) {
yhelp-= div_y;
line.drawLine(0, yhelp,x_panel, yhelp);
}
yhelp= origin.y;
for (int i = 0; i < 20; i++) {
yhelp+= div_y;
line.drawLine(0, yhelp, x_panel, yhelp);
}
}
public void setDivisionDefault() {
div_x = 20;
div_y = 20;
}
#Override
public void mouseDragged(MouseEvent e) {
//Point temp_point = new Point(mouse_x,mouse_y);
Point coords = new Point(e.getX(), e.getY());
setOrigin(coords);
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
Based on this example, the following program allows the user to drag the axes' intersection to an arbitrary point, origin, which starts at the center of the panel.
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* #see https://stackoverflow.com/a/15576413/230513
* #see https://stackoverflow.com/a/5312702/230513
*/
public class MouseDragTest extends JPanel {
private static final String TITLE = "Drag me!";
private static final int W = 640;
private static final int H = 480;
private Point origin = new Point(W / 2, H / 2);
private Point mousePt;
public MouseDragTest() {
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mousePt = e.getPoint();
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
int dx = e.getX() - mousePt.x;
int dy = e.getY() - mousePt.y;
origin.setLocation(origin.x + dx, origin.y + dy);
mousePt = e.getPoint();
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0, origin.y, getWidth(), origin.y);
g.drawLine(origin.x, 0, origin.x, getHeight());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame(TITLE);
f.add(new MouseDragTest());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}

Simple Java game draws only half window

I can not figure out why the game is only drawing only on half the window I make.
I add in actionPerformed to always implement to y position and it goes only on half the window , then the images stopes.
Main
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Main extends JFrame{
public static void main(String[]args){
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame ex = new Main();
ex.setVisible(true);
}
});
}
public Main(){
setTitle("Maze");
add(new Game());
pack();
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Game
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener {
private final int GWIDTH = 400;
private final int GHEIGHT = 400;
private int GAME_DELAY = 10;
private Timer timer;
private Image player;
/*Player*/
private final int spawnPosition = 0;
int playerX = 0;
int playerY = spawnPosition;
/*Mouse*/
private Mouse m;
public Game(){
setFocusable(true);
setPreferredSize(new Dimension(GWIDTH, GHEIGHT));
addMouseListener(new Mouse());
initTime();
//Importam poza
loadPlayer();
//Mouse
m = new Mouse();
}
private void initTime(){
timer = new Timer(GAME_DELAY, this);
timer.start();
}
private void loadPlayer(){
ImageIcon img = new ImageIcon("smiley.png");
player = img.getImage();
}
public int getX(){ return playerX; }
public int getY() { return playerY; }
private void drawPlayer(Graphics2D g2d){
g2d.drawImage(player,getX(),getY(),null);
Toolkit.getDefaultToolkit().sync();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawPlayer(g2d);
g2d.dispose();
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
playerY += 1;
repaint();
}
}
Image

adding background pic to JFrame

I'm trying to follow this answer to add a background picture to a JFrame and I'm getting a weird error. While debugging my url is coming back null and I get a window that pops up saying "Class File Editor" source not found the source attachment does not contain the source for the file Launcher.class you can change the source attachment by clicking Chang Attached Source below. What does that mean?
here's the code that I have so far:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class DeluxKenoMainWindow extends JFrame
{
public DeluxKenoMainWindow()
{
initUI();
}
public final void initUI()
{
setLayout(null);
getContentPane().add(new BackgroundImage());
int xCoord = 10;
int yCoord = 10;
Button[] button = new Button[80];
for(int i = 0; i<80; i++)
{
String buttonName = "button" + i;
if(i % 10 == 0)
{
xCoord = 10;
yCoord +=40;
}
xCoord += 40;
if(i % 40 == 0)
yCoord += 8;
button[i] = new Button(buttonName, xCoord, yCoord, i+1);
getContentPane().add(button[i]);
}
setTitle("Delux Keno");
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
System.setProperty("DEBUG_UI", "true");
DeluxKenoMainWindow ex = new DeluxKenoMainWindow();
ex.setVisible(true);
}
});
}
}
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.io.*;
public class Button extends JButton {
private String name;
private int xCoord;
private int yCoord;
private final int xSize = 40;
private final int ySize = 40;
private int buttonNumber;
private String picture;
public Button(String inName, int inXCoord, int inYCoord, int inButtonNumber)
{
xCoord = inXCoord;
yCoord = inYCoord;
buttonNumber = inButtonNumber;
picture = "graphics\\" + buttonNumber + "normal.png";
super.setName(name);
super.setIcon(new ImageIcon(picture));
super.setBounds(xCoord, yCoord, xSize, ySize);
}
}
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class BackgroundImage extends JPanel{
private BufferedImage img;
private URL rUrl;
public BackgroundImage()
{
super();
try{
rUrl = getClass().getResource("formBackground.png");
img = ImageIO.read(rUrl);
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g)
{
//super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
any sugesstions will be appriciated!!
set classpath by #Gagandeep Bali
don't perform any FileIO in paintComponent, load this image one time as local variable, pass variable in paintComponent
for Bingo, Minesweaper to use JToggleButton instead of JButton
went at it a different way, using a JLabel. Here's my final code:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class DeluxKenoMainWindow extends JFrame
{
public DeluxKenoMainWindow()
{
initUI();
}
public final void initUI()
{
setLayout(null);
JLabel background = new JLabel(new ImageIcon ("graphics\\formBackground.png"));
background.setBounds(0,0,600,600);
//getContentPane().add(new BackgroundImage());
int xCoord = 85;
int yCoord = 84;
Button[] button = new Button[80];
for(int i = 0; i<80; i++)
{
String buttonName = "button" + i;
if(i % 10 == 0)
{
xCoord = 12;
yCoord +=44;
}
if(i % 40 == 0)
yCoord += 10;
button[i] = new Button(buttonName, xCoord, yCoord, i+1);
xCoord += 42;
getContentPane().add(button[i]);
}
add(background);
setTitle("Delux Keno");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
System.setProperty("DEBUG_UI", "true");
DeluxKenoMainWindow ex = new DeluxKenoMainWindow();
ex.setVisible(true);
}
});
}
}
another problem I found is that you need to use setBounds() for the JPanel for it to have any size. To do it the first way I tried this is the updated BackgroundImage class:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class BackgroundImage extends JPanel{
private BufferedImage img;
private URL rUrl;
public BackgroundImage()
{
super();
try{
rUrl = getClass().getResource("formBackground.png");
img = ImageIO.read(rUrl);
}
catch(IOException ex)
{
ex.printStackTrace();
}
super.setBounds(0,0,600,600);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}

Categories