Resize the panel without revalidation - java

I have aJPanel in which I draw lines to create an illusion of pencil. This panel is in aScrollPane.
When I resize the panel one call to revalidate() method is automatically placed and all my drawn lines in this panel are gone. Is there any way to keep my drawn line in the panel with the new size ?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* #author Sanjeev
*/
public class WorkArea extends JFrame implements ActionListener, MouseListener, MouseMotionListener
{
private final int PEN_OP = 1;
private final int ERASER_OP = 2;
private final int SCROLL_OP = 3;
private int mousex = 0;
private int mousey = 0;
private int prevx = 0;
private int prevy = 0;
private boolean initialPen = true;
private boolean initialEraser = true;
private int eraserLength = 5;
private int opStatus = PEN_OP;
private Color mainColor = new Color(0,0,0);
private int drawPanelHeight =1000;
public WorkArea()
{
initComponents();
setLocationRelativeTo(null);
pencilButton.addActionListener(this);
eraserButton.addActionListener(this);
drawPanel.addMouseMotionListener(this);
drawPanel.addMouseListener(this);
drawPanel.add(new TestPane());
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
private void initComponents() {
headerPanel = new javax.swing.JPanel();
backButton = new javax.swing.JLabel();
headerImage = new javax.swing.JLabel();
controlPanel = new javax.swing.JPanel();
scrollButton = new javax.swing.JButton();
pencilButton = new javax.swing.JButton();
eraserButton = new javax.swing.JButton();
drawingPanel = new javax.swing.JPanel();
drawingScrollPane = new javax.swing.JScrollPane();
drawPanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("v0.1");
setBackground(new java.awt.Color(237, 254, 255));
setBounds(new java.awt.Rectangle(0, 0, 513, 693));
setResizable(false);
headerPanel.setBackground(new java.awt.Color(237, 254, 255));
headerPanel.setPreferredSize(new java.awt.Dimension(513, 25));
headerPanel.setLayout(null);
backButton.setBackground(new java.awt.Color(237, 254, 255));
backButton.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
backButton.setForeground(new java.awt.Color(255, 255, 255));
backButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/back-arrow.png"))); // NOI18N
backButton.setText("Back");
backButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
backButton.setPreferredSize(new java.awt.Dimension(40, 20));
headerPanel.add(backButton);
backButton.setBounds(0, 3, 40, 20);
headerImage.setBackground(new java.awt.Color(237, 254, 255));
headerImage.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
headerImage.setForeground(new java.awt.Color(255, 255, 255));
headerImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/topbar_ipad_wide.png"))); // NOI18N
headerImage.setText("Work Area");
headerImage.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
headerImage.setPreferredSize(new java.awt.Dimension(513, 25));
headerPanel.add(headerImage);
headerImage.setBounds(0, 0, 513, 25);
controlPanel.setBackground(new java.awt.Color(237, 254, 255));
controlPanel.setPreferredSize(new java.awt.Dimension(90, 670));
controlPanel.setLayout(null);
scrollButton.setBackground(new java.awt.Color(237, 254, 255));
scrollButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/up_down_ipad.png"))); // NOI18N
scrollButton.setPreferredSize(new java.awt.Dimension(60, 60));
scrollButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
scrollButtonMouseClicked(evt);
}
});
controlPanel.add(scrollButton);
scrollButton.setBounds(20, 570, 60, 60);
pencilButton.setBackground(new java.awt.Color(237, 254, 255));
pencilButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pencil_ipad.png"))); // NOI18N
pencilButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
pencilButtonMouseClicked(evt);
}
});
controlPanel.add(pencilButton);
pencilButton.setBounds(20, 450, 60, 60);
eraserButton.setBackground(new java.awt.Color(237, 254, 255));
eraserButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/eraser_ipad.png"))); // NOI18N
eraserButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
eraserButtonMouseClicked(evt);
}
});
controlPanel.add(eraserButton);
eraserButton.setBounds(20, 510, 60, 60);
drawingPanel.setBackground(new java.awt.Color(237, 254, 255));
drawingPanel.setPreferredSize(new java.awt.Dimension(420, 670));
drawingPanel.setLayout(null);
drawingScrollPane.setBorder(null);
drawingScrollPane.setPreferredSize(new java.awt.Dimension(423, 1000));
drawPanel.setBackground(new java.awt.Color(237, 254, 255));
drawPanel.setPreferredSize(new java.awt.Dimension(400, 1000));
drawPanel.setLayout(null);
drawingScrollPane.setViewportView(drawPanel);
drawingPanel.add(drawingScrollPane);
drawingScrollPane.setBounds(0, 0, 424, 670);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 513, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(headerPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(controlPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 423, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 93, Short.MAX_VALUE)
.addComponent(drawingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 420, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 693, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(headerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 668, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 23, Short.MAX_VALUE)
.addComponent(controlPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 670, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 23, Short.MAX_VALUE)
.addComponent(drawingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 670, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
pack();
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand() == "Pen")
opStatus = PEN_OP;
if (e.getActionCommand() == "Eraser")
opStatus = ERASER_OP;
if(e.getActionCommand() == "Scroll")
opStatus = SCROLL_OP;
}
private void pencilButtonMouseClickedTest(java.awt.event.MouseEvent evt)
{
opStatus = PEN_OP;
Graphics g = drawPanel.getGraphics();
if (initialPen)
{
setGraphicalDefaults(evt);
initialPen = false;
g.drawLine(prevx,prevy,mousex,mousey);
}
if (mouseHasMoved(evt))
{
mousex = evt.getX();
mousey = evt.getY();
g.drawLine(prevx,prevy,mousex,mousey);
prevx = mousex;
prevy = mousey;
}
}
private void eraserButtonMouseClickedTest(java.awt.event.MouseEvent evt)
{
opStatus = ERASER_OP;
Graphics g = drawPanel.getGraphics();
if (initialEraser)
{
setGraphicalDefaults(evt);
initialEraser = false;
mousex = evt.getX();
mousey = evt.getY();
System.out.println("Initial Eraser ::::::::x's value is : "+prevx+" , "+mousey+" and y's value is : "+mousex+" , "+mousey);
g.setColor(new java.awt.Color(237,254,255));
g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
//g.setColor(Color.black); //Eraser Border
g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
prevx = mousex;
prevy = mousey;
}
if (mouseHasMoved(evt))
{
System.out.println("Eraser ::::::::x's value is : "+prevx+" , "+mousey+" and y's value is : "+mousex+" , "+mousey);
g.setColor(new java.awt.Color(237,254,255));
g.drawRect(prevx-eraserLength, prevy-eraserLength,eraserLength*2,eraserLength*2);
mousex = evt.getX();
mousey = evt.getY();
/* Draw eraser block to panel */
g.setColor(new java.awt.Color(237,254,255));
g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
g.setColor(Color.black);//Eraser Border
g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
prevx = mousex;
prevy = mousey;
}
}
private void scrollButtonMouseClicked(java.awt.event.MouseEvent evt) {
opStatus = SCROLL_OP;
drawingScrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e)
{
int extent,curValue;
extent = drawingScrollPane.getVerticalScrollBar().getModel().getExtent();
curValue = drawingScrollPane.getVerticalScrollBar().getValue()+extent;
if(curValue==drawPanel.getHeight())
{
System.out.println("value of scroll equals to Max value....");
drawPanel.setPreferredSize(new Dimension(423,drawPanelHeight*4));
}
System.out.println("Value: " + curValue + " Max: " + drawingScrollPane.getVerticalScrollBar().getMaximum());
}
});
}
private void eraserButtonMouseClicked(java.awt.event.MouseEvent evt) {
eraserButtonMouseClickedTest(evt);
updateMouseCoordinates(evt);
}
private void pencilButtonMouseClicked(java.awt.event.MouseEvent evt) {
opStatus = PEN_OP;
}
public boolean mouseHasMoved(MouseEvent e)
{
return (mousex != e.getX() || mousey != e.getY());
}
public void setGraphicalDefaults(MouseEvent e)
{
mousex = e.getX();
mousey = e.getY();
prevx = e.getX();
prevy = e.getY();
}
#Override
public void mouseDragged(MouseEvent e)
{
updateMouseCoordinates(e);
switch (opStatus)
{
case PEN_OP : pencilButtonMouseClickedTest(e);
break;
case ERASER_OP: eraserButtonMouseClicked(e);
break;
case SCROLL_OP: scrollButtonMouseClicked(e);
break;
}
}
public void mouseReleased(MouseEvent e)
{
updateMouseCoordinates(e);
switch (opStatus)
{
case PEN_OP : releasedPen();
break;
case ERASER_OP : releasedEraser();
break;
}
}
public void mouseEntered(MouseEvent e)
{
updateMouseCoordinates(e);
}
public void releasedPen()
{
initialPen = true;
}
public void releasedEraser()
{
initialEraser = true;
Graphics g = drawPanel.getGraphics();
g.setColor(mainColor.white);
g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
}
public void updateMouseCoordinates(MouseEvent e)
{
String xCoor ="";
String yCoor ="";
if (e.getX() < 0) xCoor = "0";
else
{
xCoor = String.valueOf(e.getX());
}
if (e.getY() < 0) xCoor = "0";
else
{
yCoor = String.valueOf(e.getY());
}
}
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(WorkArea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(WorkArea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(WorkArea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(WorkArea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new WorkArea().setVisible(true);
}
});
}
private javax.swing.JLabel backButton;
private javax.swing.JPanel controlPanel;
private javax.swing.JPanel drawPanel;
private javax.swing.JPanel drawingPanel;
private javax.swing.JScrollPane drawingScrollPane;
private javax.swing.JButton eraserButton;
private javax.swing.JLabel headerImage;
private javax.swing.JPanel headerPanel;
private javax.swing.JButton pencilButton;
private javax.swing.JButton scrollButton;
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
updateMouseCoordinates(e);
}
#Override
public void mouseMoved(MouseEvent e) {
updateMouseCoordinates(e);
}
#Override
public void mousePressed(MouseEvent e) {
updateMouseCoordinates(e);
}
}

