Drawing on JPanel with paint(Graphics gr) - java

I tried to draw a simple rectangle on a JPanel wich is on a JFrame, but it didn't work. Can someone please give me some advices? Would be happy if someone could... I really tried hard, but I couldn figure out how to do this. This code is part of my "Snake" -program. All the rest works, in excep of this. Here is my Code:
package initialising_Package;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Initialising extends JPanel implements WindowListener,
ItemListener, ChangeListener, Runnable {
/**
* #param args
*/
private String name;
private JFrame frame;
private boolean fall = false;
private JSlider slider;
private JLabel lbl1, lbl2, lbl3, lbl4;
private JComboBox box1, box2, box3;
private String[] positionsx, positionsy, laenge;
private JPanel pnl1, pnl2, pnl3, pnlpnl;
private JButton btn;
private int beginningLenght, posX, posY;
private boolean start = false;
public Initialising() {
initStartFrame("Initialising");
}
public void initStartFrame(String name) {
frame = new JFrame(name);
frame.setLocation(300, 300);
frame.setSize(500, 350);
frame.setUndecorated(false);
frame.getContentPane().setLayout(new GridLayout(5, 1));
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setVisible(true);
frame.addWindowListener(this);
// GUI
slider = new JSlider(1, 100, 50);
slider.addChangeListener(this);
slider.setPaintTicks(false);
slider.setPaintTrack(true);
positionsx = new String[50];
positionsy = new String[50];
for (int i = 0, j = 0; i < 50; i++, j = j + 10) {
positionsx[i] = new String("" + j);
positionsy[i] = new String("" + j);
}
laenge = new String[45];
for (int i = 0; i < 45; i++) {
laenge[i] = "" + (i + 1);
}
box1 = new JComboBox(positionsx);
box1.addItemListener(this);
box2 = new JComboBox(positionsy);
box2.addItemListener(this);
box3 = new JComboBox(laenge);
box3.addItemListener(this);
lbl1 = new JLabel("Geschwindigkeit: ");
lbl2 = new JLabel("Startlaenge: ");
lbl3 = new JLabel("Position: ");
pnlpnl = new JPanel();
pnlpnl.setPreferredSize(new Dimension(95, 490));
pnlpnl.setBackground(Color.BLACK);
pnl1 = new JPanel();
pnl1.setLayout(new GridLayout(1, 2));
pnl2 = new JPanel();
pnl2.setLayout(new GridLayout(1, 2));
pnl3 = new JPanel();
pnl3.setLayout(new GridLayout(1, 3));
btn = new JButton("Snake!");
btn.setPreferredSize(new Dimension(80, 490));
pnl1.add(lbl1);
pnl1.add(slider);
pnl2.add(lbl2);
pnl2.add(box3);
pnl3.add(lbl3);
pnl3.add(box1);
pnl3.add(box2);
frame.add(pnlpnl);
frame.add(pnl1);
frame.add(pnl2);
frame.add(pnl3);
frame.add(btn);
// GUI
frame.validate();
frame.repaint();
}
public int getSpeed() {
return slider.getValue();
}
public int getBeginningLenght() {
return beginningLenght;
}
public int getPosX() {
return posX;
}
public int getPosY() {
return posY;
}
#Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosing(WindowEvent arg0) {
int z = JOptionPane.showConfirmDialog(frame,
"Willst du wirklich benden?", "Warnung", 0);
if (z == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
#Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Initialising init = new Initialising();
new Thread(init).start();
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(box1)) {
posX = Integer.parseInt((String) box1.getSelectedItem());
System.out.println("PosX: " + posX);
} else if (e.getSource().equals(box2)) {
posY = Integer.parseInt((String) box2.getSelectedItem());
System.out.println("PosY: " + posY);
} else if (e.getSource().equals(box3)) {
beginningLenght = Integer.parseInt((String) box3.getSelectedItem());
System.out.println("Beginning Lenght: " + beginningLenght);
System.out.println("H: " + pnlpnl.getHeight() + " B: "
+ pnlpnl.getWidth());
}
}
#Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(slider)) {
System.out.println("Speed: " + slider.getValue());
}
}
#Override
public void paintComponent(Graphics gr) {
super.paint(gr);
gr.setColor(Color.CYAN);
gr.fillRect(0, 0, 200, 200);
}
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
System.out.println("It works!!");
try {
Thread.sleep(800);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!start) {
}
repaint();
validate();
}
}
}

