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);
}
}
}
Related
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();
}
}
This question already has answers here:
Adding images on Java JFrame - Netbeans
(3 answers)
Closed 6 years ago.
I'm creating a Java UI for a school project. I have 4 buttons and an image in the JFrame, I want to be able to perform a task on the Image with each button. Each time I press the button it will overwrite the Image using the buttons function. I have the buttons and functions working but I'm clueless at how to add the Image to the JFrame. Do I use a Jpanel or a canvas to put the image onto the frame. I used the netbeans GUI builder. Here is my code in a compressed form
//import static NewJFrame.plotWidth;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ij.process.ImageConverter;
import ij.process.ImageProcessor;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Polygon;
public class my_JframePlugin extends javax.swing.JFrame {
static int plotWidth =400;
static double angleInDegrees = 40;
static double angle = (angleInDegrees/360.0)*2.0*Math.PI;
static int polygonMultiplier = 100;
static boolean oneToOne;
double picsize;
ImagePlus img = IJ.openImage();
ImageProcessor imgP = img.getProcessor();
int[] x,y;
/**
* Creates new form NewJFrame
*/
public my_JframePlugin() {
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() {
jFileChooser1 = new javax.swing.JFileChooser();
canvas1 = new java.awt.Canvas();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = 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, 477, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 310, Short.MAX_VALUE)
);
jButton1.setText("FFT");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Inverse FFT");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("3D Plot");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Crop");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("Add Image");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(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()
.addGap(36, 36, 36)
.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)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(108, 108, 108))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(56, 56, 56))
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
IJ.log("FFT clicked");
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//ImagePlus myimage = img;
img = WindowManager.getCurrentImage();
if (img==null)
{
//IJ.noImage();
IJ.log("No Image selected");
return;
}
if (!showDialog())
return;
if (img.getType()!=ImagePlus.GRAY8)
{
ImageProcessor ip = img.getProcessor();
ip = ip.crop(); // duplicate
img = new ImagePlus("temp", ip);
new ImageConverter(img).convertToGray8();
}
ImageProcessor plot = makeSurfacePlot(img.getProcessor());
new ImagePlus("Surface Plot", plot).show();
IJ.register(Surface_Plotter.class);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
IJ.log("Inverse FFT clicked");
}
boolean showDialog()
{
GenericDialog gd = new GenericDialog("Surface Plotter");
gd.addNumericField("Width (pixels):", plotWidth, 0);
gd.addNumericField("Angle (-90-90 degrees):", angleInDegrees, 0);
gd.addNumericField("Polygon Multiplier (10-200%):", polygonMultiplier, 0);
gd.addCheckbox("One Polygon Per Line", oneToOne);
gd.showDialog();
if (gd.wasCanceled())
return false;
plotWidth = (int) gd.getNextNumber();
angleInDegrees = gd.getNextNumber();
polygonMultiplier = (int)gd.getNextNumber();
oneToOne = gd.getNextBoolean();
if (polygonMultiplier>400) polygonMultiplier = 400;
if (polygonMultiplier<10) polygonMultiplier = 10;
return true;
}
public ImageProcessor makeSurfacePlot(ImageProcessor ip)
{
double angle = (angleInDegrees/360.0)*2.0*Math.PI;
int polygons = (int)(plotWidth*(polygonMultiplier/100.0)/4);
if (oneToOne)
polygons = ip.getHeight();
double xinc = 0.8*plotWidth*Math.sin(angle)/polygons;
double yinc = 0.8*plotWidth*Math.cos(angle)/polygons;
boolean smooth = true;
IJ.showProgress(0.01);
ip.setInterpolate(true);
ip = ip.resize(plotWidth, polygons);
int width = ip.getWidth();
int height = ip.getHeight();
double min = ip.getMin();
double max = ip.getMax();
if (smooth)
ip.smooth();
//new ImagePlus("Image", ip).show();
int windowWidth =(int)(plotWidth+polygons*Math.abs(xinc) + 20.0);
int windowHeight = (int)(255+polygons*yinc + 10.0);
Image plot =IJ.getInstance().createImage(windowWidth, windowHeight);
Graphics g = plot.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, windowWidth, windowHeight);
x = new int[width+2];
y = new int[width+2];
double xstart = 10.0;
if (xinc<0.0)
xstart += Math.abs(xinc)*polygons;
double ystart = 0.0;
for (int row=0; row<height; row++) {
double[] profile = ip.getLine(0, row, width-1, row);
Polygon p = makePolygon(profile, xstart, ystart);
g.setColor(Color.white);
g.fillPolygon(p);
g.setColor(Color.black);
g.drawPolygon(p);
xstart += xinc;
ystart += yinc;
if ((row%5)==0) IJ.showProgress((double)row/height);
}
IJ.showProgress(1.0);
ip = new ColorProcessor(plot);
byte[] bytes = new byte[windowWidth*windowHeight];
int[] ints =(int[]) ip.getPixels();
for (int i=0; i<windowWidth*windowHeight; i++)
bytes[i] = (byte)ints[i];
ip = new ByteProcessor(windowWidth,windowHeight, bytes, null);
return ip;
}
Polygon makePolygon(double[] profile, double xstart, double ystart) {
int width = profile.length;
for (int i=0; i<width; i++)
x[i] =(int)( xstart+i);
for (int i=0; i<width; i++)
y[i] =(int)(ystart+255.0-profile[i]);
x[width] =(int)xstart+width-1;
y[width] = (int)ystart+255;
x[width+1] =(int)xstart;
y[width+1] = (int)ystart+255;
//for (int i=0; i<width; i++)
// IJ.write("dbg: "+i+" "+profile[i]+" "+x[i]+" "+y[i]);
return new Polygon(x, y, width+2);
}
/**
* #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(my_JframePlugin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(my_JframePlugin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(my_JframePlugin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(my_JframePlugin.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private java.awt.Canvas canvas1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JFileChooser jFileChooser1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
I just have no idea how to approach loading the image onto the frame
See the section from the Swing tutorial on How to Use Icons.
It shows you how to read an Image and use a JLabel to display the Image as an Icon.
The tutorial will also show you other Swing basics.
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();
}
}
}
I want to make smooth rounded corners for my swing application, but I can't get my desired result...
here's the screenshots:
1.setShape() for JFrame :
2.overriding paintComponent() method for JPanel instead of using setShape() :
3.setBackground(new Color(0, 0, 0, 0)) for JFrame :
well, but there's a problem with text quality:
before step 3 :
after step 3 :
guys I'm confused, I've searched many times but nothing helped me...
what should I do? please help me
here's the full code :
public class WelcomePage extends JFrame {
private Point initialClick;
private boolean end = false;
private JLabel jLabelAppTitle;
private JPanel jPanelExit;
private JLabel jLabelHint;
private int r = 220, g = 0, b = 0;
private int r2 = 10, g2 = 10, b2 = 10;
private boolean flag = false;
public WelcomePage() {
initComponents();
// setShape(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 15, 15));
centerLocation();
refreshPage();
}
public static void main(String args[]) {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
EventQueue.invokeLater(() -> FadeTransitions.fadeIn(new WelcomePage(), FadeTransitions.NORMAL_FADE, true));
}
private void refreshPage() {
Timer timer = new Timer(20, e -> {
if (!end) {
if (r == 220 && b == 0 && g < 220) {
g++;
} else if (g == 220 && b == 0 && r > 0) {
r--;
} else if (g == 220 && r == 0 && b < 220) {
b++;
} else if (b == 220 && r == 0 && g > 0) {
g--;
} else if (b == 220 && g == 0 && r < 220) {
r++;
} else if (r == 220 && g == 0 && b > 0) {
b--;
}
if (!flag) {
r2 += 5;
g2 += 5;
b2 += 5;
if (r2 == 250) {
flag = true;
}
} else {
r2 -= 5;
g2 -= 5;
b2 -= 5;
if (r2 == 10) {
flag = false;
}
}
jLabelAppTitle.setForeground(new Color(r, g, b));
jLabelHint.setForeground(new Color(r2, g2, b2));
} else {
((Timer) e.getSource()).stop();
}
});
timer.setCoalesce(true);
timer.setRepeats(true);
timer.start();
}
private void centerLocation() throws HeadlessException {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
final int x = (screenSize.width - this.getWidth()) / 2;
final int y = (screenSize.height - this.getHeight()) / 2;
this.setLocation(x, y);
}
#SuppressWarnings("unchecked")
private void initComponents() {
JPanel jPanelMain = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(qualityHints);
g2.setPaint(Color.WHITE);
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 25, 25);
g2.dispose();
}
};
jPanelExit = new JPanel();
JLabel jLabelExit = new JLabel();
JLabel jLabelWelcome = new JLabel();
jLabelAppTitle = new JLabel();
jLabelHint = new JLabel();
JButton jButtonGo = new JButton();
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("welcome to My App!");
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
close();
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
thisMouseDragged(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(MouseEvent evt) {
thisMousePressed(evt);
}
});
jPanelMain.setBackground(Color.WHITE);
jPanelExit.setBackground(new Color(160, 0, 20));
jLabelExit.setFont(new Font("Tahoma", Font.BOLD, 13));
jLabelExit.setForeground(new Color(255, 255, 255));
jLabelExit.setHorizontalAlignment(SwingConstants.CENTER);
jLabelExit.setText("X");
jLabelExit.setCursor(new Cursor(Cursor.HAND_CURSOR));
jLabelExit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
jLabelExitMouseClicked();
}
public void mouseEntered(MouseEvent evt) {
jLabelExitMouseEntered();
}
public void mouseExited(MouseEvent evt) {
jLabelExitMouseExited();
}
});
GroupLayout jPanelExitLayout = new GroupLayout(jPanelExit);
jPanelExit.setLayout(jPanelExitLayout);
jPanelExitLayout.setHorizontalGroup(
jPanelExitLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, jPanelExitLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabelExit, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE))
);
jPanelExitLayout.setVerticalGroup(
jPanelExitLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, jPanelExitLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabelExit, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
);
jLabelWelcome.setFont(new Font("Tahoma", 0, 25));
jLabelWelcome.setForeground(new Color(0, 0, 100));
jLabelWelcome.setHorizontalAlignment(SwingConstants.CENTER);
jLabelWelcome.setText("Welcome");
jLabelAppTitle.setFont(new Font("MV Boli", 0, 29));
jLabelAppTitle.setHorizontalAlignment(SwingConstants.CENTER);
jLabelAppTitle.setText("My Swing App");
jButtonGo.setBackground(new Color(100, 20, 80));
jButtonGo.setFont(new Font("Tahoma", 0, 15));
jButtonGo.setForeground(new Color(255, 255, 255));
jButtonGo.setText("GO");
jButtonGo.addActionListener(evt -> jButtonGoActionPerformed());
jLabelHint.setFont(new Font("Tahoma", 0, 11));
jLabelHint.setHorizontalAlignment(SwingConstants.CENTER);
jLabelHint.setText("press GO button");
javax.swing.GroupLayout jPanelMainLayout = new javax.swing.GroupLayout(jPanelMain);
jPanelMain.setLayout(jPanelMainLayout);
jPanelMainLayout.setHorizontalGroup(
jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMainLayout.createSequentialGroup()
.addContainerGap(48, Short.MAX_VALUE)
.addGroup(jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelMainLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanelExit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15))
.addGroup(jPanelMainLayout.createSequentialGroup()
.addGroup(jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabelWelcome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelAppTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addComponent(jLabelHint, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonGo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(48, Short.MAX_VALUE))))
);
jPanelMainLayout.setVerticalGroup(
jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMainLayout.createSequentialGroup()
.addComponent(jPanelExit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(64, 64, 64)
.addComponent(jLabelWelcome, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(98, 98, 98)
.addComponent(jLabelAppTitle)
.addGap(86, 86, 86)
.addComponent(jLabelHint)
.addGap(24, 24, 24)
.addComponent(jButtonGo, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(86, 86, 86))
);
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(0, 0, 0)
.addComponent(jPanelMain, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jPanelMain, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
pack();
}
private void thisMousePressed(MouseEvent evt) {
initialClick = evt.getPoint();
}
private void thisMouseDragged(MouseEvent evt) {
int thisX = this.getLocation().x;
int thisY = this.getLocation().y;
int xMoved = (thisX + evt.getX()) - (thisX + initialClick.x);
int yMoved = (thisY + evt.getY()) - (thisY + initialClick.y);
int x = thisX + xMoved;
int y = thisY + yMoved;
this.setLocation(x, y);
}
private void jLabelExitMouseClicked() {
close();
}
private void close() {
end = true;
FadeTransitions.fadeOut(this, FadeTransitions.FAST_FADE, FadeTransitions.EXIT_ON_CLOSE);
}
private void jLabelExitMouseEntered() {
jPanelExit.setBackground(new Color(200, 0, 20));
}
private void jLabelExitMouseExited() {
jPanelExit.setBackground(new Color(160, 0, 20));
}
private void jButtonGoActionPerformed() {
end = true;
FadeTransitions.run(this, new ServerManager(this), FadeTransitions.NORMAL_FADE, FadeTransitions.DISPOSE_ON_CLOSE);
}
}
thanks.
Sorry, not an answer, but hopefully at least one step towards an acceptable answer: From my analysis so far, it might be that this is simply a bug somewhere deep (deeeep!) inside the rendering pipeline.
The following MVCE shows two (undecorated) frames, each containing a button. They are equal, except for the background of the frames. For one frame, the color is transparent, and for the other one, it is opaque.
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TextRenderBug extends JFrame {
public static void main(String[] args)
{
setLookAndFeel();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI(new Color(0,0,0 ), 400);
createAndShowGUI(new Color(0,0,0,0), 600);
}
});
}
private static void setLookAndFeel()
{
try
{
for (UIManager.LookAndFeelInfo info :
UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void createAndShowGUI(Color background, int x)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.setBackground(background);
JButton b = new JButton("Text");
b.setFont(new Font("Tahoma", 0, 15));
f.getContentPane().add(b);
f.setBounds(x, 400, 200, 50);
f.setVisible(true);
}
}
It clearly shows that the text is rendered differently, solely depending on the background being transparent - and of course, this should not be the case.
(This is not Nimbus-specific, by the way: It also applies to other LookAndFeels. Just remove the line where the LaF is set).
What I found out so far:
The behavior is somehow caused by the drawString method of the sun.swing.SwingUtilities2 class
It does not appear in all components. It can be observed on JButton and JLabel, but not on a normal JComponent
Update: It also does not depend on the font (although with other fonts, the effect is not so noticable). When rendered correctly, the font looks a little bit more bold, but of course, it is not simply the same font as a Font.BOLD.
The painting process is rather complicated.
(OK, some of you might already have known the latter).
Here is an example that shows the last observations, maybe it can serve as a starting point for further research of others:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.lang.reflect.Method;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TextRenderBugTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI(new Color(0,0,0 ), 400);
createAndShowGUI(new Color(0,0,0,0), 600);
}
});
}
private static void createAndShowGUI(Color background, int x)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.setBackground(background);
JButton b = new JButton("Text");
b.setFont(new Font("Tahoma", 0, 15));
JComponent c = new ExampleComponent();
c.setFont(new Font("Tahoma", 0, 15));
f.getContentPane().setLayout(new GridLayout(0,1));
f.getContentPane().add(b);
f.getContentPane().add(c);
f.setBounds(x, 400, 200, 100);
f.setVisible(true);
}
static class ExampleComponent
//extends JComponent
extends JButton
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(getForeground());
g.drawString("Text", 10, 20);
drawStringWithSwingUtilities(g, 60, 20);
}
private void drawStringWithSwingUtilities(Graphics g, int x, int y)
{
try
{
Class<?> c = Class.forName("sun.swing.SwingUtilities2");
Method m = c.getMethod("drawString", JComponent.class,
Graphics.class, String.class, int.class, int.class);
m.invoke(null, this, g, "Text", x, y);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
I already tried to analyze this further, and played around with RenderingHints like KEY_TEXT_ANTIALIASING and KEY_TEXT_LCD_CONTRAST and other settings that are changed in the painting pipeline while it is heading towards the pixels that are finally placed on the screen, but no further insights until now.
(If you want to, you can add this information to your original question, then I'll delete this (not-)answer)
The only chance you have is working with regions. You will need to hardcode a bit and play with subtract, but eventually it will look fine. You can take a look at how it's done in mylyn's notification class: http://grepcode.com/file/repository.grepcode.com/java/eclipse.org/3.6/org.eclipse.mylyn.commons/ui/3.4.0/org/eclipse/mylyn/internal/provisional/commons/ui/AbstractNotificationPopup.java
Hope it helps, best of luck!
Edit: Just remembered this little tutorial which might help: http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/SWTShellcreateanonrectangularwindow.htm
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