I assume you are drawing to the JPanel by using getGraphics() and rendering your out put to it.
You have now seen why you shouldn't do this. When the component is repainted, anything previously painted to is wiped cleaned and you are expected to repaint the contents.
Start by overriding paintComponent and updating all the lines within this method (don't forget to call super.paintComponent
See Performing Custom Painting and Painting in AWT and Swing for more details
For example..
Drawing a rectangle that won't disappear in next paint
MouseEvent is not registering a release when I release the mouse button
Updated with example
This is a modified version of the answer to MouseEvent is not registering a release when I release the mouse button which includes a scroll pane...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
public class MouseDraggedTest {
public static void main(String[] args) {
new MouseDraggedTest();
}
public MouseDraggedTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(new TestPane()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Map<Point, List<Point>> mapPoints;
private Point currentPoint;
public TestPane() {
mapPoints = new HashMap<>(25);
MouseAdapter mouseListener = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
currentPoint = e.getPoint();
mapPoints.put(currentPoint, new ArrayList<Point>(25));
}
#Override
public void mouseReleased(MouseEvent e) {
List<Point> points = mapPoints.get(currentPoint);
if (points.isEmpty()) {
mapPoints.remove(currentPoint);
}
currentPoint = null;
}
#Override
public void mouseDragged(MouseEvent me) {
List<Point> points = mapPoints.get(currentPoint);
points.add(me.getPoint());
repaint();
}
};
addMouseListener(mouseListener);
addMouseMotionListener(mouseListener);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 800);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Point startPoint : mapPoints.keySet()) {
List<Point> points = mapPoints.get(startPoint);
for (Point p : points) {
if (startPoint != null) {
g.drawLine(startPoint.x, startPoint.y, p.x, p.y);
}
startPoint = p;
}
}
}
}
}
Updated with a BufferedImage example
Because you need to supply more operations than just drawing, you may find it easier to use BufferedImage as your primary drawing surface and render this to your DrawingPanel
import java.awt.BasicStroke;
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.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyPicture {
public static void main(String[] args) {
new MyPicture();
}
public MyPicture() {
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public enum DrawOperation {
Draw,
Erase
}
public class TestPane extends JPanel {
private DrawOperation op;
private JToggleButton pencil;
private JToggleButton eraser;
private DrawPane drawPane;
public TestPane() {
setLayout(new BorderLayout());
drawPane = new DrawPane();
MouseAdapter adapter = new MouseAdapter() {
private Point startPoint;
#Override
public void mouseEntered(MouseEvent e) {
drawPane.updateDrawCursor(e.getPoint(), op);
}
#Override
public void mouseExited(MouseEvent e) {
drawPane.removeDrawCursor();
}
#Override
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent e) {
startPoint = null;
}
#Override
public void mouseDragged(MouseEvent e) {
drawPane.applyOperation(startPoint, e.getPoint(), op);
drawPane.updateDrawCursor(e.getPoint(), op);
startPoint = e.getPoint();
}
#Override
public void mouseMoved(MouseEvent e) {
drawPane.updateDrawCursor(e.getPoint(), op);
}
};
drawPane.addMouseListener(adapter);
drawPane.addMouseMotionListener(adapter);
JPanel operations = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
pencil = new JToggleButton("Draw");
eraser = new JToggleButton("Erase");
ButtonGroup bgOps = new ButtonGroup();
bgOps.add(pencil);
bgOps.add(eraser);
operations.add(pencil, gbc);
operations.add(eraser, gbc);
pencil.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
op = DrawOperation.Draw;
}
});
eraser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
op = DrawOperation.Erase;
}
});
add(operations, BorderLayout.WEST);
add(new JScrollPane(drawPane));
}
}
public class DrawPane extends JPanel {
private BufferedImage image;
private Shape drawCursor;
private Point cursorPoint;
private int eraseSize = 20;
public DrawPane() {
image = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, 400, 400);
g2d.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (image != null) {
g2d.drawImage(image, 0, 0, this);
}
if (drawCursor != null && cursorPoint != null) {
int x = (cursorPoint.x - (drawCursor.getBounds().width) / 2);
int y = (cursorPoint.y - (drawCursor.getBounds().height) / 2);
g2d.translate(x, y);
g2d.draw(drawCursor);
g2d.translate(-x, -y);
}
g2d.dispose();
}
public void updateDrawCursor(Point point, DrawOperation op) {
cursorPoint = point;
if (op != null) {
switch (op) {
case Draw:
drawCursor = new Ellipse2D.Float(0, 0, 4, 4);
break;
case Erase:
drawCursor = new Ellipse2D.Float(0, 0, eraseSize, eraseSize);
break;
}
} else {
drawCursor = null;
}
repaint();
}
protected void removeDrawCursor() {
drawCursor = null;
repaint();
}
protected void applyOperation(Point fromPoint, Point toPoint, DrawOperation op) {
if (image != null) {
if (op != null) {
Graphics2D g2d = image.createGraphics();
switch (op) {
case Draw:
g2d.setColor(Color.BLACK);
g2d.draw(new Line2D.Float(fromPoint, toPoint));
break;
case Erase:
g2d.setColor(Color.WHITE);
g2d.setStroke(new BasicStroke(eraseSize));
g2d.draw(new Line2D.Float(fromPoint, toPoint));
break;
}
g2d.dispose();
}
}
repaint();
}
}
}

