How to input values or phrases on a window? - java

I'm trying to write a program that solves an equation for a school project, but I can't figure out how to create a space for writing in the screen instead of eclipse's console. Like, creating a space in the bottom of the window so the user can input the requested values and the program can read that and make the equation, finally showing the user the final result.
public class Main extends Canvas implements Runnable{
public static JFrame frame;
private Thread thread;
private boolean isRunning = true;
private final int WIDTH = 160;
private final int HEIGHT = 120;
private final int SCALE = 4;
private BufferedImage image;
public Main() {
setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
initFrame();
image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
}
public void initFrame() {
frame = new JFrame("Tempo de Queda (FĂ­sica)");
frame.add(this);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public synchronized void start() {
thread = new Thread(this);
isRunning = true;
thread.start();
}
public synchronized void stop() {
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Main main = new Main();
main.start();}
public void tick() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs==null) {
createBufferStrategy(3);
return;
}
Graphics g = image.getGraphics();
//Back Ground---------------------------------------
g.setColor(new Color(19,19,19));
g.fillRect(0,0,WIDTH,HEIGHT);
g = bs.getDrawGraphics();
g.drawImage(image,0,0,WIDTH*SCALE,HEIGHT*SCALE,null);
//Back Ground---------------------------------------
g.setFont(new Font("Arial",Font.PLAIN,20));
g.setColor(Color.green);
g.drawString("Write Here: ", 5,20);
bs.show();
}
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int frames = 0;
double timer = System.currentTimeMillis();
while(isRunning) {
long now = System.nanoTime();
delta+= (now-lastTime) / ns;
lastTime = now;
if(delta >= 1) {
tick();
render();
frames++;
delta--;
}
if(System.currentTimeMillis() - timer >= 1000) {
System.out.println("FPS: "+frames);
frames = 0;
timer+=1000;
}
}
}
}

So in your case, I'd make some additions to the initFrame method. Specifically, you'll want to add a JPanel to it.
JPanel panel = new JPanel();
frame.add(panel);
Then, define your JTextFields, a JButton and any JLabels to go with them. Java will want you to define any that you're messing with the text value as "final." The other components are ok to set as "final" if you don't plan on reinitializing them:
final JLabel labelX = new JLabel();
final JLabel labelY = new JLabel();
final JLabel output = new JLabel();
final JTextField inputX = new JTextField(5);
final JTextField inputY = new JTextField(5);
final JButton button = new JButton("multiply");
Setting the text of any labels is a good idea:
labelX.setText("X");
labelY.setText("Y");
output.setText("NaN");
Then add them all to the panel:
panel.add(labelX);
panel.add(inputX);
panel.add(labelY);
panel.add(inputY);
panel.add(button);
panel.add(output);
Finally, you'll need to add a listener for the button action. This is where you'll process your inputs and display the output.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
float valueX = 0;
float valueY = 0;
boolean validInputs = true;
try {
valueX = Float.parseFloat(inputX.getText());
valueY = Float.parseFloat(inputY.getText());
} catch (NumberFormatException ex) {
output.setText("Invalid input value(s)");
validInputs = false;
}
if (validInputs) {
//multiply
float result = valueX * valueY;
output.setText(Float.toString(result));
}
}
});
Running that should give you something like this:
Link to Github: FloatMathGUI

Related

Trouble repainting game with swing timer

