image wont move for scrolling background in java - java

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author kids
*/
public class background extends javax.swing.JFrame {
private PaintSurface canvas;
private BufferedImage image;
/**
* Creates new form background
*/
public background() {
try {
image = ImageIO.read(new File("C:\\Users\\kids\\Documents\\NetBeansProjects\\game\\src\\backgroundimage.png"));
} catch (IOException ex) {
// handle exception...
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Handle the CLOSE button
pack(); // pack all the components in the JFrame
setVisible(true); // show it
requestFocus(); // set the focus to JFrame to receive KeyEvent
super.setTitle("Game");
this.setSize(1056, 540);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.add(new PaintSurface(), BorderLayout.CENTER);
this.setVisible(true);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
class PaintSurface extends JComponent {
public void paint(Graphics g) {
int width = image.getWidth();
int height = image.getHeight();
int mapWidth = 1056; //Get map width
int mapHeight = 540; //Get map height
int tilesx = 1056/width;
int tilesy = 540/height;
int offsetx = 300;
int offsety = 300;
Graphics2D g2 = (Graphics2D) g;
for(int y=0; y<tilesy; y++)
{
for(int x=0; x<tilesx; x++)
{
g.drawImage(image, x*width-offsetx, y*height-offsety, null);
}
}
}
}
/**
*
* #param args the command line arguments
*/
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(background.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(background.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(background.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(background.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 background();
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
It paints the image, but it does not move when I scroll, so I am confused where the error is. I have looked in various places for an explanation and eventually I tried one.
for(int y=0; y<tilesy; y++
{
for(int x=0; x<tilesx; x++)
{
g.drawImage(myimage, x*width, y*height, null);
}
}
This is how he first painted the image, but he later said that in order to make it scroll is simply a matter of adding an offsetx and offsety, where the offset is how much the map is scrolled. I was unsure of how to define these, so I gave them an integer value of 300. The image is now being drawn, but does not respond to scrolling of any kind. I know my code probably makes you gag but very new so please bear with me on this one. Thanks
I believe I followed the steps correctly, but when I came to the last step, using offset i was confused.

Related

How to fix chess board squares not moving to middle

at the moment I try to make a chessboard with fix sizes. I successfully make that the chessboard will be painted in the corner (coordinate 0,0,400,400). However, now I want that the chessboard will always be in the middle also if I move the window.
The background of the chessboard moves always and is always in the middle but the squares are fixed.
To make you understand my problem, I upload some pics where you can see my main issue.
First Start:
Moving the window to the left
Background in the middle but without the white squares
JPanel
import java.awt.Color;
import java.awt.Graphics;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Serge Junk
*/
public class DrawPanel extends javax.swing.JPanel {
/**
* Creates new form DrawPanel
*/
public DrawPanel() {
initComponents();
}
#Override
public void paintComponent(Graphics g)
{
int width = (getWidth() - 400)/2;
int height = (getHeight()- 400)/2;
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.gray);
g.fillRect(width, height, 400, 400);
g.setColor(Color.black);
g.drawRect(width, height, 400, 400);
for(int i=width;i<400;i+=100)
{
for(int j=height;j<400;j+=100)
{
g.setColor(Color.white);
g.fillRect(i, j, 50, 50);
g.setColor(Color.black);
g.drawRect(i, j, 50, 50);
}
}
for(int i=width+50;i<400;i+=100)
{
for(int j=height+50;j<400;j+=100)
{
g.setColor(Color.white);
g.fillRect(i, j, 50, 50);
g.setColor(Color.black);
g.drawRect(i, j, 50, 50);
}
}
}
/**
*
*/
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}
JFrame
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Serge Junk
*/
public class MainFrame extends javax.swing.JFrame {
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
drawPanel1 = new DrawPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout drawPanel1Layout = new javax.swing.GroupLayout(drawPanel1);
drawPanel1.setLayout(drawPanel1Layout);
drawPanel1Layout.setHorizontalGroup(
drawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 652, Short.MAX_VALUE)
);
drawPanel1Layout.setVerticalGroup(
drawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 473, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private DrawPanel drawPanel1;
// End of variables declaration
}
Here is the "correct" way to draw your squares.
for (int i = width; i < 400 + width; i += 100) {
for (int j = height; j < 400 + height; j += 100) {
g.setColor(Color.white);
g.fillRect(i, j, 50, 50);
g.setColor(Color.black);
g.drawRect(i, j, 50, 50);
}
}
for (int i = width + 50; i < 400 + width; i += 100) {
for (int j = height + 50; j < 400 + height; j += 100) {
g.setColor(Color.white);
g.fillRect(i, j, 50, 50);
g.setColor(Color.black);
g.drawRect(i, j, 50, 50);
}
}
You can achieve it with a twice smaller code:
for (int i = width; i < 400 + width; i += 100) {
for (int j = height; j < 400 + height; j += 100) {
g.setColor(Color.white);
g.fillRect(i, j, 50, 50);
g.fillRect(i+50, j+50, 50, 50);
g.setColor(Color.black);
g.drawRect(i, j, 50, 50);
g.drawRect(i+50, j+50, 50, 50);
}
}

How to fix paint on existing draw

I have some problems with my DrawPanel. I want to make a grill—that should be drawn with the parameters—given by the user by defining the rows and colons.
For example, I enter 3 rows and 5 colons (:), Swing should draw it. The main problem is if I enter the numbers in the TextField and press the draw button, Swing draws the new grill over the old one. Furthermore, sometimes the program doesn't complete some rows or colons and I don't understand why. I already add some numbers such as rows-6 because swing draw a few pixels more than he should. Probably you know a solution for this problem too.
On the picture you can see the lines that are to much. I use a blue line to show how far the lines should go.
DrawPanel (JPanel)
import java.awt.Graphics;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Serge Junk
*/
public class DrawPanel extends javax.swing.JPanel {
/**
* Creates new form DrawPanel
*
*/
private int rows = 1;
private int cols = 2;
public DrawPanel() {
initComponents();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
// draw the rows
int rowHt = (height / rows)-1;
for (int i = 0; i <= rows; i++){
g.drawLine(0, i * rowHt, width, i * rowHt);
}
// draw the columns
int rowWid = (width / cols)-1;
for (int i = 0; i <= cols; i++){
g.drawLine(i * rowWid, 0, i * rowWid, height);
}
}
public void setRows(int pRows){
rows = pRows;
}
public void setCols(int pCols){
cols = pCols;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setPreferredSize(new java.awt.Dimension(300, 200));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}
MainFrame (JFrame)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Serge Junk
*/
public class MainFrame extends javax.swing.JFrame {
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
}
public void updateView()
{
drawPanel1.repaint();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
drawPanel1 = new DrawPanel();
jLabel1 = new javax.swing.JLabel();
rowTextField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
colsTextField = new javax.swing.JTextField();
drawButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout drawPanel1Layout = new javax.swing.GroupLayout(drawPanel1);
drawPanel1.setLayout(drawPanel1Layout);
drawPanel1Layout.setHorizontalGroup(
drawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 600, Short.MAX_VALUE)
);
drawPanel1Layout.setVerticalGroup(
drawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 200, Short.MAX_VALUE)
);
jLabel1.setText("Lignes");
jLabel2.setText("Colonnes");
drawButton.setText("Draw");
drawButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
drawButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(rowTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(colsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addComponent(drawButton))
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(drawPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(26, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(drawPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(rowTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(colsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(drawButton)))
.addContainerGap())
);
pack();
}// </editor-fold>
private void drawButtonActionPerformed(java.awt.event.ActionEvent evt) {
//E
int row = Integer.valueOf(rowTextField.getText());
int col = Integer.valueOf(colsTextField.getText());
//T
drawPanel1.setRows(row);
drawPanel1.setCols(col);
//S
updateView();
}
/**
* #param args the command line arguments
*/
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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField colsTextField;
private javax.swing.JButton drawButton;
private DrawPanel drawPanel1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField rowTextField;
// End of variables declaration
}
Netbeans draw the new grill over the old one.
The first statement in the paintComponent() method should be:
super.paintComponent(g);
This will clear the background before you do your custom painting.
drawPanel1.setRows(row);
drawPanel1.setCols(col);
//S
updateView();
There is no need for the updateView() method. Instead both the setRows(...) and setCols(...) method should invoke repaint() directly. That is it is the responsibility of the component to repaint itself when a property of the component is changed.
sometimes the program doesn't complete some rows or colons and I don't understand why.
int rowHt = height / rows-1;
Be explicit when using formulas so we know exactly what you intend instead of relying in the compiler. So you should use:
int rowHt = (height / rows) - 1;
Don't be afraid to create variables for your parameters:
//g.drawLine(i * rowWid, 0, i * rowWid, height-5);
int xOffset = i * rowWidth;
int yEnd = height - 5;
g.drawLine(xOffset, 0, xOffset, yEnd);
This then allows you to add debug code easily to see exactly what values a being used to draw the line:
System.out.println(xOffset + " : " + yEnd);
Now you should be able to determine if your logic is correct.
So, as camickr suggested, you should not add any hidden variables to the division or rows / height or cols / width, because this is a maintenance nightmare. Stay away from magic values!
The DrawPanel.paintComponent must do a few things.
Don't forget to call super() !
You will need to determine line thickness so you know how much to offset.
Keep your units as floating-point values until you NEED to set them as integers.
Dispose afterwards.
Moreover, you do not want to set instance variables in their declaration, but through a constructor of some sorts.
Additionally, I added two more fields to control line width and color as seen below. I also redesigned the layout so that it is actually legible from a code maintenance standpoint.
Runner
package question58310987;
import javax.swing.*;
public class Runner {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new MainFrame();
setLookAndFeel(frame);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
private static void setLookAndFeel(JFrame frame) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(frame);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
}
DrawPanel
package question58310987;
import java.awt.*;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
private static final long serialVersionUID = 1889951852010548809L;
private int rows;
private int cols;
private int thickness;
private Color fgColor;
private Color bgColor;
private boolean dirty;
private Stroke strokeRef;
public DrawPanel() {
this(3, 3);
}
public DrawPanel(int rows, int cols) {
this(rows, cols, 1, Color.BLACK, null);
}
public DrawPanel(int rows, int cols, int thickness, Color fgColor, Color bgColor) {
super();
this.rows = rows;
this.cols = cols;
this.thickness = thickness;
this.fgColor = fgColor;
this.bgColor = bgColor;
this.dirty = true; // initialized as true
}
private float getStrokeThickness(Graphics2D g2d) {
Stroke stroke = g2d.getStroke();
if (stroke instanceof BasicStroke) {
return ((BasicStroke) stroke).getLineWidth();
}
return 1.0f;
}
/**
* Re-evaluates the state of the properties.
*/
protected void commitProperties(Graphics2D g2d) {
if (dirty) {
strokeRef = new BasicStroke(this.thickness);
dirty = false;
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
commitProperties(g2d);
g2d.setStroke(strokeRef);
float lineSize = getStrokeThickness(g2d); // Calculate line thickness
float halfStroke = lineSize > 2.0f ? lineSize / 2.0f : 1.0f;
int width = this.getWidth();
int height = this.getHeight();
int maxWidth = (int) (width - halfStroke);
int maxHeight = (int) (height - halfStroke);
float yOffset = (((float) maxHeight - halfStroke) / (rows));
float xOffset = (((float) maxWidth - halfStroke) / (cols));
if (bgColor != null) {
g2d.setColor(bgColor);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
g2d.setColor(fgColor);
// Draw the horizontal lines
for (int row = 0; row < rows; row++) {
int y = (int) (row * yOffset + halfStroke);
g2d.drawLine((int) halfStroke, y, maxWidth, y);
}
g2d.drawLine((int) halfStroke, maxHeight, maxWidth, maxHeight); // Draw the final horizontal line
// Draw the vertical lines
for (int col = 0; col < cols; col++) {
int x = (int) (col * xOffset + halfStroke);
g2d.drawLine(x, (int) halfStroke, x, maxHeight);
}
g2d.drawLine(maxWidth, (int) halfStroke, maxWidth, maxHeight); // Draw the final vertical line
g2d.dispose(); // Clear changes
}
public String getFgColorHex() {
return String.format("#%02X%02X%02X", fgColor.getRed(), fgColor.getGreen(), fgColor.getBlue());
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getCols() {
return cols;
}
public void setCols(int cols) {
this.cols = cols;
}
public int getThickness() {
return thickness;
}
public void setThickness(int thickness) {
this.thickness = thickness;
this.dirty = true;
}
public Color getFgColor() {
return fgColor;
}
public void setFgColor(Color fgColor) {
this.fgColor = fgColor;
}
public Color getBgColor() {
return bgColor;
}
public void setBgColor(Color bgColor) {
this.bgColor = bgColor;
}
}
MainFrame
package question58310987;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MainFrame extends JFrame {
private static final long serialVersionUID = -2796976952328960949L;
private static final String DEFAULT_APP_TITLE = "Main Frame";
private DrawPanel drawPanel;
private JLabel rowLabel;
private JTextField rowTextField;
private JLabel colLabel;
private JTextField colTextField;
private JLabel thicknessLabel;
private JTextField thicknessTextField;
private JLabel colorLabel;
private JTextField colorTextField;
private JButton drawButton;
public MainFrame() {
this(DEFAULT_APP_TITLE);
}
public MainFrame(String title) {
super(title);
initialize();
addChildren();
}
protected void initialize() {
drawPanel = new DrawPanel();
drawPanel.setThickness(6);
drawPanel.setFgColor(Color.BLUE);
drawPanel.setPreferredSize(new Dimension(600, 200));
rowLabel = new JLabel("Rows");
rowTextField = new JTextField(Integer.toString(drawPanel.getRows()), 3);
colLabel = new JLabel("Columns");
colTextField = new JTextField(Integer.toString(drawPanel.getCols()), 3);
thicknessLabel = new JLabel("Thickness");
thicknessTextField = new JTextField(Integer.toString(drawPanel.getThickness()), 3);
colorLabel = new JLabel("Color");
colorTextField = new JTextField(drawPanel.getFgColorHex(), 6);
drawButton = new JButton("Draw");
drawButton.addActionListener(evt -> drawButtonActionPerformed(evt));
}
protected void addChildren() {
GridBagLayout verticalLayout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(16, 16, 16, 16); // top, left, bottom, right
getContentPane().setLayout(verticalLayout);
getContentPane().add(drawPanel, gbc);
FlowLayout horizontalLayout = new FlowLayout();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(horizontalLayout);
buttonPanel.add(rowLabel);
buttonPanel.add(rowTextField);
buttonPanel.add(Box.createHorizontalStrut(30));
buttonPanel.add(colLabel);
buttonPanel.add(colTextField);
buttonPanel.add(Box.createHorizontalStrut(30));
buttonPanel.add(thicknessLabel);
buttonPanel.add(thicknessTextField);
buttonPanel.add(Box.createHorizontalStrut(30));
buttonPanel.add(colorLabel);
buttonPanel.add(colorTextField);
buttonPanel.add(Box.createHorizontalStrut(30));
buttonPanel.add(drawButton);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(0, 16, 16, 16); // top, left, bottom, right
getContentPane().add(buttonPanel, gbc);
}
private void drawButtonActionPerformed(ActionEvent evt) {
int row = Integer.valueOf(rowTextField.getText().trim());
int col = Integer.valueOf(colTextField.getText().trim());
int thickness = Integer.valueOf(thicknessTextField.getText().trim());
String colorHex = colorTextField.getText().trim();
drawPanel.setRows(row);
drawPanel.setCols(col);
drawPanel.setThickness(thickness);
drawPanel.setFgColor(hexToColor(colorHex));
this.updateView();
}
public void updateView() {
drawPanel.repaint();
}
/**
* Supports both #FF0000 and #F00 formats.
*
* #param hex a hexadecimal color value from #000000 -> #FFFFFF
* #return
*/
public static final Color hexToColor(String hex) {
if (hex.startsWith("#")) {
hex = hex.replace("#", "");
}
if (hex.length() == 3) {
hex = splicePad(hex, 2);
}
int v = Integer.parseInt(hex, 16);
int r = (v & 0xFF0000) >> 16;
int g = (v & 0xFF00) >> 8;
int b = (v & 0xFF);
return new Color(r, g, b);
}
/**
* Splices each character after itself n-number of times.
*/
public static final String splicePad(String str, final int repeat) {
StringBuffer buff = new StringBuffer();
for (char ch : str.toCharArray()) {
for (int i = 0; i < repeat; i++) {
buff.append(ch);
}
}
return buff.toString();
}
}

How can I make a simple jumping up animation in Java for a scrolling game?

I am very new to Java but I have been working on a scrolling background game, like Geometry Dash. It is very bare bones with just some clouds to indicate that the background is moving, but I am now confronted with the problem of making it so my player can jump up then fall back down by pressing the arrow up key, like a jumping motion. I hope there is a simple solution to my problem, so that someone can help me and I understand it. I have made it so the player can jump up, but I have not been able to make it go back down after it jumps. Any help would be greatly appreciated. Thanks!
here is the code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
/**
*
* #author kids
*/
public class game extends javax.swing.JFrame {
private PaintSurface canvas;
int x_position = 0;
int y_position = 580;
int x_speed = 7;
int enemy_posX = 0;
int enemy_posY = 560;
int x_pos = 0;
int y_pos = 0;
int x_pos2 = -1200;
int x_position2 = -1200;
int enemy_posX2 = -1150;
int enemy_posY2 = 560;
int cloudOnex = 30;
int cloudOney = 70;
int cloud2x = -1150;
int cloud2y = 70;
int cloud3x = 700;
int cloud3y = 70;
int cloud4x = -600;
int cloud4y = 70;
int playerx =400;
int playery = 540;
/**
* Creates new form game
*/
public game() {
JPanel btnPanel = new JPanel(new FlowLayout());
JButton btnUp = new JButton("Move Up ");
btnPanel.add(btnUp);
btnUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
playery += 10;
canvas.repaint();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
// "super" JFrame fires KeyEvent
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent evt) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_UP:
playery -= 22;
repaint();
break;
}
}
});
this.setTitle("Scrolling Game");
this.setSize(1200, 650);
// super.setBackground(Color.YELLOW);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.add(new PaintSurface(), BorderLayout.CENTER);
this.setVisible(true);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
//settings for the form, handling things such as exiting and size
Timer timer = new Timer(10, e -> {
canvas.movement();
canvas.check();
canvas.repaint();
});
timer.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
class PaintSurface extends JComponent {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D background = new Rectangle2D.Float(x_pos, y_pos, 1200, 650);
g2.setColor(Color.CYAN);
g2.fill(background);
Rectangle2D ground = new Rectangle2D.Float(x_position, y_position, 1200, 30);
g2.setColor(Color.GREEN);
g2.fill(ground);
Rectangle2D cloudOne = new Rectangle2D.Float(cloudOnex, cloudOney, 70, 70);
g2.setColor(Color.WHITE);
g2.fill(cloudOne);
Rectangle2D cloudThree = new Rectangle2D.Float(cloud3x, cloud3y, 70, 70);
g2.setColor(Color.WHITE);
g2.fill(cloudThree);
Rectangle2D background2 = new Rectangle2D.Float(x_pos2, y_pos, 1200, 650);
g2.setColor(Color.CYAN);
g2.fill(background2);
Rectangle2D ground2 = new Rectangle2D.Float(x_position2, y_position, 1200, 30);
g2.setColor(Color.GREEN);
g2.fill(ground2);
Rectangle2D cloudTwo = new Rectangle2D.Float(cloud2x, cloud2y, 70, 70);
g2.setColor(Color.WHITE);
g2.fill(cloudTwo);
Rectangle2D cloudFour = new Rectangle2D.Float(cloud4x, cloud4y, 70, 70);
g2.setColor(Color.WHITE);
g2.fill(cloudFour);
Rectangle2D player = new Rectangle2D.Float(playerx, playery,40,40);
g2.setColor(Color.red);
g2.fill(player);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
/**
* #param args the command line arguments
*/
}
public void movement(){
cloudOnex += 10;
cloud2x += 10;
cloud3x += 10;
cloud4x += 10;
x_position += 10;
x_pos += 10;
x_position2 += 10;
x_pos2 += 10;
enemy_posX += 10;
enemy_posX2 += 10;
try { Thread.sleep(20); } /* this will pause for 50 milliseconds */
catch (InterruptedException e) { System.err.println("sleep exception"); }
}
public void check(){
if (x_pos == 1200 ) {
x_pos = -1200;
//x_position = -1200;
repaint();
}
if (x_pos2 == 1200) {
x_pos2 = -1200;
// x_position2 = -1200;
repaint();
}
if (x_position == 1200) {
x_position = -1200;
repaint();
}
if (x_position2 == 1200) {
x_position2 = -1200;
repaint();
}
if (cloudOnex == 1200) {
cloudOnex = -1150;
repaint();
}
if (cloud2x == 1200){
cloud2x = -1150;
repaint();
}
// if (x_position2 > 1300) {
// x_position2 = -600;
// repaint();
// }
}
}
/**
* #param args the command line arguments
*/
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(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(game.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 game().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
The simplest way to do this is to make the character go up, and then go down after a certain time. To do this replace the addKeyListener code in your function with the following:
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent evt) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_UP:
playery -= 22;
repaint();
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
playery += 22;
}
},
100
);
break;
}
}
});
This uses java.util.TimerTask, which allows you to delay an action.

