I created a Class with JPanel extended to it. Then when I created an object of it and added to an existing JPanel, it doesn't show up. What am I doing wrong here?
public class StartTower extends JPanel{
private int value;
public StartTower(int value){
this.value = value;
}
public static StartTower send(int value){
return new StartTower(value);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(752, 359);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(120, 60, 10, 270);
g.fillRect(20, 330, 210, 10);
g.fillRect(375, 60, 10, 270);
g.fillRect(275, 330, 210, 10);
g.fillRect(630, 60, 10, 270);
g.fillRect(530, 330, 210, 10);
int val1 = 20;
int val2 = 315;
int val3 = 210;
int col = 100;
for (int i = 0; i < value; i++) {
g.setColor(new Color(100, col, 100));
g.fillRect(val1, val2, val3, 15);
System.out.println(val1 + " " + val2 + " " + val3 + " " + col);
val1 += 10;
val2 -= 15;
val3 -= 20;
col -= 10;
}
}
}
Class with JPanel extended
private void startBtActionPerformed(java.awt.event.ActionEvent evt) {
//mainPanel.repaint();
name = javax.swing.JOptionPane.showInputDialog(rootPane, "Enter you name!", "Ready?", WIDTH);
if (name != null) {
clockFunc(true);
game.initialDisk((int) disksSpinner.getValue());
StartTower startTower = new StartTower((int) disksSpinner.getValue());
mainPanel.setLayout(null);
this.add(startTower);
a2bBt.setEnabled(true);
a2cBt.setEnabled(true);
b2aBt.setEnabled(true);
b2cBt.setEnabled(true);
c2aBt.setEnabled(true);
c2bBt.setEnabled(true);
optimumLabel.setText(getNoOfOptimumMoves((int) disksSpinner.getValue()));
disksSpinner.setEnabled(false);
startBt.setEnabled(false);
}
}
Method where I made the object of the before said class and added it to the existing JPanel. (mainPanel is the existing JPanel created using drag drop in NetBeans).
Why isn't this showing up? What's wrong in the code? Thanks in advance!
I'm not sure what's your complete code, but I just tried this and it works fine:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class StartTower extends JPanel
{
private int value;
public StartTower(int value)
{
this.value = value;
}
public static StartTower send(int value)
{
return new StartTower(value);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(752, 359);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.fillRect(120, 60, 10, 270);
g.fillRect(20, 330, 210, 10);
g.fillRect(375, 60, 10, 270);
g.fillRect(275, 330, 210, 10);
g.fillRect(630, 60, 10, 270);
g.fillRect(530, 330, 210, 10);
int val1 = 20;
int val2 = 315;
int val3 = 210;
int col = 100;
for (int i = 0; i < value; i++)
{
g.setColor(new Color(100, col, 100));
g.fillRect(val1, val2, val3, 15);
System.out.println(val1 + " " + val2 + " " + val3 + " " + col);
val1 += 10;
val2 -= 15;
val3 -= 20;
col -= 10;
}
}
private static void createAndShowGUI()
{
StartTower startTower = new StartTower(5);
JFrame jFrame = new JFrame();
JPanel jPanel = new JPanel();
jPanel.add(startTower);
jFrame.getContentPane().add(jPanel);
jFrame.pack();
jFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If you are going to use null layout, which I don't recommend, then before you add a component you have to set its bounds so the null layout knows where to put it.
Doing without a layout
Related
So I'm new at java and need some help with my breakout game. My JFrame is just blank and i don't know how to fix it?
So I have a ball class, paddle class, canvas class and a brick class as well as a main class. In my canvas class I set all functions the ball, paddle and bricks has etc. In brick class I draw the bricks. And in my main I do the JFrame but it's blank
Main class :
public class Main {
public static void main(String[] args){
JFrame frame = new JFrame();
Canvas c = new Canvas();
frame.add(c);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I expect the JFrame to show the game instead of just blank window
package breakout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.KeyEvent;
import breakout.Bricks.Type;
public class Canvas extends JPanel implements ActionListener, MouseMotionListener, MouseListener, KeyListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int HEIGHT = 600;
public static final int WIDTH = 720;
private int horizontalCount;
private BufferedImage image;
private Graphics2D bufferedGraphics;
private Timer time;
private static final Font endFont = new Font(Font.SANS_SERIF, Font.BOLD, 20);
private static final Font scoreFont = new Font(Font.SANS_SERIF, Font.BOLD, 15);
private Paddle player;
private Ball ball;
ArrayList<ArrayList<Bricks>> bricks;
public Canvas() {
super();
setPreferredSize( new Dimension(WIDTH, HEIGHT));
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
bufferedGraphics = image.createGraphics();
time = new Timer (15, this);
player = new Paddle((WIDTH/2)-(Paddle.PADDLE_WIDTH/2));
ball = new Ball (((player.getX() + (Paddle.PADDLE_WIDTH / 2 )) - (Ball.DIAMETER / 2)), (Paddle.Y_POS - (Ball.DIAMETER + 10 )), -5, -5);
bricks = new ArrayList<ArrayList<Bricks>>();
horizontalCount = WIDTH / Bricks.BRICK_WIDTH;
for(int i = 0; i < 8; ++i) {
ArrayList<Bricks> temp = new ArrayList<Bricks>();
#SuppressWarnings("unused")
Type rowColor = null;
switch(i) {
case 0 :
case 2:
rowColor = Type.LOW;
break;
case 1 :
case 3 :
case 5 :
rowColor = Type.MEDIUM;
break;
case 4 :
case 6 :
rowColor = Type.HIGH;
break;
case 7 :
default :
rowColor = Type.ULTRA;
break;
}
for(int j = 0; j < horizontalCount; ++j) {
Bricks tempBrick = new Bricks();
temp.add(tempBrick);
}
bricks.add(temp);
addMouseMotionListener(this);
addMouseListener(this);
addKeyListener(this);
requestFocus();
}
}
public void actionPerformed(ActionEvent e) {
checkCollisions();
ball.Move();
for(int i = 0; i < bricks.size(); ++i) {
ArrayList<Bricks> al = bricks.get(i);
for(int j = 0; j < al.size(); ++j) {
Bricks b = al.get(j);
if(b.dead()) {
al.remove(b);
}
}
}
repaint();
}
private void checkCollisions() {
if(player.hitPaddle(ball)) {
ball.setDY(ball.getDY() * -1);
return;
}
if(ball.getX() >= (WIDTH - Ball.DIAMETER) || ball.getX() <= 0) {
ball.setDX(ball.getDX() * -1);
}
if(ball.getY() > (Paddle.Y_POS + Paddle.PADDLE_HEIGHT + 10)) {
resetBall();
}
if(ball.getY() <= 0) {
ball.setDY(ball.getDY() * -1);
}
int brickRowActive = 0;
for(ArrayList<Bricks> alb : bricks) {
if(alb.size() == horizontalCount) {
++brickRowActive;
}
}
for(int i = (brickRowActive==0) ? 0 : (brickRowActive - 1); i < bricks.size(); ++i) {
for(Bricks b : bricks.get(i)) {
if(b.hitBy(ball)) {
player.setScore(player.getScore() + b.getBrickType().getPoints());
b.decrementType();
}
}
}
}
private void resetBall() {
if(gameOver()) {
time.stop();
return;
}
ball.setX(WIDTH/2);
ball.setDY((HEIGHT/2) + 80);
player.setLives(player.getLives() -1);
player.setScore(player.getScore() <= 1);
}
private boolean gameOver() {
if(player.getLives() <= 1) {
return true;
}
return false;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
bufferedGraphics.clearRect(0, 0, WIDTH, HEIGHT);
player.drawPaddle(bufferedGraphics);
player.drawBall(bufferedGraphics);
for(ArrayList<Bricks> row : bricks) {
for(Bricks b : row) {
b.drawBrick(bufferedGraphics);
}
}
bufferedGraphics.setFont(scoreFont);
bufferedGraphics.drawString("Score: " + player.getScore(), 10, 25);
if(gameOver() && ball.getY() >= HEIGHT) {
bufferedGraphics.setColor(Color.black);
bufferedGraphics.setFont(endFont);
bufferedGraphics.drawString("Game Over Score: " + player.getScore(), (WIDTH /2) -85, (HEIGHT/2));
}
if(empty()) {
bufferedGraphics.setColor(Color.black);
bufferedGraphics.setFont(endFont);
bufferedGraphics.drawString("You won. Score: " + player.getScore(), (WIDTH /2) -85, (HEIGHT /2));
time.stop();
}
g.drawImage(image, 0, 0, this);
Toolkit.getDefaultToolkit().sync();
}
private boolean empty() {
for(ArrayList<Bricks> al : bricks) {
if(al.size() != 0) {
return false;
}
}
return true;
}
#Override
public void mouseMoved(MouseEvent e) {
player.setX(e.getX() - (Paddle.PADDLE_WIDTH / 2));
}
#Override
public void mouseClicked(MouseEvent e) {
if(time.isRunning()) {
return;
}
time.start();
}
#Override
public void mouseDragged(MouseEvent e) { }
#Override
public void mouseEntered(MouseEvent arg0) {}
#Override
public void mouseExited(MouseEvent arg0) {}
#Override
public void mousePressed(MouseEvent arg0) {}
#Override
public void mouseReleased(MouseEvent arg0) {}
#Override
public void keyPressed(KeyEvent arg0) {}
#Override
public void keyReleased(KeyEvent arg0) {}
#Override
public void keyTyped(KeyEvent arg0) {}
}
Preparing an MCVE, as required in SO, not only it makes helping much easier.
In many case, while preparing one, you are likely to find the problem, so it is a good debugging tool.
To answer "why is my JFrame blank ?" you could create the minimal code example like the following (copy-paste the entire code into GameBoard.java and run):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameBoard extends JPanel {
static final int HEIGHT = 600, WIDTH = 720, BRICK_ROWS = 8;
private final int horizontalCount;
private static final Font scoreFont = new Font(Font.SANS_SERIF, Font.BOLD, 15);
private final Paddle player;
private final Ball ball;
ArrayList<ArrayList<Brick>> bricks;
public GameBoard() {
super();
setPreferredSize( new Dimension(WIDTH, HEIGHT));
player = new Paddle(WIDTH/2-Paddle.PADDLE_WIDTH/2);
ball = new Ball (player.getX() + Paddle.PADDLE_WIDTH / 2 - Ball.DIAMETER / 2,
Paddle.Y_POS - (Ball.DIAMETER + 10 ));
bricks = new ArrayList<>();
horizontalCount = WIDTH / Brick.BRICK_WIDTH;
for(int i = 0; i < BRICK_ROWS; ++i) {
ArrayList<Brick> temp = new ArrayList<>();
for(int j = 0; j < horizontalCount; ++j) {
Brick tempBrick = new Brick(j*Brick.BRICK_WIDTH , Brick.BRICK_YPOS + i*Brick.BRICK_HEIGHT);
temp.add(tempBrick);
}
bricks.add(temp);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)g;
g2D.clearRect(0, 0, WIDTH, HEIGHT);
player.drawPaddle(g2D);
ball.drawBall(g2D);
for(ArrayList<Brick> row : bricks) {
for(Brick b : row) {
b.drawBrick(g2D);
}
}
g2D.setFont(scoreFont);
g2D.drawString("Score: " + player.getScore(), 10, 25);
}
}
class Paddle{
public final static int PADDLE_WIDTH = 100, PADDLE_HEIGHT= 30, Y_POS = GameBoard.HEIGHT - 2* PADDLE_HEIGHT;
private int xPos, score;
Paddle(int xPos) {
this.xPos = xPos;
}
void setX(int xPos) {this.xPos = xPos;}
int getX() {return xPos;}
String getScore() {
return String.valueOf(score);
}
void drawPaddle(Graphics2D g2D) {
g2D.setColor(Color.GREEN);
g2D.fillRect(xPos, Y_POS, PADDLE_WIDTH, PADDLE_HEIGHT);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(400,250);
frame.add(new GameBoard());
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
class Brick{
final static int BRICK_WIDTH = 80, BRICK_HEIGHT = 15, BRICK_YPOS = 50;
int xPos, yPos;
Brick(int xPos, int yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
void drawBrick(Graphics2D g2D) {
g2D.setColor(Color.RED);
g2D.fillRect(xPos, yPos, BRICK_WIDTH, BRICK_HEIGHT);
g2D.setColor(Color.BLACK);
g2D.drawRect(xPos, yPos, BRICK_WIDTH, BRICK_HEIGHT);
}
}
class Ball{
final static int DIAMETER = 40;
int xPos, yPos;
Ball(int xPos, int yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
void drawBall(Graphics2D g2D) {
g2D.setColor(Color.BLUE);
g2D.fillOval(xPos, yPos, DIAMETER, DIAMETER);
}
}
This produces the following result, which I believe can serve as the basis of what you wanted to achieve:
Now start adding the missing functionality and see what breaks it.
I tried to make a tetris game. But my jframe GUI is blinking continuosuly. But when i comment the below line in the code, its not blinking. Could someone please help?
map.draw((Graphics2D) g);
JDK Version - 1.8
NetBeans - 7.4
Code file links are below.
package GUI;
import Maps.MapGenerator;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;
public class BrickBreaker extends javax.swing.JFrame implements KeyListener, ActionListener {
private MapGenerator map;
public BrickBreaker() {
initComponents();
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setTitle("Test Tetris");
//Map
map = new MapGenerator(3, 7);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
time = new Timer(delay, this);
time.start();
}
public void paint(Graphics g) {
//background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
//map
map.draw((Graphics2D) g);
//score
g.setColor(Color.white);
g.setFont(new Font("serif", Font.BOLD, 25));
g.drawString("" + score, 560, 30);
//border
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(691, 0, 3, 592);
//paddle
g.setColor(Color.green);
g.fillRect(playerPosX, 550, 100, 8);
//ball
g.setColor(Color.red);
g.fillOval(ballPosX, ballPosY, 20, 20);
g.dispose();
}
private boolean play = false;
private int score = 0;
private int totalBricks = 21;
private Timer time;
private int delay = 8;
private int playerPosX = 310;
private int ballPosX = 210;
private int ballPosY = 350;
private int ballXDir = -1;
private int ballYDir = -2;
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(700, 600));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 525, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 403, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(BrickBreaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BrickBreaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BrickBreaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BrickBreaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new BrickBreaker().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
try {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (playerPosX >= 600) {
playerPosX = 600;
} else {
moveRight();
}
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (playerPosX < 10) {
playerPosX = 10;
} else {
moveLeft();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void moveRight() {
play = true;
playerPosX += 20;
}
public void moveLeft() {
play = true;
playerPosX -= 20;
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void actionPerformed(ActionEvent e) {
time.start();
if (play) {
if (new Rectangle(ballPosX, ballPosY, 20, 20).intersects(new Rectangle(playerPosX, 550, 100, 8))) {
ballYDir = -ballYDir;
}
A:
for (int i = 0; i < map.map.length; i++) {
for (int j = 0; j < map.map[0].length; j++) {
if (map.map[i][j] > 0) {
int brickX = j * map.brickWidth + 60;
int brickY = i * map.brickHeight + 50;
int brickWidht = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY, brickWidht, brickHeight);
Rectangle ballRect = new Rectangle(ballPosX, ballPosY, 20, 20);
Rectangle brickRect = rect;
if (ballRect.intersects(brickRect)) {
map.setBrickValue(0, i, j);
totalBricks--;
score += 2;
if (ballPosX + 19 <= brickRect.x || ballPosX + 1 >= brickRect.x + brickRect.width) {
ballXDir = -ballXDir;
} else {
ballYDir = -ballYDir;
}
break A;
}
}
}
}
ballPosX += ballXDir;
ballPosY += ballYDir;
if (ballPosX < 0) {
ballXDir = -ballXDir;
}
if (ballPosY < 0) {
ballYDir = -ballYDir;
}
if (ballPosX > 670) {
ballXDir = -ballXDir;
}
}
repaint();
}
}
Map generator
package Maps;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class MapGenerator {
public int map[][];
public int brickWidth;
public int brickHeight;
public MapGenerator(int row, int col) {
map = new int[row][col];
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
map[i][j] = 1;
}
}
brickWidth = 240 / row;
brickHeight = 150 / col;
}
public void draw(Graphics2D g) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
if (map[i][j] > 0) {
g.setColor(Color.black);
g.fillRect(j * brickWidth + 60, i * brickHeight + 50, brickWidth, brickHeight);
g.setStroke(new BasicStroke(3));
g.setColor(Color.white);
g.drawRect(j * brickWidth + 60, i * brickHeight + 50, brickWidth, brickHeight);
}
}
}
}
public void setBrickValue(int value, int row, int col) {
map[row][col] = value;
}
}
Top level containers, like JFrame are not double buffered, which is causing the flickering.
This is just one of many reasons why you should not override paint of top level containers. Instead, start with a JPanel and override it's paintComponent, Swing components, by default, are double buffered automatically for you.
Have a look at Performing Custom Painting and Painting in AWT and Swing for more details about how painting works in Swing.
A more suitable solution might start looking something like this...
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private boolean play = false;
private int score = 0;
private int totalBricks = 21;
private Timer timer;
private int delay = 8;
private int playerPosX = 310;
private int ballPosX = 210;
private int ballPosY = 350;
private int ballXDir = -1;
private int ballYDir = -2;
private MapGenerator map;
public TestPane() {
setBackground(Color.BLACK);
map = new MapGenerator(3, 7);
timer = new Timer(delay, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (play) {
if (new Rectangle(ballPosX, ballPosY, 20, 20).intersects(new Rectangle(playerPosX, 550, 100, 8))) {
ballYDir = -ballYDir;
}
for (int i = 0; i < map.map.length; i++) {
for (int j = 0; j < map.map[0].length; j++) {
if (map.map[i][j] > 0) {
int brickX = j * map.brickWidth + 60;
int brickY = i * map.brickHeight + 50;
int brickWidht = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY, brickWidht, brickHeight);
Rectangle ballRect = new Rectangle(ballPosX, ballPosY, 20, 20);
Rectangle brickRect = rect;
if (ballRect.intersects(brickRect)) {
map.setBrickValue(0, i, j);
totalBricks--;
score += 2;
if (ballPosX + 19 <= brickRect.x || ballPosX + 1 >= brickRect.x + brickRect.width) {
ballXDir = -ballXDir;
} else {
ballYDir = -ballYDir;
}
}
}
}
}
ballPosX += ballXDir;
ballPosY += ballYDir;
if (ballPosX < 0) {
ballXDir = -ballXDir;
}
if (ballPosY < 0) {
ballYDir = -ballYDir;
}
if (ballPosX > 670) {
ballXDir = -ballXDir;
}
}
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(700, 600);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
//map
map.draw((Graphics2D) g);
//score
g.setColor(Color.white);
g.setFont(new Font("serif", Font.BOLD, 25));
g.drawString("" + score, 560, 30);
//border
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(691, 0, 3, 592);
//paddle
g.setColor(Color.green);
g.fillRect(playerPosX, 550, 100, 8);
//ball
g.setColor(Color.red);
g.fillOval(ballPosX, ballPosY, 20, 20);
g2d.dispose();
}
}
public class MapGenerator {
public int map[][];
public int brickWidth;
public int brickHeight;
public MapGenerator(int row, int col) {
map = new int[row][col];
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
map[i][j] = 1;
}
}
brickWidth = 240 / row;
brickHeight = 150 / col;
}
public void draw(Graphics2D g) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
if (map[i][j] > 0) {
g.setColor(Color.black);
g.fillRect(j * brickWidth + 60, i * brickHeight + 50, brickWidth, brickHeight);
g.setStroke(new BasicStroke(3));
g.setColor(Color.white);
g.drawRect(j * brickWidth + 60, i * brickHeight + 50, brickWidth, brickHeight);
}
}
}
}
public void setBrickValue(int value, int row, int col) {
map[row][col] = value;
}
}
}
Observations...
This...
A:
for (int i = 0; i < map.map.length; i++) {
//...
//...
break A;
is a pretty good sign of a bad design. There should be no need for a "goto" or "label" based jumped in good code.
You have to think of you "main-loop" in a very linear set of operations, update the state, check for collisions, update the UI. Keep it simple, keep it quick
You will also find that the Key Bindings API will solve all the inherit issues of KeyListener
I've decided on making a HUD with the picture above, but I don't know what command in Java I need to use so as I can fill the top half and the bottom half separately.
I only know how to use the g.fillRect(); command, and it will take around twenty of these commands to fill said half.
public class HUD {
private Player player;
private BufferedImage image;
private Font font;
private Font font2;
private int Phealth = Player.getHealth();
public HUD(Player p) {
player = p;
try {
image = ImageIO.read(getClass().getResourceAsStream("/HUD/HUD_TEST.gif"));
font = new Font("Arial", Font.PLAIN, 10);
font2 = new Font("SANS_SERIF", Font.BOLD, 10);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void draw(Graphics2D g) {
g.drawImage(image, 0, 10, null);
g.setFont(font2);
g.setColor(Color.black);
g.drawString("Health:", 30, 22);
g.drawString("Mana:", 25, 47);
g.setFont(font);
g.drawString(Player.getHealth() + "/" + player.getMaxHealth(), 64, 22);
g.drawString(player.getCubes() / 100 + "/" + player.getMaxCubes() / 100, 55, 47);
g.setColor(Color.red);
g.fillRect(1, 25, Phealth * 25, 4);
g.setColor(Color.blue);
g.fillRect(1, 31, player.getCubes() / 33, 4);
}
}
This is the code for the HUD so far.
Any help in filling the shape will help.
Removed Idea #1! (It didn't seem to work.)
Okay, Idea #2:
Image1
Image2
Image3
So, there are 3 .png images.
Draw Image1 first, followed by drawing Image2 and Image3 directly on top of it.
To fill up either the red/blue bars, clip Image2 and Image3 accordingly (i.e. cut away their left sides)
Take a look at this on clipping.
This will require some minor calculations on how much to clip, based on the HP/Mana of the Player, but it should be good enough.
This is what it should look like (Clipping and overlaying done in Paint)
UPDATE (Problem solved, using Idea #2!):
Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
#SuppressWarnings("serial")
public class TestGraphics extends JFrame implements ActionListener
{
JPanel utilBar = new JPanel();
JButton hpUpBtn = new JButton("HP++");
JButton hpDownBtn = new JButton("HP--");
JButton mpUpBtn = new JButton("MP++");
JButton mpDownBtn = new JButton("MP--");
GraphicsPanel drawingArea = new GraphicsPanel();
TestGraphics()
{
setSize(600, 500);
setLayout(new BorderLayout());
add(utilBar, BorderLayout.NORTH);
utilBar.setLayout(new GridLayout(1, 4));
utilBar.add(hpUpBtn);
utilBar.add(hpDownBtn);
utilBar.add(mpUpBtn);
utilBar.add(mpDownBtn);
add(drawingArea, BorderLayout.CENTER);
hpUpBtn.addActionListener(this);
hpDownBtn.addActionListener(this);
mpUpBtn.addActionListener(this);
mpDownBtn.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == hpUpBtn) {
drawingArea.incHp();
}
else if (e.getSource() == hpDownBtn) {
drawingArea.decHp();
}
else if (e.getSource() == mpUpBtn) {
drawingArea.incMp();
}
else if (e.getSource() == mpDownBtn) {
drawingArea.decMp();
}
System.out.println("Player HP: " + drawingArea.getHp() +
" Player MP: " + drawingArea.getMp());
drawingArea.revalidate();
drawingArea.repaint();
}
public static void main(String[]agrs)
{
new TestGraphics();
}
}
#SuppressWarnings("serial")
class GraphicsPanel extends JPanel {
private static int baseX = 150;
private static int baseY = 150;
private static final int BAR_FULL = 287;
private static final int BAR_EMPTY = 8;
private BufferedImage image1 = null;
private BufferedImage image2 = null;
private BufferedImage image3 = null;
private int playerHp = 100;
private int playerMp = 100;
public GraphicsPanel() {
try {
// All 3 images are the same as those posted in answer
image1 = ImageIO.read(
getClass().getResourceAsStream("/Image1.png"));
image2 = ImageIO.read(
getClass().getResourceAsStream("/Image2.png"));
image3 = ImageIO.read(
getClass().getResourceAsStream("/Image3.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void incHp() { playerHp += (playerHp < 100) ? 5 : 0; }
public void decHp() { playerHp -= (playerHp > 0) ? 5 : 0; }
public void incMp() { playerMp += (playerMp < 100) ? 5 : 0; }
public void decMp() { playerMp -= (playerMp > 0) ? 5 : 0; }
public int getHp() { return playerHp; }
public int getMp() { return playerMp; }
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Clear the graphics
g.setClip(null);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 600, 600);
g.drawImage(image1, baseX, baseY, null);
int hpPerc = (int) ((BAR_FULL - BAR_EMPTY) * (playerHp / 100.0));
g.setClip(baseX + BAR_EMPTY + hpPerc, 0, 600, 500);
g.drawImage(image2, baseX, baseY, null);
g.setClip(null);
int mpPerc = (int) ((BAR_FULL - BAR_EMPTY) * (playerMp / 100.0));
g.setClip(baseX + BAR_EMPTY + mpPerc, 0, 600, 500);
g.drawImage(image3, baseX, baseY + 78, null);
g.setClip(null);
}
}
I've got this GUI that I want to run and when I try to make a Object out of the class I get the error Cannot instantiate the type GUI. So what does it mean and how can I fix?
The code in the mainclass
public static void main(String[] args){
//Classes
GUI go = new GUI();
//Running Class Methods
//JFrame
//JFrame frame = new JFrame("Yatsy");
go.setVisible(true);
go.setVisible(true);
//go.setLocation((dim.width - width) / 2, (dim.height - height) / 2);
go.setSize(width, height);
System.out.println(width + " " + height);
//draw paint = new draw();
//go.add(paint);
}
code inside the GUI class
public GUI(){
super();
panel = new JPanel();
roll = new JButton("Roll");
nextPlayer = new JButton("Next Player");
bDice1 = new JButton("dice");
quit = new JButton("Quit");
use = new JButton("Use");
roll.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(turn == true){
rollResult1 = roll1();
rollResult2 = roll2();
rollResult3 = roll3();
rollResult4 = roll4();
rollResult5 = roll5();
sRollResult1 = Integer.toString(rollResult1);
sRollResult2 = Integer.toString(rollResult2);
sRollResult3 = Integer.toString(rollResult3);
sRollResult4 = Integer.toString(rollResult4);
sRollResult5 = Integer.toString(rollResult5);
rolls++;
start = false;
repaint();
System.out.println( rollResult1 + " " + rollResult2 + " " + rollResult3 + " " + rollResult4 + " " + rollResult5);
//System.out.println( rollAI );
}
if(rolls == 3){
turn = false;
System.out.println("Out of rolls");
}
}
});
nextPlayer.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(rolls > 0){
rolls = 0;
System.out.println("Next player");
turn = true;
repaint();
start = true;
}
}
});
quit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
add(panel, BorderLayout.CENTER);
panel.setBackground(Color.BLUE);
add(quit, BorderLayout.SOUTH);
add(roll, BorderLayout.NORTH);
add(nextPlayer, BorderLayout.EAST);
Handlerclass handler = new Handlerclass();
panel.addMouseListener(handler);
}
So I wonder why do I get an error?
I'm using java 1.7!
For these who want to know this is the full code!!!!
package Christofer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
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 javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public abstract class GUI extends JFrame implements MouseListener{
private static final long serialVersionUID = 1L;
int dice1, dice2, dice3, dice4, dice5;
private JButton roll;
private JButton nextPlayer;
private JButton bDice1;
private JButton quit;
private JButton use;
private JPanel panel;
public int rolls = 0;
public boolean turn = true;
public boolean start = true;
boolean saved1 = false, saved2 = false, saved3 = false, saved4 = false, saved5 = false;
int rollResult1;
int rollResult2;
int rollResult3;
int rollResult4;
int rollResult5;
String sRollResult1, sRollResult2, sRollResult3, sRollResult4, sRollResult5;
public GUI(){
super();
panel = new JPanel();
roll = new JButton("Roll");
nextPlayer = new JButton("Next Player");
bDice1 = new JButton("dice");
quit = new JButton("Quit");
use = new JButton("Use");
roll.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(turn == true){
rollResult1 = roll1();
rollResult2 = roll2();
rollResult3 = roll3();
rollResult4 = roll4();
rollResult5 = roll5();
sRollResult1 = Integer.toString(rollResult1);
sRollResult2 = Integer.toString(rollResult2);
sRollResult3 = Integer.toString(rollResult3);
sRollResult4 = Integer.toString(rollResult4);
sRollResult5 = Integer.toString(rollResult5);
rolls++;
start = false;
repaint();
System.out.println( rollResult1 + " " + rollResult2 + " " + rollResult3 + " " + rollResult4 + " " + rollResult5);
//System.out.println( rollAI );
}
if(rolls == 3){
turn = false;
System.out.println("Out of rolls");
}
}
});
nextPlayer.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(rolls > 0){
rolls = 0;
System.out.println("Next player");
turn = true;
repaint();
start = true;
}
}
});
quit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
add(panel, BorderLayout.CENTER);
panel.setBackground(Color.BLUE);
add(quit, BorderLayout.SOUTH);
add(roll, BorderLayout.NORTH);
add(nextPlayer, BorderLayout.EAST);
Handlerclass handler = new Handlerclass();
panel.addMouseListener(handler);
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
this.setBackground(Color.BLUE);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(getWidth() / 2 - 75, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 1
g2d.fillRoundRect(getWidth() / 2 - 40, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 2
g2d.fillRoundRect(getWidth() / 2 - 5, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 3
g2d.fillRoundRect(getWidth() / 2 + 30, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 4
g2d.fillRoundRect(getWidth() / 2 + 65, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 5
//Score Board
g2d.fillRect(30, 70, 370, getHeight() - 125);
g2d.setColor(Color.BLACK);
g2d.drawLine(150, 70, 150, getHeight() - 30);
g2d.drawLine(30, 70, 400, 70);
g2d.drawString("Ones", 35, 85);
g2d.drawLine(30, 90, 400, 90);
g2d.drawString("Twos", 35, 105);
g2d.drawLine(30, 110, 400, 110);
g2d.drawString("Threes", 35, 125);
g2d.drawLine(30, 130, 400, 130);
g2d.drawString("Fours", 35, 145);
g2d.drawLine(30, 150, 400, 150);
g2d.drawString("Fives", 35, 165);
g2d.drawLine(30, 170, 400, 170);
g2d.drawString("Sixes", 35, 185);
g2d.drawLine(30, 190, 400, 190);
if(start == false){
g.setColor(Color.BLACK);
Font font = new Font("Arial", Font.PLAIN, 25);
g2d.setFont(font);
g2d.drawString( sRollResult1 + " " + sRollResult2 + " " + sRollResult3 + " " + sRollResult4 + " " + sRollResult5, getWidth() / 2 - 70 , getHeight() / 2 - 25 );
if(turn == false){
g2d.setColor(Color.RED);
g2d.drawString("Out Of Rolls", getWidth() / 2 - 70, getHeight() / 2 - 75);
}
}
}
public int roll1(){
if (saved1 == false){
dice1 = (int )(Math.random() * 6 + 1);
}
return dice1;
}
public int roll2(){
if (saved2 == false){
dice2 = (int )(Math.random() * 6 + 1);
}
return dice2;
}
public int roll3(){
if (saved3 == false){
dice3 = (int )(Math.random() * 6 + 1);
}
return dice3;
}
public int roll4(){
if (saved4 == false){
dice4 = (int )(Math.random() * 6 + 1);
}
return dice4;
}
public int roll5(){
if (saved5 == false){
dice5 = (int )(Math.random() * 6 + 1);
}
return dice5;
}
private class Handlerclass implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
mx = e.getX();
my = e.getY();
System.out.println("X: " + mx + " Y: " + my);
if(mx < getWidth() / 2 - 75 && mx > getWidth() / 2 - 45 && my < getHeight() / 2 - 50 && my > getHeight() / 2 - 20){
System.out.println("saved1 = true");
}
}
public void mouseReleased(MouseEvent e) {
}
}
}
I know that I've got some cleaning up to do
public abstract class GUI is your problem. You can't instantiate abstract classes.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can create a subclass and instantiate that though.
As part of my programming assignment, I have to display a rotating fan in an applet.
Here is my code (class to display the fan):
import javax.swing.*;
import java.awt.*;
public class Fan extends JPanel
{
private int angle1 = -15;
private int angle2 = 75;
private int angle3 = 165;
private int angle4 = 255;
public Fan()
{
this.setSize(600, 400);
Runnable spinner = new SpinFan();
Thread thread1 = new Thread(spinner);
thread1.start();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(200, 150, 150, 150);
g.fillArc(210, 160, 130, 130, angle1, 30);
g.fillArc(210, 160, 130, 130, angle2, 30);
g.fillArc(210, 160, 130, 130, angle3, 30);
g.fillArc(210, 160, 130, 130, angle4, 30);
}
}
class SpinFan implements Runnable
{
#Override
public void run()
{
try
{
while(true)
{
angle1 = (angle1 + 1) % 360;
angle2 = (angle2 + 1) % 360;
angle3 = (angle3 + 1) % 360;
angle4 = (angle4 + 1) % 360;
System.out.println(angle1 + " " + angle2 + " " + angle3 + " " + angle4);
repaint();
Thread.sleep(10);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem while putting thread to sleep.");
}
}
}
Class for further processing (right now just has instance of Fan):
import java.awt.*;
import javax.swing.*;
public class FanControl extends JPanel
{
public FanControl()
{
add(new Fan());
}
}
And finally, here is the Applet class:
import java.awt.*;
import javax.swing.*;
public class FanApplet extends JApplet
{
public FanApplet()
{
add(new FanControl());
}
}
Now I've been trying all sorts of stuff for a long time so please don't mind the extra commented out code. The Fan.java class works properly (I can see the fan spinning if I run it as an application by putting it in a frame). But I just can't get the fan to rotate in the Applet. However, if I add something like a JButton to the Applet from the Fan.java class, it works.
What am I missing out on? Is there some complications while using threads and applets, or paintComponent() and applets that I don't seem to know.
When I run the code as an application, it WORKS fine. I can see the rotating fan. Here is the code for that:
import javax.swing.*;
import java.awt.*;
public class Fan extends JPanel
{
private int angle1 = -15;
private int angle2 = 75;
private int angle3 = 165;
private int angle4 = 255;
public Fan()
{
Runnable spinner = new SpinFan();
Thread thread1 = new Thread(spinner);
thread1.start();
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.add(new Fan());
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(200, 150, 150, 150);
g.fillArc(210, 160, 130, 130, angle1, 30);
g.fillArc(210, 160, 130, 130, angle2, 30);
g.fillArc(210, 160, 130, 130, angle3, 30);
g.fillArc(210, 160, 130, 130, angle4, 30);
}
class SpinFan implements Runnable
{
#Override
public void run()
{
try
{
while(true)
{
angle1 = (angle1 - 1) % 360;
angle2 = (angle2 - 1) % 360;
angle3 = (angle3 - 1) % 360;
angle4 = (angle4 - 1) % 360;
System.out.println(angle1 + " " + angle2 + " " + angle3 + " " + angle4);
repaint();
Thread.sleep(10);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem while putting thread to sleep.");
}
}
}
}
while(true) .. repaint(); .. Thread.sleep(10);
This is entirely the wrong way to go about animation.
Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeating tasks or a SwingWorker for long running tasks. See Concurrency in Swing for more details.
The following source uses the Thread defined in code but puts the GUI updates back on the EDT.
But the real problem here is that the animation component was being added to the applet at size 0x0. By changing the layout of the parent container to BorderLayout, we can stretch it to fit the available space.
E.G.
import java.awt.*;
import javax.swing.*;
public class FanApplet extends JApplet
{
private int angle1 = -15;
private int angle2 = 75;
private int angle3 = 165;
private int angle4 = 255;
public FanApplet()
{
add(new FanControl());
}
class FanControl extends JPanel
{
public FanControl()
{
// by setting a BorderLayout and adding a component to the CENTER
// (default if no constraint specified) the child component will
// be stretched to fill the available space.
setLayout(new BorderLayout());
add(new Fan());
}
}
class Fan extends JPanel
{
public Fan()
{
//this.setSize(600, 400);
Runnable spinner = new SpinFan();
Thread thread1 = new Thread(spinner);
thread1.start();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(200, 150, 150, 150);
g.fillArc(210, 160, 130, 130, angle1, 30);
g.fillArc(210, 160, 130, 130, angle2, 30);
g.fillArc(210, 160, 130, 130, angle3, 30);
g.fillArc(210, 160, 130, 130, angle4, 30);
}
}
class SpinFan implements Runnable
{
#Override
public void run()
{
try
{
while(true)
{
angle1 = (angle1 + 1) % 360;
angle2 = (angle2 + 1) % 360;
angle3 = (angle3 + 1) % 360;
angle4 = (angle4 + 1) % 360;
System.out.println(angle1 + " " + angle2 + " " + angle3 + " " + angle4);
// This ensures that repaint() is called on the EDT.
Runnable r = new Runnable() {
public void run() {
repaint();
}
};
SwingUtilities.invokeLater(r);
Thread.sleep(10);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem while putting thread to sleep.");
}
}
}
}