This is a follow up to my previous question. I am making Frogger in Java I'm trying to implement a swing timer but it doesn't seem to be working. I'm having some trouble setting it up.
I've tried implementing it in different areas of my code and have come to no conclusion as to what's wrong with it. I followed multiple tutorials and nothing has worked.
private int delay = 7;
public CPT() {
setLayout(new BorderLayout());
label = new JLabel("Frogger");
frame1 = new JFrame("Main");
label.setFont(new Font("Serif", Font.BOLD,50));
label.setBounds(275,10,250,250);
button1 = new JButton("PLAY");
button1.setBounds(300,350,100,50);
button1.setOpaque(false);
button1.setVisible(true);
this.setOpaque(false);
this.setLayout(null);
this.add(label);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.setSize(700,500);
frame1.setResizable(false);
button1.setVisible(false);
frame1.add(new TrainCanvas());
frame1.add(p1);
frame1.addKeyListener(new frog());
}
});
this.add(button1);
}
This is the main constructor of my class
class TrainCanvas extends JComponent {
private int lastX = 0;
private int lastX_1 = 0;
private int lastX_2 = 0;
public TrainCanvas() {
// Thread animationThread = new Thread(new Runnable() {
// public void run() {
// while (true) {
// repaint();
// try {Thread.sleep(10);} catch (Exception ex) {}
// }
// }
// });
//
// animationThread.start();
// }
Timer time = new Timer(delay, this {
TrainCanvas.repaint();
});
time.start();
}
public void paintComponent(Graphics g) {
Graphics2D gg = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
int trainW_1 = 100;
int trainH_1 = 5;
int trainSpeed_1 = 3;
int x = lastX + trainSpeed_1;
if (x > w + trainW_1) {
x = -trainW_1;
}
gg.setColor(Color.BLACK);
gg.fillRect(x, h/2 + trainH_1, trainW_1, trainH_1);
lastX = x;
//Draw Frog
frog = new Rectangle(f_x,f_y,25,25);
g3.fill(frog);
g3.setColor(Color.GREEN);
}
}
This is the code that draws the main game I previously used a thread but was told that a swing timer is more useful.
The timer is supposed to repaint my game but it seems as if i can't even implement it properly even though I was told this was right. Any help is appreciated!

Java Canvas when I resize the JFrame, the canvas stops drawing

In more detail, I have a componentResized event attached to the JFrame (which contains the canvas, and nothing else), and in that event a call a method which sets the bounds of the canvas accordingly. This works fine, except that while I'm resizing the canvas, it doesn't show anything. I just see the back of the JFrame. Once I've stopped resizing the JFrame, the canvas paints fine again.
public class MyCanvas implements ComponentListener {
public static void main(String[] args) {
new MyCanvas("MyCanvas",new Dimension(300,300));
}
private static final int frameRate = 30;
private JFrame frame;
private JPanel panel;
private Canvas canvas;
private BufferStrategy strategy;
private int delta;
private boolean running = false;
private int frameCount = 0;
public MyCanvas(String name, Dimension size) {
frame = new JFrame(name);
panel = (JPanel) frame.getContentPane();
canvas = new Canvas();
frame.setSize(size);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(size);
panel.setLayout(null);
canvas.setBounds(0,0,size.width,size.height);
panel.add(canvas);
canvas.setIgnoreRepaint(true);
frame.setResizable(true);
frame.pack();
frame.addComponentListener(this);
canvas.createBufferStrategy(2);
strategy = canvas.getBufferStrategy();
running = true;
frame.setVisible(true);
long lastLoopTime = 0;
while (running) {
frameCount++;
delta = (int) (System.currentTimeMillis() - lastLoopTime);
lastLoopTime = System.currentTimeMillis();
Graphics2D graphics = (Graphics2D) strategy.getDrawGraphics();
graphics.setColor(Color.black);
graphics.fillRect(0,0,getSize().width,getSize().height);
graphics.dispose();
strategy.show();
try {
Thread.sleep(1000/frameRate);
} catch (InterruptedException e) {}
}
}
public final Dimension getSize() {
return frame.getSize();
}
public final void setSize(Dimension size) {
frame.setSize(size);
canvas.setBounds(0,0,size.width,size.height);
}
public synchronized void componentResized(ComponentEvent e) {
setSize(frame.getSize());
}
public synchronized void componentHidden(ComponentEvent e) {
// unused
}
public synchronized void componentShown(ComponentEvent e) {
// unused
}
public synchronized void componentMoved(ComponentEvent e) {
// unused
}
}
Edit
After tweaking with the code for a while, I have come up with a solution:
public class MyCanvas {
public static void main(String[] args) {
new MyCanvas("MyCanvas",new Dimension(400,400));
}
private static final int frameRate = 1000 / 30;
private JFrame frame;
private JPanel panel;
private int delta;
private long lastLoopTime;
private boolean running = false;
private int frameCount = 0;
private BufferedImage backBuffer = null;
private int lastPaintFrame = -1;
public MyCanvas(String name, Dimension size) {
frame = new JFrame(name);
panel = new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
redraw(g);
}
};
frame.setContentPane(panel);
frame.setSize(size);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(size);
panel.setLayout(null);
frame.setResizable(true);
running = true;
frame.setVisible(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
backBuffer = new BufferedImage(screenSize.width,screenSize.height,BufferedImage.TYPE_INT_ARGB);
lastLoopTime = System.nanoTime();
while (running) {
long thisLoopTime = System.nanoTime();
delta = (int) ((thisLoopTime - lastLoopTime) / 1000000);
draw(backBuffer.getGraphics());
frameCount++;
lastLoopTime = thisLoopTime;
redraw(panel.getGraphics());
try {
Thread.sleep(1000/30);
} catch (InterruptedException e) {}
}
}
private final void redraw(Graphics g) {
if (g != null && backBuffer != null) {
g.drawImage(backBuffer,0,0,null);
}
}
int x = 30;
public final void draw(Graphics g) {
g.setColor(Color.darkGray);
g.fillRect(0,0,getSize().width,getSize().height);
g.setColor(Color.gray);
g.fillRect(0,0,500,500);
g.setColor(Color.blue);
g.fillRect(x,30,300,300);
x++;
}
public final Dimension getSize() {
return frame.getSize();
}
public final void setSize(Dimension size) {
frame.setSize(size);
}
}
However, this is not quite solved yet, because it still has odd little graphical glitches which only seem to appear when redraw is called from panel's paintComponent method, though not consistently. Those glitches manifest themselves as odd rectangles of color (usually black or grey) which promptly disappear again. I'm really not sure of what it could be... maybe problems with the double buffering? BTW, if I threw a runtime exception in paintComponent, it worked perfectly.
If this should be moved to a new question, please let me know.
I found the solution: different loops for draw and update:
public class MyCanvas {
public static void main(String[] args) {
new MyCanvas("MyCanvas",new Dimension(400,400));
}
private static final int frameRate = 1000 / 30;
private JFrame frame;
private JPanel panel;
private int delta;
private long lastLoopTime;
private volatile boolean running = false;
private int frameCount = 0;
public MyCanvas(String name, Dimension size) {
frame = new JFrame(name);
panel = new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
if (running) repaint();
}
};
frame.setContentPane(panel);
frame.setSize(size);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(size);
panel.setLayout(null);
frame.setResizable(true);
running = true;
frame.setVisible(true);
lastLoopTime = System.nanoTime();
new Thread(()->{
while (running) {
update();
frameCount++;
try {
Thread.sleep(frameRate);
} catch (InterruptedException e) {}
}
},"Game Loop").start();
}
int x = 30;
public final void update() {
x++;
}
public final void draw(Graphics g) {
g.setColor(Color.darkGray);
g.fillRect(0,0,getSize().width,getSize().height);
g.setColor(Color.gray);
g.fillRect(0,0,500,500);
g.setColor(Color.blue);
g.fillRect(x,30,300,300);
}
public final Dimension getSize() {
return frame.getSize();
}
public final void setSize(Dimension size) {
frame.setSize(size);
}
}