I am making a simple paint program in java, I can draw but when I minimize the window or resize what I painted goes away. How do I get them to stay?

Here is what I have so far, I tried creating the draw function just to test if that would work. The palette is just another gui window that will have color options once I figure this saving problem out first
import csc260final.Palette;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JOptionPane;
/**
*
* #author Jared Hughes
*/
public class Canvas extends javax.swing.JFrame {
/**
* Creates new form Canvas
*/
Draw line;
private int curX, curY, oldX, oldY;
public Graphics2D g2;
Palette palette;
public Canvas() {
initComponents();
palette = new Palette();
palette.setVisible(true);
}
public void draw(){
g2 = (Graphics2D) jPanel1.getGraphics();
g2.setColor(Color.yellow);
g2.setStroke(new BasicStroke(10));
g2.drawLine(oldX, oldY, curX, curY);
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
super.paint(g);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setPreferredSize(new java.awt.Dimension(1130, 550));
jPanel1.setRequestFocusEnabled(false);
jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
jPanel1MouseDragged(evt);
}
public void mouseMoved(java.awt.event.MouseEvent evt) {
jPanel1MouseMoved(evt);
}
});
jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jPanel1MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jPanel1MouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jPanel1MouseExited(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
jPanel1MousePressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
jPanel1MouseReleased(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1130, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 550, Short.MAX_VALUE)
);
jButton1.setText("jButton1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(94, 94, 94))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jPanel1MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
// save x and y when mouse is pressed
curX = evt.getX();
curY = evt.getY();
oldX = curX;
oldY = curY;
}
private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
// get x and y when mouse is dragged
curX = evt.getX();
curY = evt.getY();
g2 = (Graphics2D) jPanel1.getGraphics();
g2.setColor(Color.yellow);
g2.setStroke(new BasicStroke(10));
g2.drawLine(oldX, oldY, curX, curY);
oldX = curX;
oldY = curY;
}
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jPanel1MouseEntered(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jPanel1MouseMoved(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jPanel1MouseExited(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jPanel1MouseReleased(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
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(Canvas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Canvas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Canvas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Canvas.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 Canvas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
Your Swing drawing is being done incorrectly. You should not draw with a Graphics object obtained by calling getGraphics() on a component. This will return a Graphics object that is short lived, risking disappearing graphics or worse, a NullPointerException. Instead, draw in the JPanel's paintComponent(...) method either directly, or indirectly by drawing on a BufferedImage (yes, you can get its Graphics object via getGraphics()) and then drawing the BufferedImage to the GUI within the paintComponent method.
Useful Java Tutorials:
Lesson: Performing Custom Painting: introductory tutorial to Swing graphics
Painting in AWT and Swing: advanced tutorial on Swing graphics
Small nitpicks:
Avoid giving your classes names that clash with core Java classes, such as Canvas. This will help prevent confusing others and your future self.
When posting code here, we greatly appreciate it if you strive to format it well, including judicious use of empty lines. Your code above has several large empty regions that make following it hard. A single empty line here or there is OK, but a lot, not so much.
For example:
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestDrawingCanvas extends JPanel {
private DrawingCanvas drawingCanvas = new DrawingCanvas();
public TestDrawingCanvas() {
JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
btnPanel.add(new JButton(new ClearAction()));
setLayout(new BorderLayout());
add(drawingCanvas, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
private class ClearAction extends AbstractAction {
public ClearAction() {
super("Clear Canvas");
putValue(MNEMONIC_KEY, KeyEvent.VK_C);
}
#Override
public void actionPerformed(ActionEvent e) {
drawingCanvas.clear();
}
}
private static void createAndShowGui() {
TestDrawingCanvas mainPanel = new TestDrawingCanvas();
JFrame frame = new JFrame("Drawing Canvas");
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(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class DrawingCanvas extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 600;
public static final Color LINE_COLOR = Color.YELLOW;
public static final Stroke IMG_STROKE = new BasicStroke(10f);
private Color lineColor = LINE_COLOR;
private BufferedImage image;
public DrawingCanvas() {
setBackground(Color.WHITE);
image = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
public void setLineColor(Color lineColor) {
this.lineColor = lineColor;
}
public void clear () {
image = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
repaint();
}
private class MyMouse extends MouseAdapter {
private Graphics2D imgG2d;
private Point p1;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
imgG2d = image.createGraphics();
imgG2d.setColor(lineColor);
imgG2d.setStroke(IMG_STROKE);
p1 = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent e) {
drawLine(e);
imgG2d.dispose();
p1 = null;
imgG2d = null;
}
#Override
public void mouseDragged(MouseEvent e) {
drawLine(e);
p1 = e.getPoint();
}
private void drawLine(MouseEvent e) {
if (imgG2d == null || p1 == null) {
return;
}
Point p2 = e.getPoint();
int x1 = p1.x;
int y1 = p1.y;
int x2 = p2.x;
int y2 = p2.y;
imgG2d.drawLine(x1, y1, x2, y2);
repaint();
}
}
}

Made a JFrame, made an applet, not sure how to combine the two?

I'm a complete Java novice and need some help. Basically, I was tying to make a JFrame that had a background for my already made game. I just used Netbeans JFrame design tab and was hoping I could combine the code in a dedicated section of the JFrame code, which I've been unable to do.
Alternatively, it would be just as good if somebody could show me how to add a background to the JFrame created in my game, the code is below:
package javagame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class JavaGame extends JFrame {
int x, y;
Image piggy1;
private Image dbImage;
private Graphics dbg;
public class ActionListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == e.VK_LEFT) {
if(x <= 0)
x = 0;
else
x += -5;
}
if(keyCode == e.VK_RIGHT) {
if (x>= 450)
x = 450;
else
x += +5;
}
if(keyCode == e.VK_UP) {
if(y<= 20)
y = 20;
else
y += -5;
}
if(keyCode == e.VK_DOWN) {
if (y>= 450)
y = 450;
else
y += +5;
}
}
public void keyReleased(KeyEvent e) {
}
}
public JavaGame() {
//Images
ImageIcon i = new ImageIcon("C:/Users/MrBlueMKII/Documents/NetBeansProjects/JavaGame/src/javagame/PIGGY.gif");
piggy1 = i.getImage();
addKeyListener(new ActionListener());
setTitle("Java Game");
setSize(500, 500);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 150;
y = 150;
ImageIcon j = new ImageIcon("C:/Users/MrBlueMKII/Downloads/field.jpg");
}
public void paint(Graphics g){
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.drawImage(piggy1, x, y, this);
repaint();
}
public static void main(String[] args) {
new JavaGame();
}
}
The code for the JFrame is:
package javagame;
public class JFrame extends javax.swing.JFrame {
public JFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(null);
jTextField1.setBackground(new java.awt.Color(223, 248, 248));
jTextField1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jTextField1.setForeground(new java.awt.Color(255, 255, 255));
jTextField1.setText("Eat the flies to evolve wings!");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jPanel1.add(jTextField1);
jTextField1.setBounds(280, 0, 200, 80);
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\MrBlueMKII\\Downloads\\field.jpg")); // NOI18N
jLabel1.setText("jLabel1");
jPanel1.add(jLabel1);
jLabel1.setBounds(0, 0, 500, 500);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
public static void main(String args[]) {
//<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(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
Thanks!
The best approach would be to remove all the common elements that you need to into separate components (using something like JPanel instead of JFrame and JApplet)
This will allow you to add the to the frame or applet as you see fit.
This is very common design philosophy, don't trap your self to a particular top level container by implementing the logic in a common in a common ancestor

Categories