Remove the paintComponent from the JFrame. That did also call super.paint i.o. super.paintComponent.
pnlpnl = new JPanel() {
#Override
public void paintComponent(Graphics gr) {
super.paintComponent(gr);
gr.setColor(Color.CYAN);
gr.fillRect(0, 0, 200, 200);
}
};
In this paintComponent you can use the JFrame's fields.
As initStartFrame is called in the constructor it should not be overridable (the child class's version then would be called, without the child class being entirely initialized).
//Sometimes: public final void initStartFrame(String name) {
private void initStartFrame(String name) {
Start the frame as such:
// GUI
frame.validate();
//frame.repaint();
frame.pack();
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});

Related

How to get the JFrame with the JLabel? Error when attempted

I am attempting to make minesweeper. I understand that there is probably a better way to do this but this is how I am trying it.
My problem comes in the gridSquare class. This class is a JLabel and I need the frame that the gridSquare is contained within. I attempt to get the frame with the line minesweeperFrame frame = (minesweeperFrame) SwingUtilities.getWindowAncestor(this);. The problem I run into is that frame is null and never set to the gridSquares Frame. Is there any way to fix this.
Main.java
public class Main {
public static void main(String[] args) {
minesweeperFrame frame = new minesweeperFrame();
}
}
gridSquare.java
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Objects;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.Border;
public class gridSquare extends JLabel implements MouseListener{
Boolean isBomb = false;
int gridNum;
int n1,n2,n3,n4,n6,n7,n8,n9;
int bombNumber;
minesweeperFrame frame = (minesweeperFrame) SwingUtilities.getWindowAncestor(this);
gridSquare(int gridNum){
this.gridNum = gridNum;
n1 = gridNum - 10 - 1; //Top left
n2 = gridNum - 10 ; //Top center
n3 = gridNum - 10 + 1; //Top Left
n4 = gridNum - 1;//center left
n6 = gridNum + 1;//center right
n7 = gridNum + 10 -1;//Bottom Left
n8 = gridNum + 10; //Bottom Center
n9 = gridNum + 10 + 1; //Bottom Right
int neighbors[] = {n1,n2,n3,n4,n6,n7,n8,n9};
try {
//get the bomb number
for(int i:neighbors) {
if(frame.getSquares().get(i).getIsBomb()) { // if any neighbor is a bomb increase bombNumber ---------- frame.getSquares().get(i).getIsBomb()
bombNumber++;
}
System.out.println("WORKS");
}
}
catch(Exception e){
System.out.println(e);
}
setText("");
setHorizontalAlignment(JLabel.CENTER);
setVerticalAlignment(JLabel.CENTER);
setFont(new Font("Copperplate Gothic Bold",Font.PLAIN,20));
setForeground(new Color(0x000000)); //set font color CHANGE FOR EACHER NUMBER
setSize(50,50);
Border border = BorderFactory.createLineBorder(Color.darkGray,5);
setBorder(border);
setBackground(new Color(0xd3d3d3)); //set background color ----- change to #424242 after clicked
setOpaque(true);//display background color
addMouseListener(this);
}
public Boolean getIsBomb() {
return isBomb;
}
public void setIsBomb(Boolean isBomb) {
this.isBomb = isBomb;
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getButton() == MouseEvent.BUTTON1) {
setText("Left Click!");
if(isBomb) {
setText("bomb");
}
}
if(e.getButton() == MouseEvent.BUTTON3) {
setText("Flag");
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
mineSeeperFrame.java
import java.awt.GridLayout;
import java.awt.color.*;
import java.util.ArrayList;
import javax.swing.*;
public class minesweeperFrame extends JFrame{
private final int numColumns = 10;
private int numRows = 8;
int numBombs = 0;
ArrayList<gridSquare> squares = new ArrayList<gridSquare>();
minesweeperFrame(){
setTitle("Minesweeper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000,850);
setResizable(false);
setLayout(new GridLayout(numRows,numColumns,1,1));
setVisible(true);
//Fill Arraylist and add to frame
for(int i = 0; i < 80;i++) {
squares.add(new gridSquare(i));
add(squares.get(i));
}
//AddBombs
while(numBombs < 10) {
squares.get((int) (Math.random()*80)).setIsBomb(true);
numBombs++;
}
}
public ArrayList<gridSquare> getSquares() {
return squares;
}
public int getGridRows() {
return numRows;
}
public int getGridColumns() {
return numColumns;
}
}
You cannot do this during initialization:
minesweeperFrame frame = (minesweeperFrame) SwingUtilities.getWindowAncestor(this);
the component is being created and not added to the frame yet, so you get null.
Moreover you add the gridsquare to the frame directly, this is wrong, you must add it to the contentPane, please read:
https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html
https://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html

How to let user draw inside a canvas and save image afterwards?

I am trying to implement a free hand drawing Java applet which allows user to draw something in canvas (canvas is not the priority, it could be anything else as long I can save the image after (need to save it, because I have to display it later in a different place after pressing a button, any other solutions are welcome)). I found a code, which allows me to draw, but now I am having a trouble with drawing inside the canvas... And I have already spent few days with no results on that. Here is the code I have by now and a description below it:
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
import java.applet.*;
public class paintMozApplet extends Applet implements ActionListener
{
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
private GridLayout gL;
private JPanel buttons;
private JPanel panel;
private Button clear, createMoz;
private Label result_here;
private javax.swing.JPanel drawing;
private JPanel moz;
private Canvas canvas;
private draw draw;
public paintMozApplet()
{
draw = new draw();
gL = new GridLayout(1, 0);
buttons = new JPanel();
drawing = new JPanel();
moz = new JPanel();
canvas = new Canvas();
clear = new Button("clear");
createMoz = new Button("Create Moz");
buttons.add(clear);
buttons.add(createMoz);
result_here = new Label("Result here!");
moz.add(result_here);
drawing.add(canvas);
clear.addActionListener(this);
//canvas.add(draw);
//canvas.addMouseMotionListener(this);
canvas.setPreferredSize(new Dimension(200, 200));
canvas.setBackground(Color.green);
add(drawing);
add(buttons);
add(moz);
add(draw);
setPreferredSize(new Dimension(1000, 1000));
setSize(1000, 1000);
setLayout(gL);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==clear)
{
//setOpaque(false);
repaint();
}
}
}
class draw extends JFrame implements MouseListener, MouseMotionListener, ActionListener {
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
private JButton clear;
public draw()
{
setPreferredSize(new Dimension(1200, 500));
setBounds(0, 0, 480, 500);
clear=new JButton("CLEAR");
add(clear);
clear.setBounds(540, 5, 100, 25);
clear.addActionListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
protected void paintComponent(Graphics g)
{
g.drawLine(xPressed,yPressed,xDragged,yDragged);
xPressed=xDragged;
yPressed=yDragged;
}
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
g.drawLine(xPressed, yPressed, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
xPressed = arg0.getX();
yPressed = arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
So my idea is to create two classes where one is used to draw and other to create place where to draw and everything else. I have tried lots of things and now I am here and cant figure out, how to cal the draw class on my canvas so it will draw only there. Before I had everything in one class and called mouse events on my canvas. Result was that it drawed only when I clicked on canvas, but the actual drawing went also out of canvas if I did not let go of my mouse and dragged it out of canvas. Also it did not draw in canvas, but on the background of applet, at least it looked like that.
I really hope I explained my self understanding and I am sure, that this can be solved easily since there are lots of solutions online but I can't seem to find one that would work as I intend.
I suggest starting with this approach based around a BufferedImage as the painting surface..
import java.awt.*;
import java.awt.RenderingHints.Key;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class BasicPaint {
/** Reference to the original image. */
private BufferedImage originalImage;
/** Image used to make changes. */
private BufferedImage canvasImage;
/** The main GUI that might be added to a frame or applet. */
private JPanel gui;
/** The color to use when calling clear, text or other
* drawing functionality. */
private Color color = Color.WHITE;
/** General user messages. */
private JLabel output = new JLabel("You DooDoodle!");
private BufferedImage colorSample = new BufferedImage(
16,16,BufferedImage.TYPE_INT_RGB);
private JLabel imageLabel;
private int activeTool;
public static final int SELECTION_TOOL = 0;
public static final int DRAW_TOOL = 1;
public static final int TEXT_TOOL = 2;
private Point selectionStart;
private Rectangle selection;
private boolean dirty = false;
private Stroke stroke = new BasicStroke(
3,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,1.7f);
private RenderingHints renderingHints;
public JComponent getGui() {
if (gui==null) {
Map<Key, Object> hintsMap = new HashMap<RenderingHints.Key,Object>();
hintsMap.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
hintsMap.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
renderingHints = new RenderingHints(hintsMap);
setImage(new BufferedImage(320,240,BufferedImage.TYPE_INT_RGB));
gui = new JPanel(new BorderLayout(4,4));
gui.setBorder(new EmptyBorder(5,3,5,3));
JPanel imageView = new JPanel(new GridBagLayout());
imageView.setPreferredSize(new Dimension(480,320));
imageLabel = new JLabel(new ImageIcon(canvasImage));
JScrollPane imageScroll = new JScrollPane(imageView);
imageView.add(imageLabel);
imageLabel.addMouseMotionListener(new ImageMouseMotionListener());
imageLabel.addMouseListener(new ImageMouseListener());
gui.add(imageScroll,BorderLayout.CENTER);
JToolBar tb = new JToolBar();
tb.setFloatable(false);
JButton colorButton = new JButton("Color");
colorButton.setMnemonic('o');
colorButton.setToolTipText("Choose a Color");
ActionListener colorListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Color c = JColorChooser.showDialog(
gui, "Choose a color", color);
if (c!=null) {
setColor(c);
}
}
};
colorButton.addActionListener(colorListener);
colorButton.setIcon(new ImageIcon(colorSample));
tb.add(colorButton);
setColor(color);
final SpinnerNumberModel strokeModel =
new SpinnerNumberModel(3,1,16,1);
JSpinner strokeSize = new JSpinner(strokeModel);
ChangeListener strokeListener = new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
Object o = strokeModel.getValue();
Integer i = (Integer)o;
stroke = new BasicStroke(
i.intValue(),
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND,
1.7f);
}
};
strokeSize.addChangeListener(strokeListener);
strokeSize.setMaximumSize(strokeSize.getPreferredSize());
JLabel strokeLabel = new JLabel("Stroke");
strokeLabel.setLabelFor(strokeSize);
strokeLabel.setDisplayedMnemonic('t');
tb.add(strokeLabel);
tb.add(strokeSize);
tb.addSeparator();
ActionListener clearListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.OK_OPTION;
if (dirty) {
result = JOptionPane.showConfirmDialog(
gui, "Erase the current painting?");
}
if (result==JOptionPane.OK_OPTION) {
clear(canvasImage);
}
}
};
JButton clearButton = new JButton("Clear");
tb.add(clearButton);
clearButton.addActionListener(clearListener);
gui.add(tb, BorderLayout.PAGE_START);
JToolBar tools = new JToolBar(JToolBar.VERTICAL);
tools.setFloatable(false);
JButton crop = new JButton("Crop");
final JRadioButton select = new JRadioButton("Select", true);
final JRadioButton draw = new JRadioButton("Draw");
final JRadioButton text = new JRadioButton("Text");
tools.add(crop);
tools.add(select);
tools.add(draw);
tools.add(text);
ButtonGroup bg = new ButtonGroup();
bg.add(select);
bg.add(text);
bg.add(draw);
ActionListener toolGroupListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource()==select) {
activeTool = SELECTION_TOOL;
} else if (ae.getSource()==draw) {
activeTool = DRAW_TOOL;
} else if (ae.getSource()==text) {
activeTool = TEXT_TOOL;
}
}
};
select.addActionListener(toolGroupListener);
draw.addActionListener(toolGroupListener);
text.addActionListener(toolGroupListener);
gui.add(tools, BorderLayout.LINE_END);
gui.add(output,BorderLayout.PAGE_END);
clear(colorSample);
clear(canvasImage);
}
return gui;
}
/** Clears the entire image area by painting it with the current color. */
public void clear(BufferedImage bi) {
Graphics2D g = bi.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(color);
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
g.dispose();
imageLabel.repaint();
}
public void setImage(BufferedImage image) {
this.originalImage = image;
int w = image.getWidth();
int h = image.getHeight();
canvasImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.drawImage(image, 0, 0, gui);
g.dispose();
selection = new Rectangle(0,0,w,h);
if (this.imageLabel!=null) {
imageLabel.setIcon(new ImageIcon(canvasImage));
this.imageLabel.repaint();
}
if (gui!=null) {
gui.invalidate();
}
}
/** Set the current painting color and refresh any elements needed. */
public void setColor(Color color) {
this.color = color;
clear(colorSample);
}
private JMenu getFileMenu(boolean webstart){
JMenu file = new JMenu("File");
file.setMnemonic('f');
JMenuItem newImageItem = new JMenuItem("New");
newImageItem.setMnemonic('n');
ActionListener newImage = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
BufferedImage bi = new BufferedImage(
360, 300, BufferedImage.TYPE_INT_ARGB);
clear(bi);
setImage(bi);
}
};
newImageItem.addActionListener(newImage);
file.add(newImageItem);
if (webstart) {
//TODO Add open/save functionality using JNLP API
} else {
//TODO Add save functionality using J2SE API
file.addSeparator();
ActionListener openListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (!dirty) {
JFileChooser ch = getFileChooser();
int result = ch.showOpenDialog(gui);
if (result==JFileChooser.APPROVE_OPTION ) {
try {
BufferedImage bi = ImageIO.read(
ch.getSelectedFile());
setImage(bi);
} catch (IOException e) {
showError(e);
e.printStackTrace();
}
}
} else {
// TODO
JOptionPane.showMessageDialog(
gui, "TODO - prompt save image..");
}
}
};
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('o');
openItem.addActionListener(openListener);
file.add(openItem);
ActionListener saveListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser ch = getFileChooser();
int result = ch.showSaveDialog(gui);
if (result==JFileChooser.APPROVE_OPTION ) {
try {
File f = ch.getSelectedFile();
ImageIO.write(BasicPaint.this.canvasImage, "png", f);
BasicPaint.this.originalImage = BasicPaint.this.canvasImage;
dirty = false;
} catch (IOException ioe) {
showError(ioe);
ioe.printStackTrace();
}
}
}
};
JMenuItem saveItem = new JMenuItem("Save");
saveItem.addActionListener(saveListener);
saveItem.setMnemonic('s');
file.add(saveItem);
}
if (canExit()) {
ActionListener exit = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
};
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.addSeparator();
exitItem.addActionListener(exit);
file.add(exitItem);
}
return file;
}
private void showError(Throwable t) {
JOptionPane.showMessageDialog(
gui,
t.getMessage(),
t.toString(),
JOptionPane.ERROR_MESSAGE);
}
JFileChooser chooser = null;
public JFileChooser getFileChooser() {
if (chooser==null) {
chooser = new JFileChooser();
FileFilter ff = new FileNameExtensionFilter("Image files", ImageIO.getReaderFileSuffixes());
chooser.setFileFilter(ff);
}
return chooser;
}
public boolean canExit() {
boolean canExit = false;
SecurityManager sm = System.getSecurityManager();
if (sm==null) {
canExit = true;
} else {
try {
sm.checkExit(0);
canExit = true;
} catch(Exception stayFalse) {
}
}
return canExit;
}
public JMenuBar getMenuBar(boolean webstart){
JMenuBar mb = new JMenuBar();
mb.add(this.getFileMenu(webstart));
return mb;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// use default
}
BasicPaint bp = new BasicPaint();
JFrame f = new JFrame("DooDoodle!");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(bp.getGui());
f.setJMenuBar(bp.getMenuBar(false));
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
public void text(Point point) {
String text = JOptionPane.showInputDialog(gui, "Text to add", "Text");
if (text!=null) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
g.setStroke(stroke);
int n = 0;
g.drawString(text,point.x,point.y);
g.dispose();
this.imageLabel.repaint();
}
}
public void draw(Point point) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
g.setStroke(stroke);
int n = 0;
g.drawLine(point.x, point.y, point.x+n, point.y+n);
g.dispose();
this.imageLabel.repaint();
}
class ImageMouseListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
if (activeTool==BasicPaint.SELECTION_TOOL) {
selectionStart = arg0.getPoint();
} else if (activeTool==BasicPaint.DRAW_TOOL) {
// TODO
draw(arg0.getPoint());
} else if (activeTool==BasicPaint.TEXT_TOOL) {
// TODO
text(arg0.getPoint());
} else {
JOptionPane.showMessageDialog(
gui,
"Application error. :(",
"Error!",
JOptionPane.ERROR_MESSAGE);
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
if (activeTool==BasicPaint.SELECTION_TOOL) {
selection = new Rectangle(
selectionStart.x,
selectionStart.y,
arg0.getPoint().x,
arg0.getPoint().y);
}
}
}
class ImageMouseMotionListener implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent arg0) {
reportPositionAndColor(arg0);
if (activeTool==BasicPaint.SELECTION_TOOL) {
selection = new Rectangle(
selectionStart.x,
selectionStart.y,
arg0.getPoint().x-selectionStart.x,
arg0.getPoint().y-selectionStart.y);
} else if (activeTool==BasicPaint.DRAW_TOOL) {
draw(arg0.getPoint());
}
}
#Override
public void mouseMoved(MouseEvent arg0) {
reportPositionAndColor(arg0);
}
}
private void reportPositionAndColor(MouseEvent me) {
String text = "";
if (activeTool==BasicPaint.SELECTION_TOOL) {
text += "Selection (X,Y:WxH): " +
(int)selection.getX() +
"," +
(int)selection.getY() +
":" +
(int)selection.getWidth() +
"x" +
(int)selection.getHeight();
} else {
text += "X,Y: " + (me.getPoint().x+1) + "," + (me.getPoint().y+1);
}
output.setText(text);
}
}
This source is very patchy.
It has many parts with // TODO
A dirty attribute is declared but never used in any meaningful way. ..
It is just something I hacked together today and thought should be shown before it hit the posting limit.
Oh, and don't go looking for any 'OO design' since I did not put any in. If there is any, it is only by accident. This code is intended to demonstrate what is possible and how to start doing it.