Related

I want to be applied paintComponent individually

I make a PaintBrush.
I want to apply the line in a different color, but all the lines change to the same color.
I painted it white to create the eraser function, and when I use the eraser, all the lines become white, and when I select a different color, the lines reappear with the color I chose.
//choose the color
public void ColorBox() {
ArrayList<Color> clist = new ArrayList<>();
clist.add(Color.RED);
clist.add(Color.ORANGE);
clist.add(Color.YELLOW);
clist.add(Color.GREEN);
clist.add(Color.BLUE);
clist.add(Color.MAGENTA);
clist.add(Color.WHITE);
clist.add(Color.BLACK);
for (int i = 0; i < clist.size(); i++) {
JButton cbutton = new JButton();
cbutton.setBackground(clist.get(i));
cbutton.setBounds(500+50*i, 10, 37, 37); add(cbutton);
cbutton.addActionListener(e -> {
colour = cbutton.getBackground();
});
add(cbutton);
}
}
public void Pencil() {
JButton pen = new JButton(new ImageIcon("icon\\pencil.png"));
pen.setBounds(200, 10, 37, 37); add(pen);
pen.addActionListener(e -> {
draw = true; erase = false;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
plist.add(new Point(x, y));
repaint();
}
});
});
}
public void Eraser() {
JButton eraser = new JButton(new ImageIcon("icon\\eraser.png"));
eraser.setBounds(250, 10, 37, 37); add(eraser);
eraser.addActionListener(e -> {
draw = false; erase = true;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
elist.add(new Point(x, y));
repaint();
}
});
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (draw == true)
g.setColor(colour);
for (Point p : plist) {
g.fillOval(p.x, p.y, 5, 5);
}
if (erase == true)
g.setColor(Color.WHITE);
for (Point p : plist) {
g.fillOval(p.x, p.y, 5, 5);
}
}
Full Code
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class Board extends JPanel {
int x, y;
Color colour;
boolean draw = false; boolean erase = false;
Vector<Point> plist = new Vector<>();
Vector<Point> elist = new Vector<>();
public void ColorBox() {
ArrayList<Color> clist = new ArrayList<>();
clist.add(Color.RED);
clist.add(Color.ORANGE);
clist.add(Color.YELLOW);
clist.add(Color.GREEN);
clist.add(Color.BLUE);
clist.add(Color.MAGENTA);
clist.add(Color.WHITE);
clist.add(Color.BLACK);
for (int i = 0; i < clist.size(); i++) {
JButton cbutton = new JButton();
cbutton.setBackground(clist.get(i));
cbutton.setBounds(500+50*i, 10, 37, 37); add(cbutton);
cbutton.addActionListener(e -> {
colour = cbutton.getBackground();
});
add(cbutton);
}
}
public void Pencil() {
JButton pen = new JButton(new ImageIcon("icon\\pencil.png"));
pen.setBounds(200, 10, 37, 37); add(pen);
pen.addActionListener(e -> {
draw = true; erase = false;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
plist.add(new Point(x, y));
repaint();
}
});
});
}
public void Eraser() {
JButton eraser = new JButton(new ImageIcon("icon\\eraser.png"));
eraser.setBounds(250, 10, 37, 37); add(eraser);
eraser.addActionListener(e -> {
draw = false; erase = true;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
elist.add(new Point(x, y));
repaint();
}
});
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (draw == true)
g.setColor(colour);
for (Point p : plist) {
g.fillOval(p.x, p.y, 5, 5);
}
if (erase == true)
g.setColor(Color.WHITE);
for (Point p : plist) {
g.fillOval(p.x, p.y, 5, 5);
}
}
public Board() {
setLayout(null);
this.Pencil();
this.Eraser();
this.ColorBox();
setBackground(Color.WHITE);
}
}
public class PaintBrush extends JFrame {
public PaintBrush() {
setSize(1200, 600);
setTitle("그림판");
add(new Board());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
PaintBrush p = new PaintBrush();
}
}
How can I do?
So, the basic idea is, you need to keep track of the color each "pixel" is meant to be painted with.
I'd start by creating some kind of "drawing" entity to track this, for example...
public class Pixel {
private Point point;
private Color color;
public Pixel(Point point, Color color) {
this.point = point;
this.color = color;
}
public Point getPoint() {
return point;
}
public Color getColor() {
return color;
}
}
When the user selects a color, you apply it to an instance field and when the user drags the mouse, you create a new instance of Pixel with the selected color, for example...
int x = e.getX();
int y = e.getY();
Pixel pixel = new Pixel(e.getPoint(), getPixelColor());
pixels.add(pixel);
repaint();
Runnable example...
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.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public final class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Pixel {
private Point point;
private Color color;
public Pixel(Point point, Color color) {
this.point = point;
this.color = color;
}
public Point getPoint() {
return point;
}
public Color getColor() {
return color;
}
}
public class MainPane extends JPanel {
private CanvasPane canvasPane;
public MainPane() {
setLayout(new BorderLayout());
canvasPane = new CanvasPane();
add(canvasPane);
Color[] colors = new Color[]{
Color.RED,
Color.ORANGE,
Color.YELLOW,
Color.GREEN,
Color.BLUE,
Color.MAGENTA,
Color.WHITE,
Color.BLACK
};
JPanel colorSelectionPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.weightx = 1;
ButtonGroup bg = new ButtonGroup();
for (Color color : colors) {
JToggleButton btn = new JToggleButton();
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
btn.setForeground(color);
btn.setBackground(color);
btn.setOpaque(true);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
canvasPane.setPixelColor(color);
}
});
colorSelectionPane.add(btn, gbc);
bg.add(btn);
}
add(colorSelectionPane, BorderLayout.NORTH);
}
}
public class CanvasPane extends JPanel {
private List<Pixel> pixels = new ArrayList<>(128);
private Color pixelColor = Color.BLACK;
public CanvasPane() {
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Pixel pixel = new Pixel(e.getPoint(), getPixelColor());
pixels.add(pixel);
repaint();
}
});
}
public Color getPixelColor() {
return pixelColor;
}
public void setPixelColor(Color pixelColor) {
this.pixelColor = pixelColor;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Pixel pixel : pixels) {
g2d.setColor(pixel.getColor());
Point p = pixel.getPoint();
g2d.fillOval(p.x - 2, p.y - 2, 4, 4);
}
g2d.dispose();
}
}
}
Feedback...
This (and the eraser work flow)...
pen.addActionListener(e -> {
draw = true; erase = false;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
plist.add(new Point(x, y));
repaint();
}
});
});
is a bad idea. Every time you action either of these two, you are adding ANOTHER mouse listener, this is going to be become messy very quickly.
I would, personally, make a simple enum with DRAW and ERASE and maintain a simple instance field which described the current "pen action".
When erasing, instead of drawing "white" pixels, I would use a "collision detection" workflow and remove the pixels from the List if you run over them, but that's me.

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

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