Giving mulitple Jbuttons the same actionListener

I have written a 2x2x2 rubiks cube solver and I want to make the experience for the user entering their cube better, currently they enter numbers which are assigned to colors of the cube. For example 0 could represent white, 1 could represent yellow etc. I have been working on a GUI that is a 2d cube made of buttons that when they are clicked change loop over an array of colors. This is what I have so far but I can't get the actionListener to apply to all the buttons.
public static void main(String[] args) {
final int WINDOW_HEIGHT = 500;
final int WINDOW_WIDTH = 700;
//create a window
window.setTitle("First Window");
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setResizable(false);
allButtons();
}
private static void allButtons(){
panel.setLayout(null);
window.add(panel);
final JButton button[]=new JButton[23];
for(int i=0;i<button.length;i++){
button[i] = new JButton();
}
panel.add(button[0]);
button[0].setBounds(30, 30, 60, 60);
final Color[] ColorArray = {Color.WHITE, Color.ORANGE,Color.GREEN,Color.RED,Color.BLUE,Color.YELLOW};
button[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
final int stickerNum = 24;
if(stickerNum <= 3){
for(Color i : ColorArray){
button[0].setBackground(i);
cube[Side][0] = 0;
}
}
}
});
}
Just assign the ActionListener instance to a variable and add that to JButtons in a loop.
public static void main(String[] args) {
final int WINDOW_HEIGHT = 500;
final int WINDOW_WIDTH = 700;
//create a window
window.setTitle("First Window");
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setResizable(false);
allButtons();
}
private static void allButtons(){
panel.setLayout(null);
window.add(panel);
final JButton button[]=new JButton[23];
for(int i=0;i<button.length;i++){
button[i] = new JButton();
}
panel.add(button[0]);
button[0].setBounds(30, 30, 60, 60);
final Color[] ColorArray = {Color.WHITE, Color.ORANGE,Color.GREEN,Color.RED,Color.BLUE,Color.YELLOW};
ActionListener actionListener = new ActionListener(){
public void actionPerformed(ActionEvent e){
final int stickerNum = 24;
if(stickerNum <= 3){
for(Color i : ColorArray){
button[0].setBackground(i);
cube[Side][0] = 0;
}
}
}
};
for(int i=0;i<button.length;i++){
button[i].addActionListener( actionListener);
}
}
You can just create an ButtonListener class like below which stores an index. Then you just add a new instance of the listener to every button.
public static void main(String[] args) {
final int WINDOW_HEIGHT = 500;
final int WINDOW_WIDTH = 700;
//create a window
window.setTitle("First Window");
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setResizable(false);
allButtons();
}
private static void allButtons() {
panel.setLayout(null);
window.add(panel);
final JButton button[]=new JButton[23];
for(int i=0;i<button.length;i++){
button[i] = new JButton();
}
panel.add(button[0]);
button[0].setBounds(30, 30, 60, 60);
final Color[] ColorArray = {Color.WHITE, Color.ORANGE,Color.GREEN,Color.RED,Color.BLUE,Color.YELLOW};
class ButtonListener implements ActionListener {
private int buttonIndex;
public ButtonListener(int buttonIndex) {
this.buttonIndex = buttonIndex;
}
#Override
public void actionPerformed(ActionEvent e) {
final int stickerNum = 24;
if(stickerNum <= 3){
for(Color i : ColorArray){
button[buttonIndex].setBackground(i);
cube[Side][0] = 0;
}
}
}
}
for(int i = 0; i < button.length; i++) {
button[i].addActionListener(new ButtonListener(i));
}
}

