How to fix paint on existing draw - java

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();
}
}

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 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.

Line drawn by Graphics type variable disappears when making a label for it

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class NewJFrame extends JFrame {
private Graphics g1;
private JLabel label = new JLabel();
// holds information of all businesses
private Object[][] busInfo = new Object[10][15];
public NewJFrame() {
initComponents();
g1 = jPanel1.getGraphics();
}
#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);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 858, Short.MAX_VALUE));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 564, Short.MAX_VALUE));
jButton1.setText("Click Me");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1).addGap(425, 425, 425))
.addGroup(layout.createSequentialGroup().addGap(48, 48, 48)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(61, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addGap(28, 28, 28)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jButton1)));
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
printBarChart(2, 1);
System.out.println(getSize());
}
public static void main(String args[]) {
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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(() -> {
new NewJFrame().setVisible(true);
});
}
public void printBarChart(int bestBus, int worstBus) {
busInfo[0][7] = 24325.08;
busInfo[1][7] = 15394.59;
busInfo[2][7] = 186719.84;
int y = jPanel1.getSize().height;
int x = jPanel1.getSize().width;
double balance, maxScale = (double) busInfo[bestBus][7] + 650;
int sameBusDistance, diffBusDistance = 0, scaleNum, maxPoint;
for (int i = 0; i <= 2; ++i) {
if (i == 0) {
diffBusDistance = 0;
} else {
diffBusDistance += 65;
}
// color of best business
if (i == bestBus) {
g1.setColor(Color.YELLOW);
// color of worst business
} else if (i == worstBus) {
g1.setColor(Color.RED);
// color of other businesses (neither best nor worst)
} else {
g1.setColor(Color.BLACK);
}
balance = (double) busInfo[i][7];
sameBusDistance = 25;
scaleNum = y - 100;
maxPoint = scaleNum - (scaleNum * (int) balance / (int) maxScale) + 50;
g1.drawLine(125 + diffBusDistance, y - 50, 125 + diffBusDistance, maxPoint);
g1.drawLine(125 + sameBusDistance + diffBusDistance, y - 50, 125 + sameBusDistance + diffBusDistance,
maxPoint);
g1.drawLine(125 + sameBusDistance + diffBusDistance, maxPoint, 125 + diffBusDistance, maxPoint);
jPanel1.add(label);
jPanel1.setLayout(null);
label.setSize(100, 50);
label.setFont(label.getFont().deriveFont(8f));
label.setLocation(125 + sameBusDistance + diffBusDistance - 30, maxPoint - 50);
label.setText("" + busInfo[i][7]);
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
Line drawn by Graphics type variable disappears when making a label for it
This code is in a for loop for the number of businesses. I will attach a picture of the problem.The first bar works just fine:
The second however removes the first bar and its label from view:
Printing labels for Bar Charts causing other bars and their labels to dissapear
Again, I suggest that you don't use getGraphics() called on a component. By now you should have minimized and restored your GUI to see that the drawing is not stable when you minimize and restore the GUI. I suggest that you draw in the paintComponent of your JPanel.
There is an exception however -- if you draw in a BufferedImage, you can use a Graphics object obtained from it, and then display the image in an ImageIcon in a JLabel. For example in the code below I create a JLabel filled with an empty image (to give it size). I then fill the image with some bar chart data on button press, put the image into an ImageIcon and then set the JLabel with that icon by calling setIcon(...) on it:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
#SuppressWarnings("serial")
public class DrawInImage extends JPanel {
private static final int IMG_W = 900;
private static final int IMG_H = 700;
private static final int GAP = 20;
private BufferedImage img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);
private Icon icon = new ImageIcon(img);
private JLabel label = new JLabel(icon);
private int[] data = { 4, 2, 9, 7, 3, 8, 2, 8 };
public DrawInImage() {
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new AbstractAction("Press Me") {
#Override
public void actionPerformed(ActionEvent arg0) {
printBarChart();
}
}));
setLayout(new BorderLayout());
add(label);
add(btnPanel, BorderLayout.PAGE_END);
}
private void printBarChart() {
// create new image
img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics(); // get image's graphics
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 18));
// get sizes of drawing area
int totalWidth = IMG_W - 2 * GAP;
int totalHeight = IMG_H - 2 * GAP;
// number of columns including gaps
int columns = 2 * data.length + 1;
// calc the max data + 1
int maxData = 0;
for (int i : data) {
if (i > maxData) {
maxData = i;
}
}
maxData++; // + 1
for (int i = 0; i < data.length; i++) {
int x1 = GAP + ((2 * i + 1) * totalWidth) / columns;
int x2 = GAP + ((2 * i + 2) * totalWidth) / columns;
int y1 = GAP + (totalHeight * (maxData - data[i])) / maxData;
int y2 = GAP + totalHeight;
float hue = (float) i / (float) data.length;
Color c = Color.getHSBColor(hue, 1f, 1f);
g2.setColor(c);
g2.fillRect(x1, y1, x2 - x1, y2 - y1);
g2.setColor(Color.BLACK);
String text = "Data " + (i + 1);
int strX = x1;
int strY = y1 - GAP / 2;
g2.drawString(text, strX, strY);
}
g2.dispose(); // dispose of graphics objects *we* create
icon = new ImageIcon(img); // create new icon
label.setIcon(icon); // display in label
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Draw In Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawInImage());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Which displays as