Exception in thread "main" java.lang.UnsatisfiedLinkError: org.opencv.objdetect.CascadeClassifier.CascadeClassifier_1(Ljava/lang/String;)J

Hey guys I've tried all the search, so obviously google doesn't help me ^^
I'm sure, that I've installed the opencv Library right, because the thing worked with earlier prototypes. All I've done is that I changed the main method a bit, so please keep close tabs on this. Function of the program: It streams from the webcam, gets the middle of the head and draw a path which follows your head.
Error: Exception in thread "main" java.lang.UnsatisfiedLinkError: org.opencv.objdetect.CascadeClassifier.CascadeClassifier_1(Ljava/lang/String;)J
at org.opencv.objdetect.CascadeClassifier.CascadeClassifier_1(Native Method)
at org.opencv.objdetect.CascadeClassifier.<init>(CascadeClassifier.java:58)
at at.htlklu.tremoranalyzer.FaceDetector.<init>(FaceDetector.java:17)
at at.htlklu.tremoranalyzer.Main.initComponents(Main.java:110)
at at.htlklu.tremoranalyzer.Main.<init>(Main.java:40)
at at.htlklu.tremoranalyzer.Main.main(Main.java:198)
//Main method
package at.htlklu.tremoranalyzer;
//In diesem Zwischenschritt vom TremorAnalyzer funktioniert das Zeichnen
//im Panel mit Linien, dem gelben Punkt und das Rechteck
//um das Gesicht.
//Screenshot im Matura Ordner Screenshots.
//Datum: 4.11.2014
//------------------------
//Update: 3 Buttons die funktionieren
//Datum 7.11.2014
import java.awt.*;
import javax.swing.*;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.highgui.VideoCapture;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.LayoutStyle.ComponentPlacement;
public class Main {
private FaceDetector faceDetector;
private Frame frame;
private static FacePanelX facePanel;
public static boolean state = true;
public Main(){
initComponents();
initCamera();
initProcessing();
}
private void initProcessing() {
VideoCapture webCam = new VideoCapture(0);
Mat webcam_image = new Mat();
if (webCam.isOpened()) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (state) {
webCam.read(webcam_image);
if (!webcam_image.empty()) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
frame.setSize(webcam_image.width() +40 ,
webcam_image.height() +80 );
webcam_image = faceDetector.detect(webcam_image);
// Display the image
facePanel.matToBufferedImage(webcam_image);
Point center = faceDetector.getCenter();
if (center != null) {
facePanel.setFaceCenter(center);
facePanel.repaint();
facePanel.invalidate();
}
} else {
System.out.println(" --(!) No captured frame from webcam !");
webCam.release();
break;
}
}
}
webCam.release();
}
private void initCamera() {
}
private void initComponents() {
frame = new JFrame("WebCam Capture - Face detection");
((JFrame) frame).setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
faceDetector = new FaceDetector();
frame.setSize(400, 400); // give the frame some size
frame.setBackground(Color.BLUE);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JButton btnStopRecord = new JButton("Stop Recording");
btnStopRecord.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
state = false;
}
});
JButton btndrawLine = new JButton("Draw Path");
btndrawLine.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
facePanel.getArray().clear();
drawLine();
}
});
GroupLayout groupLayout = new GroupLayout(((JFrame) frame).getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(facePanel, GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnExit, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(37)
.addComponent(btnStopRecord, GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)
.addGap(30)
.addComponent(btndrawLine, GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(facePanel, GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnExit, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btndrawLine, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnStopRecord, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
((JFrame) frame).getContentPane().setLayout(groupLayout);
frame.setVisible(true);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
e.printStackTrace();
}
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
facePanel = new FacePanelX();
}
public static void main(String arg[]) throws InterruptedException {
Main m = new Main();
}
private static void drawLine(){
facePanel.setDrawLineActive(!facePanel.isDrawLineActive());
}
}
//FacePanelX for drawing
package at.htlklu.tremoranalyzer;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.highgui.Highgui;
public class FacePanelX extends JPanel {
private BufferedImage image;
private boolean drawLineActive = false;
private ArrayList<Point> array = new ArrayList<Point>();
private Point faceCenter = new Point();
//---------------------------------------------------------------------------------------------------------------
// getters, setters
public ArrayList<Point> getArray() {
return array;
}
public void setArray(ArrayList<Point> array) {
this.array = array;
}
public Point getFaceCenter() {
return faceCenter;
}
public void setFaceCenter(Point point) {
this.faceCenter = point;
array.add(point);
}
// \getters, setters
//---------------------------------------------------------------------------------------------------------------
public FacePanelX() {
super();
}
//---------------------------------------------------------------------------------------------------------------
public boolean matToBufferedImage(Mat matrix) {
MatOfByte mb = new MatOfByte();
Highgui.imencode(".jpg", matrix, mb);
try {
this.image = ImageIO.read(new ByteArrayInputStream(mb.toArray()));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
// \ matToBufferedImage
//---------------------------------------------------------------------------------------------------------------
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (this.image == null)
return;
g2d.drawImage(this.image, 10, 10, this.image.getWidth(),
this.image.getHeight(), null);
drawFaceRect(g2d);
drawMiddle(g2d);
if(drawLineActive)
drawLine(g2d);
g2d.dispose();
}
// \ paintComponent
//---------------------------------------------------------------------------------------------------------------
public void drawFaceRect(Graphics2D g) {
g.setColor(Color.blue);
g.drawRect(((int) faceCenter.x - 31), (int) faceCenter.y - 31, 62, 62);
}
public void drawMiddle(Graphics2D g) {
g.setColor(Color.ORANGE);
g.fillOval(1280 / 2, 720 / 2, 10, 10);
}
// \ drawRect, drawMiddle
//---------------------------------------------------------------------------------------------------------------
public void drawLine(Graphics2D g) {
// state = false;
// if (!((int) faceCenter.x > 350 && (int) faceCenter.y > 280)
// || ((int) faceCenter.x < 280 && (int) faceCenter.y < 190)) {
// state = true;
// }
Point bufP = new Point(-1, -1);
g.setColor(Color.blue);
if (array.size() > 1) {
for (Point p : array) {
System.out.println("p: " + p.x + " " + p.y);
g.fillOval((int) p.x, (int) p.y, 2, 2);
if (!(bufP.x == -1 && bufP.y == -1)) {
g.drawLine((int) bufP.x, (int) bufP.y, (int) p.x, (int) p.y);
}
bufP.x = p.x;
bufP.y = p.y;
}
}
}
// \ methode drawLine
//---------------------------------------------------------------------------------------------------------------
public boolean isDrawLineActive() {
return drawLineActive;
}
public void setDrawLineActive(boolean drawLineActive) {
this.drawLineActive = drawLineActive;
}
}
//FaceDetector for CascadeClassifier
package at.htlklu.tremoranalyzer;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
public class FaceDetector {
private CascadeClassifier faceCascade;
private Point center;
/**
*
*/
public FaceDetector() {
faceCascade = new CascadeClassifier("src/lbpcascade_frontalface.xml");
if (faceCascade.empty()) {
System.out.println("--(!)Error loading cascade classifier\n");
return;
} else {
System.out.println("Face classifier loaded up");
}
}
/**
* Does some basic preprocessing
*
* #param inputframe The frame to be processed
* #return The processed matrix
*/
public Mat detect(Mat inputframe) {
Mat mRgba = new Mat();
Mat mGrey = new Mat();
MatOfRect faces = new MatOfRect();
inputframe.copyTo(mRgba);
inputframe.copyTo(mGrey);
Imgproc.cvtColor(mRgba, mGrey, Imgproc.COLOR_BGR2GRAY);
Imgproc.equalizeHist(mGrey, mGrey);
faceCascade.detectMultiScale(mGrey, faces);
for (Rect rect : faces.toArray()) {
center = new Point(rect.x + rect.width * 0.5, rect.y + rect.height
* 0.5);
}
return mRgba;
}
// ---------------------------------------------------------------------------------------------------------------
public Point getCenter() {
return center;
}
}
// \class FaceDetector
// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------

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

Why are graphics not appearing in JFrame?

Below I included two of the classes in my Java program (Launcher and Controls). In the both classes, they create a JFrame, draw a background image, and add lines of text. I have looked at the code over and over, but for some reason the background image and the line of text are not appearing in the second class (Controls). Could anyone please explain to me why this is happening?
Launcher Class:
import hungerGames.Display;
import hungerGames.RunGame;
import hungerGames.input.InputHandler;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Launcher extends JFrame implements Runnable {
public static final long serialVersionUID = 1L;
protected JPanel window = new JPanel();
private int width = 800;
private int height = 450;
boolean running = false;
Thread thread;
public Launcher(int id) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
InputHandler input = new InputHandler();
addKeyListener(input);
addFocusListener(input);
addMouseListener(input);
addMouseMotionListener(input);
startMenu();
}
public void updateFrame() {
if (InputHandler.dragged) {
Point p = getLocation();
if (InputHandler.MouseDX != InputHandler.MousePX || InputHandler.MouseDX != InputHandler.MousePX) {
setLocation(p.x + InputHandler.MouseDX - InputHandler.MousePX, p.y + InputHandler.MouseDY - InputHandler.MousePY);
}
}
}
public void startMenu() {
running = true;
thread = new Thread(this, "menu");
thread.start();
}
public void stopMenu() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running) {
try {
renderMenu();
} catch (IllegalStateException e) {
System.out.println("Handled");
}
updateFrame();
}
}
private void renderMenu() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 450);
try {
g.drawImage(ImageIO.read(Display.class.getResource("/main_menu.jpg")), 0, 0, 800, 450, null);
if (InputHandler.mouseX >= 50 && InputHandler.mouseX <= 100 && InputHandler.mouseY >= 290 && InputHandler.mouseY <= 325) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 10, 295, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new RunGame();
}
}
if (InputHandler.mouseX >= 50 && InputHandler.mouseX <= 320 && InputHandler.mouseY >= 390 && InputHandler.mouseY <= 425) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 10, 395, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new Controls();
}
}
if (InputHandler.mouseX >= 400 && InputHandler.mouseX <= 490 && InputHandler.mouseY >= 290 && InputHandler.mouseY <= 325) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 360, 295, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new Credits();
}
}
if (InputHandler.mouseX >= 400 && InputHandler.mouseX <= 440 && InputHandler.mouseY >= 390 && InputHandler.mouseY <= 425) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 360, 395, 30, 33, null);
if (InputHandler.MouseButton == 1) {
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 30));
g.drawString("By Lawrence Zhao", 210, 275);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Play", 50, 325);
g.drawString("Controls and Options", 50, 425);
g.drawString("Credits", 400, 325);
g.drawString("Exit", 400, 425);
g.dispose();
bs.show();
}
}
Controls Class:
import hungerGames.Display;
import hungerGames.input.InputHandler;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Controls extends JFrame{
public static final long serialVersionUID = 1L;
protected JPanel window = new JPanel();
private int width = 720;
private int height = 450;
private Rectangle rResolution;
private Choice resolution = new Choice();
public Controls() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
InputHandler input = new InputHandler();
addKeyListener(input);
addFocusListener(input);
addMouseListener(input);
addMouseMotionListener(input);
renderControls();
drawButtons();
stopMenuThread();
}
private void stopMenuThread() {
Display.getLauncherInstance().stopMenu();
}
private void drawButtons() {
rResolution = new Rectangle(50,100, 100, 25);
resolution.setBounds(rResolution);
resolution.add("640, 400");
resolution.add("800, 600");
resolution.add("1024, 768");
resolution.select(1);
add(resolution);
}
private void renderControls() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 720, 450);
try {
g.drawImage(ImageIO.read(Display.class.getResource("/controls.jpg")),0, 0, 720, 450, null);
if (InputHandler.mouseX >= 360 && InputHandler.mouseX <= 400 && InputHandler.mouseY >=270 && InputHandler.mouseY <=305) {
g.drawImage(ImageIO.read(Controls.class.getResource("/pin.png")),360,270, 30, 33, null);
if (InputHandler.MouseButton == 1) {
Display.selection = resolution.getSelectedIndex();
dispose();
new Launcher(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Exit", 400, 300);
g.dispose();
bs.show();
}
}
It's clear that you don't understand how the buffering strategy is suppose to work.
I'd suggest you have a read through Double Buffering for some clues.
(ps, I don't have much experience with this side of the API either, but I got your code to work by simply reading through the above linked tut)
Update
Seems to work just fine for me...
Some notes.
Pre-load your images, otherwise you're wasting your time double buffering as the IO is going to slow you down.
Make sure your images exist and are begin loaded properly
.
public class BadPaint03 {
public static void main(String[] args) {
new BadPaint03();
}
public BadPaint03() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Controls frame = new Controls();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public class Controls extends JFrame {
private int width = 720;
private int height = 450;
private Rectangle rResolution;
protected JPanel window = new JPanel();
private BufferedImage background;
public Controls() {
try {
background = ImageIO.read(new File("/path/to/your/image"));
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
renderControls();
try {
Thread.sleep(1000 / 24);
} catch (InterruptedException ex) {
Logger.getLogger(BadPaint03.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}).start();
}
private void renderControls() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 720, 450);
if (background != null) {
int x = (720 - background.getWidth()) / 2;
int y = (450 - background.getHeight()) / 2;
g.drawImage(background, x, y, null);
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Exit", 400, 300);
g.dispose();
bs.show();
}
}
}

Categories