My sprite dont show the background

Im having a problem where my sprite isnt showing the background image but its showing the background Color from the frame.
Here is my code:
MAIN(edited so i only show the part where i load the sprite)
private JFrame principal;
private JButton bt_inicio_iniciar;
private JButton bt_menu_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run()
{
try
{
// UIManager.setLookAndFeel(new SyntheticaBlackEyeLookAndFeel());
new Thread (new ClientMain()).start();
}
catch( Exception e )
{
e.printStackTrace();
}
}
});
}
public ClientMain() throws IOException {
img = ImageIO.read(new File("Resources\\images\\background\\background.png"));
loadGUI();
}
private void loadGUI()
{
int principal_width = 1200;
int principal_heigth = 500;
principal = new JFrame();
// principal.setBackground(new Color(0,0,0,0));
JLabel contentPane = new JLabel();
contentPane.setIcon( new ImageIcon("Resources\\images\\background\\background.png") );
contentPane.setLayout( new BorderLayout() );
principal.pack();
principal.setContentPane( contentPane );
principal.setResizable(false);
principal.setLocationRelativeTo(null);
principal.setTitle("Cliente ");
principal.setSize(principal_width, principal_heigth);
//principal.setContentPane(new JLabel(new ImageIcon("Resources\\images\\background\\background.png")));
principal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
principal.getContentPane().setLayout(null);
//inicio
bt_inicio_iniciar = new JButton();
bt_inicio_iniciar.setBounds(500,200,200,50);
bt_inicio_iniciar.setText("Iniciar");
bt_inicio_iniciar.setEnabled(false);
tx_inicio_estado = new JLabel();
tx_inicio_estado.setText("Esperando al servidor");
tx_inicio_estado.setForeground(Color.WHITE);
tx_inicio_estado.setSize(200,20);
tx_inicio_estado.setLocation(500,175);
//menu
bt_menu_1 = new JButton();
bt_menu_1.setBounds(10,350,150,50);
bt_menu_1.setText("Attack");
bt_menu_1.setBackground(Color.LIGHT_GRAY);
bt_menu_1.setEnabled(true);
bt_menu_2 = new JButton();
bt_menu_2.setBounds(170,350,150,50);
bt_menu_2.setText("Spells");
bt_menu_2.setBackground(Color.LIGHT_GRAY);
bt_menu_2.setEnabled(true);
bt_menu_3 = new JButton();
bt_menu_3.setBounds(10,410,150,50);
bt_menu_3.setText("Items");
bt_menu_3.setBackground(Color.LIGHT_GRAY);
bt_menu_3.setEnabled(true);
bt_menu_4 = new JButton();
bt_menu_4.setBounds(170,410,150,50);
bt_menu_4.setText("Defend");
bt_menu_4.setBackground(Color.LIGHT_GRAY);
bt_menu_4.setEnabled(true);
//battleLog
tx_log = new JLabel();
tx_log.setText("Battle Log");
tx_log.setBounds(330,350,150,15);
log = new TextArea();
log.setBounds(330,370,400,89);
log.setBackground(Color.lightGray);
log.setForeground(Color.white);
//Hp
tx_hp_player1 = new JLabel();
tx_hp_player1.setBounds(740,350,150,15);
tx_hp_player1.setText("Player1");
pb_hp_player1 = new JProgressBar();
pb_hp_player1.setBounds(740,365,445,15);
pb_hp_player1.setMaximum(100);
pb_hp_player1.setMinimum(0);
pb_hp_player1.setValue(100);
pb_hp_player1.setIndeterminate(false);
pb_hp_player1.setStringPainted(true);
pb_hp_player1.setForeground(Color.red);
pb_hp_player1.setString(pb_hp_player1.getValue()+"/"+pb_hp_player1.getMaximum());
tx_hp_player2 = new JLabel();
tx_hp_player2.setBounds(740,385,150,15);
tx_hp_player2.setText("Player2");
pb_hp_player2 = new JProgressBar();
pb_hp_player2.setBounds(740,400,445,15);
pb_hp_player2.setMaximum(100);
pb_hp_player2.setMinimum(0);
pb_hp_player2.setValue(100);
pb_hp_player2.setIndeterminate(false);
pb_hp_player2.setStringPainted(true);
pb_hp_player2.setForeground(Color.red);
pb_hp_player2.setString(pb_hp_player2.getValue()+"/"+pb_hp_player2.getMaximum());
tx_hp_boss = new JLabel();
tx_hp_boss.setBounds(740,420,150,15);
tx_hp_boss.setText("Boss");
pb_hp_boss = new JProgressBar();
pb_hp_boss.setBounds(740,435,445,15);
pb_hp_boss.setMaximum(200);
pb_hp_boss.setMinimum(0);
pb_hp_boss.setValue(200);
pb_hp_boss.setIndeterminate(false);
pb_hp_boss.setStringPainted(true);
pb_hp_boss.setForeground(Color.red);
pb_hp_boss.setString(pb_hp_boss.getValue()+"/"+pb_hp_boss.getMaximum());
p = new Player();
//p.setBounds(100,100,30,35);
//p.setOpaque(true);
principal.add(bt_inicio_iniciar);
principal.add(bt_menu_1);
principal.add(bt_menu_2);
principal.add(bt_menu_3);
principal.add(bt_menu_4);
principal.add(tx_log);
principal.add(log);
principal.add(tx_hp_player1);
principal.add(pb_hp_player1);
principal.add(tx_hp_player2);
principal.add(pb_hp_player2);
principal.add(tx_hp_boss);
principal.add(pb_hp_boss);
principal.add(tx_inicio_estado);
principal.add(p);
principal.setVisible(true);
}
}
Player
public class Player extends JPanel {
// Screen Dimensions
int
GWIDTH = 30,
GHEIGHT = 30;
Dimension screenSize = new Dimension(GWIDTH, GHEIGHT);
// Double Buffer Varabiles
Image dbImage;
Graphics dbg;
// buffered spritesheet
Image firstBall;
SpriteLoader ball = new SpriteLoader("Resources\\images\\sprites\\sprite1.png");
// Animator
Animation ballAnimation;
ArrayList animationArray;
public Player() {
this.setSize(screenSize);
init();
}
private void init(){
animationArray = new ArrayList<BufferedImage>();
animationArray.add(0,ball.getImage(0,64,32,32));
animationArray.add(1,ball.getImage(32,64,32,32));
animationArray.add(2,ball.getImage(64,64,32,32));
ballAnimation = new Animation(animationArray);
ballAnimation.setSpeed(100);
ballAnimation.start();
}
#Override
public void paint(Graphics g){
super.paint(g);
dbImage = createImage(getWidth(),getHeight());
dbg = dbImage.getGraphics();
draw(dbg);
g.drawImage(dbImage, 0, 0, this);
g.dispose();
}
public void draw(Graphics g){
if(ballAnimation != null){
g.drawImage(ballAnimation.sprites, 0, 0, this);
ballAnimation.update(System.currentTimeMillis());
repaint();
}
g.dispose();
}
public static void main(String[] args) {
Player m = new Player();
}
}
Animation
public class Animation {
// initalize values
private ArrayList<BufferedImage> frames;
public BufferedImage sprites;
// Animation Varabales
private volatile boolean running = false;
private long previousTime, speed;
private int frameAtPause, currentFrame;
public Animation(ArrayList<BufferedImage> frames){
this.frames = frames;
}
public void setSpeed(long speed){
this.speed = speed;
}
public void update(long time){
if(running){
if(time - previousTime >= speed){
//Update the animation
currentFrame++;
try{
sprites = frames.get(currentFrame);
} catch(IndexOutOfBoundsException e){
currentFrame = 0;
sprites = frames.get(currentFrame);
}
previousTime = time;
}
}
}// end update
public void start (){
running = true;
previousTime = 0;
frameAtPause = 0;
currentFrame = 0;
}
public void stop (){
running = false;
running = true;
previousTime = 0;
frameAtPause = 0;
currentFrame = 0;
}
public void pause (){
frameAtPause = currentFrame;
running = false;
}
public void restart (){
currentFrame = frameAtPause;
running = true;
}
}
SpriteLoader
public class SpriteLoader {
//Initialize values
private BufferedImage bImage = null,bImage2 = null;
public SpriteLoader(String location){
try{
bImage = ImageIO.read(new File(location));
}catch(IOException e){
}
}
public BufferedImage getImage (int x, int y, int w, int h){
bImage2 = bImage.getSubimage(x, y , w, h);
return bImage2;
}
}
Here is the sprite I'm using
And the background
till now i tried to do everything that i could find on stackoverflow but i couldn't find anything that helped to solve the problem :S
EDIT1: Edited the main class to have only the GUI part but i don't know if i could clean the other classes since i dont knwo where the bug can be :S
EDIT2: Cleared unused methods