Zooming effect not shown in the frame

Here is my code below. I am trying to implement zooming by moving the slider.
However, the effect does'nt show. Please help me on this. I am lost. I am new to java and I am using Netbeans for this.
I further need to click on the zoomed image and display the corresponding points in the actual image. How can I make this possible?
public class TrialZoom extends javax.swing.JFrame {
/**
* Creates new form TrialZoom
*/
private float scaleX, scaleY;
Point p = new Point();
Point q = new Point();
Vector<Point> v = new Vector();
Vector<Float> v_scale = new Vector();
public TrialZoom() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jSlider2 = new javax.swing.JSlider();
jPanel4 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new java.awt.GridLayout(1, 0));
jButton1.setText("Done");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel3.setLayout(new java.awt.GridLayout(1, 0));
jSlider2.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider2StateChanged(evt);
}
});
jPanel3.add(jSlider2);
jPanel2.add(jPanel3, java.awt.BorderLayout.PAGE_END);
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel1MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(0, 200, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(0, 200, Short.MAX_VALUE)))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 251, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(0, 125, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(0, 126, Short.MAX_VALUE)))
);
jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void jSlider2StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
int val = ((JSlider) evt.getSource()).getValue();
setScale(val * .01f, val * .01f);
}
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {
setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.CROSSHAIR_CURSOR));
p = evt.getPoint();
q = SwingUtilities.convertPoint(evt.getComponent(), p, this);
v.add(p);
v_scale.add(scaleX);
v_scale.add(scaleY);
double c = q.getX();
double d = q.getY();
String x1 = Double.toString(p.getX());
String x2 = Double.toString(p.getY());
Graphics g = this.getGraphics();
paint(g, (int) c, (int) d); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(p.getX() + " " + p.getY() + " " + q.getX() + " " + q.getY());
float sx=v_scale.remove(0);
float sy=v_scale.remove(0);
System.out.println(sx+" "+sy);
dispose();
// TODO add your handling code here:
}
public Vector<Point> first(ImageIcon icon) {
jLabel1.setIcon(icon);
return return_vector();
}
public void paint(Graphics g, int a, int b) {
g.setColor(Color.RED);
g.drawRect(a - 1, b - 1, 3, 3);
g.fillRect(a, b, 2, 2);
}
#Override
public Dimension getPreferredSize() {
int prefWidth;
prefWidth = (int) (jLabel1 == null ? 0 : jPanel4.getWidth() * scaleX);
int prefHeight;
prefHeight = (int) (jLabel1 == null ? 0 : jPanel4.getHeight() * scaleY);
return new Dimension(prefWidth, prefHeight);
}
public void paintComponent(Graphics g) {
if (jLabel1 == null) {
return;
}
int w = (int) (jLabel1.getWidth() * scaleX);
int h = (int) (jLabel1.getHeight() * scaleY);
int x = (getWidth() - w) / 2;
int y = (getHeight() - h) / 2;
ImageIcon img_icon=(ImageIcon) jLabel1.getIcon();
g.drawImage(img_icon.getImage(), x, y, w, h, null);
}
public void setScale(float x, float y) {
this.scaleX = x;
this.scaleY = y;
jLabel1.revalidate();
jLabel1.repaint();
}
public Vector<Point> return_vector() {
return this.v;
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
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(TrialZoom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TrialZoom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TrialZoom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TrialZoom.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 TrialZoom().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JSlider jSlider2;
// End of variables declaration
}
First, start with a component that is capable of managing the image and scaling. This should be as self contained as you can make it. This allows you to decouple your program and focus on individual responsibilities of the application.
Next, you need to maintain a list of normalised points. The reason for normalising them is to ensure that the points will continue to be rendered at the right locations when the image scaled...
Take a look at Performing Custom Painting for more details
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ZoomExample {
public static void main(String[] args) {
new ZoomExample();
}
public ZoomExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ZoomPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ZoomPane extends JPanel {
private JSlider slider;
private ZoomImagePane zoomImagePane;
public ZoomPane() {
zoomImagePane = new ZoomImagePane();
slider = new JSlider(1, 200);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
zoomImagePane.setScale((float) slider.getValue() / 100f);
}
});
setLayout(new BorderLayout());
add(slider, BorderLayout.SOUTH);
add(zoomImagePane);
slider.setValue(100);
}
}
public class ZoomImagePane extends JPanel {
private float scale = 0f;
private BufferedImage master;
private Image scaled;
private List<Point2D> clickPoints;
public ZoomImagePane() {
clickPoints = new ArrayList<>(25);
try {
master = ImageIO.read(new File("/path/to/image"));
setScale(1f);
} catch (IOException ex) {
ex.printStackTrace();
}
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
Point2D scaledPoint = new Point2D.Float();
int xOffset = (getWidth() - scaled.getWidth(null)) / 2;
int yOffset = (getHeight() - scaled.getHeight(null)) / 2;
float x = (float)(p.x - xOffset) / (float)scaled.getWidth(null);
float y = (float)(p.y - yOffset) / (float)scaled.getHeight(null);
scaledPoint.setLocation(x, y);
clickPoints.add(scaledPoint);
repaint();
}
});
}
protected void setScale(float value) {
if (scale != value) {
scale = value;
scaled = master.getScaledInstance((int) ((float) master.getWidth() * scale), -1, Image.SCALE_SMOOTH);
revalidate();
repaint();
}
}
#Override
public Dimension getPreferredSize() {
Dimension size = new Dimension(200, 200);
if (scaled != null) {
size = new Dimension(scaled.getWidth(this), scaled.getHeight(this));
}
return size;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (scaled != null) {
int x = (getWidth() - scaled.getWidth(this)) / 2;
int y = (getHeight() - scaled.getHeight(this)) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(scaled, x, y, this);
g2d.setColor(Color.RED);
for (Point2D p : clickPoints) {
int xPos = x + ((int)(p.getX() * scaled.getWidth(this)) - 5);
int yPos = y + ((int)(p.getY() * scaled.getHeight(this)) - 5);
g2d.fillOval(xPos, yPos, 10, 10);
}
g2d.dispose();
}
}
}
}