Repaint() not calling paint() in Java

Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now.
With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program.
Entire code is below:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
public class Reflexology1 extends JFrame{
private static final long serialVersionUID = -1295261024563143679L;
private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25);
private Timer moveBallTimer;
int _ballXpos, _ballYpos;
JButton button1, button2;
JButton movingButton;
JTextArea textArea1;
int buttonAClicked, buttonDClicked;
private long _openTime = 0;
private long _closeTime = 0;
JPanel thePanel = new JPanel();
JPanel thePlacebo = new JPanel();
final JFrame frame = new JFrame("Reflexology");
final JFrame frame2 = new JFrame("The Test");
JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can.");
public static void main(String[] args){
new Reflexology1();
}
public Reflexology1(){
frame.setSize(600, 475);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Reflexology 1.0");
frame.setResizable(false);
frame2.setSize(600, 475);
frame2.setLocationRelativeTo(null);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setTitle("Reflexology 1.0");
frame2.setResizable(false);
button1 = new JButton("Accept");
button2 = new JButton("Decline");
//movingButton = new JButton("Click Me");
ListenForAcceptButton lForAButton = new ListenForAcceptButton();
ListenForDeclineButton lForDButton = new ListenForDeclineButton();
button1.addActionListener(lForAButton);
button2.addActionListener(lForDButton);
//movingButton.addActionListener(lForMButton);
JTextArea textArea1 = new JTextArea(24, 50);
textArea1.setText("Tracking Events\n");
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
textArea1.setSize(15, 50);
textArea1.setEditable(false);
FileReader reader = null;
try {
reader = new FileReader("EULA.txt");
textArea1.read(reader, "EULA.txt");
} catch (IOException exception) {
System.err.println("Problem loading file");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
AdjustmentListener listener = new MyAdjustmentListener();
thePanel.add(scrollBar1);
thePanel.add(button1);
thePanel.add(button2);
frame.add(thePanel);
ListenForMouse lForMouse = new ListenForMouse();
thePlacebo.addMouseListener(lForMouse);
thePlacebo.add(label1);
frame2.add(thePlacebo);
ListenForWindow lForWindow = new ListenForWindow();
frame.addWindowListener(lForWindow);
frame2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();}
}
});
frame.setVisible(true);
moveBallTimer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveBall();
System.out.println("Timer started!");
repaint();
}
});
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(frame2.isVisible()){ moveBallTimer.start(); }
}
});
}
private class ListenForAcceptButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
Calendar ClCDateTime = Calendar.getInstance();
System.out.println(ClCDateTime.getTimeInMillis() - _openTime);
_closeTime = ClCDateTime.getTimeInMillis() - _openTime;
//frame.getContentPane().remove(thePanel);
//thePlacebo.addKeyListener(lForKeys);
//frame.getContentPane().add(thePlacebo);
//frame.repaint();
//moveBallTimer.start();
frame.setVisible(false);
frame2.setVisible(true);
frame2.revalidate();
frame2.repaint();
}
}
}
private class ListenForDeclineButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button2){
JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}
private class ListenForWindow implements WindowListener{
public void windowActivated(WindowEvent e) {
//textArea1.append("Window is active");
}
// if this.dispose() is called, this is called:
public void windowClosed(WindowEvent arg0) {
}
// When a window is closed from a menu, this is called:
public void windowClosing(WindowEvent arg0) {
}
// Called when the window is no longer the active window:
public void windowDeactivated(WindowEvent arg0) {
//textArea1.append("Window is NOT active");
}
// Window gone from minimized to normal state
public void windowDeiconified(WindowEvent arg0) {
//textArea1.append("Window is in normal state");
}
// Window has been minimized
public void windowIconified(WindowEvent arg0) {
//textArea1.append("Window is minimized");
}
// Called when the Window is originally created
public void windowOpened(WindowEvent arg0) {
//textArea1.append("Let there be Window!");
Calendar OlCDateTime = Calendar.getInstance();
_openTime = OlCDateTime.getTimeInMillis();
//System.out.println(_openTime);
}
}
private class MyAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent arg0) {
AdjustmentEvent scrollBar1;
//System.out.println(scrollBar1.getValue()));
}
}
public void paint(Graphics g) {
//super.paint(g);
frame2.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
System.out.println("Calling fill()");
}
protected void moveBall() {
//System.out.println("I'm in the moveBall() function!");
int width = getWidth();
int height = getHeight();
int min, max, randomX, randomY;
min =200;
max = -200;
randomX = min + (int)(Math.random() * ((max - min)+1));
randomY = min + (int)(Math.random() * ((max - min)+1));
//System.out.println(randomX + ", " + randomY);
Rectangle ballBounds = ball.getBounds();
//System.out.println(ballBounds.x + ", " + ballBounds.y);
if (ballBounds.x + randomX < 0) {
randomX = 200;
} else if (ballBounds.x + ballBounds.width + randomX > width) {
randomX = -200;
}
if (ballBounds.y + randomY < 0) {
randomY = 200;
} else if (ballBounds.y + ballBounds.height + randomY > height) {
randomY = -200;
}
ballBounds.x += randomX;
ballBounds.y += randomY;
_ballXpos = ballBounds.x;
_ballYpos = ballBounds.y;
ball.setFrame(ballBounds);
}
public void start() {
moveBallTimer.start();
}
public void stop() {
moveBallTimer.stop();
}
private class ListenForMouse implements MouseListener{
// Called when the mouse is clicked
public void mouseClicked(MouseEvent e) {
//System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n");
if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) {
System.out.println("TRUE");
}
System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos);
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
// System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos);
// Mouse over
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
// Mouse left the mouseover area:
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.
You should not paint directly on JFrame. JPanel or extension of JComponent should be used. For painting override paintComponent() rather than paint(). Don't forget to call super.paintComponent(g);.
Also, keep in mind that repaint() only schedules component update, it does not trigger immediate paint().
For more details see Performing Custom Painting and Painting in AWT and Swing.
For example you can apply the following changes. TestPanel will paint the ball.
class TestPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
}
}
Then, update thePlacebo panel:
JPanel thePlacebo = new TestPanel();
Add repaint in moveBall():
thePlacebo.repaint();
Here is an example based on original code:
package so;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
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.util.Random;
import javax.swing.*;
public class TestBall {
private static void createAndShowUI() {
final TestPanel panel = new TestPanel();
panel.validate();
JFrame frame = new JFrame("TestBall");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 300));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ActionListener timerAction = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.moveBall();
}
};
Timer timer = new Timer(1000, timerAction);
timer.setRepeats(true);
timer.start();
}
static class TestPanel extends JPanel {
public static int BALL_SIZE = 25;
private Ellipse2D ball = new Ellipse2D.Double(0, 0, BALL_SIZE,
BALL_SIZE);
Random rand = new Random();
public TestPanel() {
this.addMouseListener(new MouseAdapter() {
// Called when the mouse is clicked
public void mouseClicked(MouseEvent e) {
if (ball.contains(e.getPoint())) {
System.out.println("hit the ball");
}
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
}
public void moveBall() {
Rectangle ballBounds = ball.getBounds();
ball.setFrame(ballBounds);
ballBounds.x = rand.nextInt(getWidth() - BALL_SIZE + 1) + 1;
ballBounds.y = rand.nextInt(getHeight() - BALL_SIZE + 1) + 1;
ball.setFrame(ballBounds);
repaint();
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Java - change JPanel image with mouse

I am trying to create a panel with pictures that are changed with the mouse.
I have 10 images (0.png to 9.png). My problem is, I want to move image and I am currently viewing the second picture. I used the JScrollPane to scroll back to the first image, but only the first image is moving. How can I refresh my panel and be able to move all images?
This is my code:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
class MapFrame extends JPanel {
/**
*
*/
private static final long serialVersionUID = (long) 1.0;
private static Image image;
private static JLabel label = new JLabel();
private static int ind =0;
private static JFrame frame;
private static String str;
//-----------------------------------------------------------------
public MapFrame(){ }
//-----------------------------------------------------------------
public MapFrame(String pathe) {
super(new BorderLayout());
image = new ImageIcon(getClass().getResource(pathe)).getImage();
label = new JLabel(new ImageIcon(image));
JScrollPane scroll = new JScrollPane(label,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
HandLcalss hand = new HandLcalss(label);
JViewport v = scroll.getViewport();
v.addMouseListener(hand);
v.addMouseMotionListener(hand);
v.addMouseWheelListener(hand);
}
//-----------------------------------------------------------------
public static void ShowGUI(String pathe) {
frame = new JFrame("Bladi_map");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MapFrame(pathe));
frame.setSize(500,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//-----------------------------------------------------------------
public static void ChangImage(String pathe){
frame.getContentPane().add(new MapFrame(pathe));
label.revalidate();
frame.setVisible(true);
}
//-----------------------------------------------------------------
class HandLcalss implements MouseListener,MouseMotionListener,MouseWheelListener{
private static final int DELAY = 10;
private Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
private Timer scroller;
private JComponent label;
private Point startPt = new Point();
private Point move = new Point();
//-----------------------------------------------------------------
public HandLcalss(JComponent comp) {
this.label = comp;
comp.getCursor();
this.scroller = new Timer(DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
}
//-----------------------------------------------------------------
#Override public void mouseDragged(MouseEvent e) {
JViewport vport = (JViewport)e.getSource();
Point pt = e.getPoint();
int dx = startPt.x - pt.x;
int dy = startPt.y - pt.y;
Point vp = vport.getViewPosition();
vp.translate(dx, dy);
label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
startPt.setLocation(pt);
}
#Override
public void mousePressed(MouseEvent e) {
((JComponent)e.getSource()).setCursor(hc);
startPt.setLocation(e.getPoint());
move.setLocation(0, 0);
scroller.stop();
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
if (notches < 0) {
ind++;
if(ind <0){ind=0;}
if(ind<=9){
str="/resources/"+ind+".png";
ChangImage(str);
System.out.println("indink"+str);
}
} else {
ind--;
if(ind >9){ind=8;}
if(ind>=0){
str="/resources/"+ind+".png";
ChangImage(str);
System.out.println("ind"+ind);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
//-----------------------------------------------------------------
}
This is the main class:
public class main {
public static void main(String[] args) {
MapFrame.ShowGUI("/resources/0.png");
}
}
You have 2 problems in your code:
The first:
public static void ChangImage(String pathe){
frame.getContentPane().add(new MapFrame(pathe));
label.revalidate();
frame.setVisible(true);
}
When you change image (invoked on mouse wheel event) you simply add new panel (MapFrame) with image to existing container: (Container pane = frame.getContentPane()). The old ones are still there and are overlapping with the new panel. The above method should be:
public static void ChangImage(String pathe) {
frame.getContentPane().removeAll();
frame.getContentPane().add(new MapFrame(pathe));
label.revalidate();
frame.setVisible(true);
}
The second thing:
Why complicate? (also there is an error on 0 value of ind):
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation() * -1;
ind += notches;
if(ind < 0) {
ind = 0;
}
else if(ind > 9) {
ind = 9;
}
str = "/resources/" + ind + ".png";
ChangImage(str);
}
And the last thing:
If you are implementing all mouse interfaces - you can extend MouseAdapter. Now you needn't override methods you don't want.

freehand drawline using mouse events

may i know if there is any formula for drawing lines? currently i am implementing a freehand draw line in java, however the code below when drawn it is not what im expecting.
i have tried g.drawLine(arg0.getX(), arg0.getY(), arg0.getX(), arg0.getY()); , however the line drawn is not continous rather it is drawing points, i read that it is because the mouse drag happens at intervals, if so how should i record the points?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class STDrawingArea extends JPanel implements MouseListener, MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
public STDrawingArea()
{
setPreferredSize(new Dimension(1280, 700));
setBounds(0, 0, 1280, 700);
setBackground(Color.WHITE);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
xDragged = xPressed;
yDragged = yPressed;
g.drawLine(xPressed, yPressed, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
xPressed = arg0.getX();
yPressed = arg0.getY();
System.out.println("xPressed: "+xPressed+" ,yPressed: "+yPressed);
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
xReleased = arg0.getX();
yReleased = arg0.getY();
System.out.println("xReleased: "+xPressed+" ,yReleased: "+yPressed);
}
}
A simple way to do this might be:
Maintain a List of Points in your component
In the mouseDragged() method, get the point (MouseEvent#getPoint()) and add it to your list
Override the paintComponent() method of the JPanel
Iterate over all points in your list of points
Draw lines between each pair of points (except the first and last, of course)
For example, you might make the following changes:
private ArrayList<Point> points = new ArrayList<Point>();
//...
public void mouseDragged(MouseEvent arg0) {
points.add(arg0.getPoint());
repaint(); //request Swing to refresh display as soon as it can
}
//...
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < points.size() - 2; i++)
{
Point p1 = points.get(i);
Point p2 = points.get(i + 1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
Some slight Changes are required
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
g.drawLine(xDragged, yDragged, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
}
and
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
xPressed = arg0.getX();
yPressed = arg0.getY();
System.out.println("xPressed: "+xPressed+" ,yPressed: "+yPressed);
xDragged=xPressed;
yDragged=yPressed;
}
I have compiled and executed this code and found its perfectly working..:-)
Try This. It's working. There is no need to use the Point class and iterate the 'for' loop, If you wanna simply make a Freehand Drawing.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class STDrawingArea extends JPanel implements MouseListener,MouseMotionListener,ActionListener
{
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
private JButton clear;
public STDrawingArea()
{
setPreferredSize(new Dimension(1200, 500));
setBounds(0, 0, 480, 500);
//setBackground(Color.YELLOW);
clear=new JButton("CLEAR");
add(clear);
clear.setBounds(540, 5, 100, 25);
clear.addActionListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==clear)
{
setOpaque(false);
repaint();
}
}
#Override
protected void paintComponent(Graphics g)
{
g.drawLine(xPressed,yPressed,xDragged,yDragged);
xPressed=xDragged;
yPressed=yDragged;
}
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
g.drawLine(xPressed, yPressed, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
setOpaque(true);
xPressed = arg0.getX();
yPressed = arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class Frame4 extends JFrame
{
private STDrawingArea da;
public Frame4()
{
da=new STDrawingArea();
da.setBackground(Color.YELLOW);
da.setLayout(new BorderLayout());
add(da);
}
}
public class FreeHandDrwing
{
public static void main(String s[])
{
Frame4 ob=new Frame4();
ob.setVisible(true);
ob.setBounds(100, 100, 1200, 500);
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Categories

Resources