My Java Picture won't show up correctly

I am trying to make a simple side-scrolling game and my background color won't work. It should fill the entire page, with an fps counter, but it only has a small line of color at the top of the pop up.
Here is my entire code so far (I had to copy and paste because I'm "not a level 10").
public static final int WIDTH = 640;
public static final int HIGHT = WIDTH / 4 * 3;
public static final String TITLE = "Sploocher's Epic Quest";
private static Game game = new Game();
private boolean running = false;
private Thread thread;
public void init(){
}
public void tick(){
}
public void renderBackground(Graphics g){
}
public void renderForeground(Graphics g){
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0,0,WIDTH,HEIGHT);
//////////////////////////////////////////////////
renderBackground(g);
renderForeground(g);
g.dispose();
bs.show();
}
#Override
public void run() {
init();
long lastTime= System.nanoTime();
final double numTicks = 60.0;
double n = 1000000000 / numTicks;
double delta = 0;
int frames = 0;
int ticks = 0;
long timer = System.currentTimeMillis();
while(running){
long currentTime = System.nanoTime();
delta += (currentTime - lastTime) / n;
lastTime = currentTime;
if(delta >= 1){
tick();
ticks++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer+=1000;
System.out.println(ticks + "Ticks, FPS: " + frames);
ticks = 0;
frames = 0;
}
}
stop();
}
public static void main(String args[]){
JFrame frame = new JFrame(TITLE);
frame.add(game);
frame.setSize(WIDTH, HIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setFocusable(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.pack();
game.start();
}
private synchronized void start(){
if(running)
return;
else
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop(){
if(!running)
return;
else
running = false;
try {
thread.join();
} catch (InterruptedException e){
e.printStackTrace();
}
System.exit(1);
}
}
If anyone could help me figure out how to fix my code, I'd really appreciate it.

Categories

Resources