Jpanel resize on repaint

i am having a scaling operation performed in the below code. The two sliders in the form are X and Y parameters for an scaling affine transformation. My ask here is when i change the slider the image is getting scaled, how do i dynamically resize my jpanel in which this image is getting painted.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package newpackage;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
*
* #author ABC
*/
public class Swon extends javax.swing.JFrame {
final BufferedImage img;
/**
* Creates new form Swon
*/
public Swon() throws IOException{
BufferedImage im=ImageIO.read(new File("C:/Users/ABC/Desktop/I-RIX2012_Final_logo_out.jpg"));
this.img=new BufferedImage(im.getWidth(),im.getWidth(),BufferedImage.TYPE_BYTE_GRAY);
this.img.getGraphics().drawImage(im, 0, 0, null);
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() {
jPanel1 = new javax.swing.JPanel(){
// #Override
// public void paint(Graphics g)
// {
// super.paint(g);
// g.drawImage(img.getScaledInstance(this.getWidth(), this.getHeight(), Image.SCALE_FAST),0,0,null);
// }
};
jSlider1 = new javax.swing.JSlider();
jSlider2 = new javax.swing.JSlider();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jPanel1.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
jPanel1ComponentResized(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 268, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 209, Short.MAX_VALUE)
);
jSlider1.setMaximum(5);
jSlider1.setValue(1);
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
jSlider2.setMaximum(5);
jSlider2.setValue(1);
jSlider2.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider2StateChanged(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()
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSlider2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(242, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(33, 33, 33)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSlider2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(38, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jPanel1ComponentResized(java.awt.event.ComponentEvent evt) {
// TODO add your handling code here:
// AffineTransform f=new AffineTransform();
}
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
AffineTransform scale = AffineTransform.getScaleInstance(jSlider1.getValue(),jSlider2.getValue());
AffineTransformOp op3 = new AffineTransformOp(scale, AffineTransformOp.TYPE_BILINEAR);
BufferedImage scaling = new BufferedImage(this.img.getHeight(), this.img.getWidth(), this.img.getType());
BufferedImage img1=op3.filter(this.img, scaling);
jPanel1.getGraphics().drawImage(img1.getScaledInstance(jPanel1.getWidth(), jPanel1.getHeight(), Image.SCALE_FAST), 0, 0, null);
}
private void jSlider2StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
AffineTransform scale = AffineTransform.getScaleInstance(jSlider1.getValue(),jSlider2.getValue());
AffineTransformOp op3 = new AffineTransformOp(scale, AffineTransformOp.TYPE_BILINEAR);
BufferedImage scaling = new BufferedImage(this.img.getHeight(), this.img.getWidth(), this.img.getType());
BufferedImage img1=op3.filter(this.img, scaling);
jPanel1.getGraphics().drawImage(img1.getScaledInstance(jPanel1.getWidth(), jPanel1.getHeight(), Image.SCALE_FAST), 0, 0, 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(Swon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Swon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Swon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Swon.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() {
try {
new Swon().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Swon.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify
public javax.swing.JPanel jPanel1;
private javax.swing.JSlider jSlider1;
private javax.swing.JSlider jSlider2;
// End of variables declaration
}
Alright, firstly, don't do this.img.getGraphics().drawImage(im, 0, 0, null), when the panel is repainted, the image would not be updated. You need to override the paintComponent method of a JComponent (prefer JPanel) and repaint the image at the appropriate scale.
Secondly, you need to place the image panel onto a layout that is capable of actually caring about the size of the panel (such as GridBagLayout). To do this, override the getPreferredSize method and return the size of the scaled image...
public class ResizableImagePane {
public static void main(String[] args) {
new ResizableImagePane();
}
public ResizableImagePane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ScalerPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class ScalerPane extends JPanel {
private JSlider slider;
private ImagePane imagePane;
public ScalerPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
imagePane = new ImagePane();
add(imagePane, gbc);
gbc.gridy = 1;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
slider = new JSlider();
slider.setMinimum(1);
slider.setMaximum(100);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(slider, gbc);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent ce) {
imagePane.setZoom(slider.getValue() / 100f);
}
});
slider.setValue(100);
}
}
protected class ImagePane extends JPanel {
private BufferedImage background;
private Image scaled;
private float zoom;
public ImagePane() {
try {
background = ImageIO.read(new File("path/to/your/image"));
} catch (IOException ex) {
ex.printStackTrace();
}
setZoom(1f);
setBorder(new LineBorder(Color.RED));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(scaled.getWidth(this), scaled.getHeight(this));
}
public void setZoom(float zoom) {
this.zoom = zoom;
int width = Math.round(background.getWidth() * zoom);
scaled = background.getScaledInstance(width, -1, Image.SCALE_SMOOTH);
invalidate();
revalidate();
repaint();
}
public float getZoom() {
return zoom;
}
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
int x = (getWidth() - scaled.getWidth(this)) / 2;
int y = (getHeight() - scaled.getHeight(this)) / 2;
grphcs.drawImage(scaled, x, y, this);
}
}
}

Categories