Problem with my whiteboard application - java

I have to develop a whiteboard application in which both the local user and the remote user should be able to draw simultaneously, is this possible? If possible then any logic?
I have already developed a code but in which i am not able to do this, when the remote user starts drawing the shape which i am drawing is being replaced by his shape and co-ordinates.
This problem is only when both draw simultaneously.
any idea guys?
Here is my code
class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener
{
static BufferedImage image;
int bpressed;
Color color;
Point start;
Point end;
Point mp;
Button elipse=new Button("elipse");
Button rectangle=new Button("rect");
Button line=new Button("line");
Button empty=new Button("");
JButton save=new JButton("Save");
JButton erase=new JButton("Erase");
String selected;
int ex,ey;//eraser
DatagramSocket dataSocket;
JButton button = new JButton("test");
Client client;
Point p=new Point();
int w,h;
public Paper(DatagramSocket dataSocket)
{
this.dataSocket=dataSocket;
client=new Client(dataSocket);
System.out.println("paper");
setBackground(Color.white);
addMouseListener(this);
addMouseMotionListener(this);
color = Color.black;
setBorder(BorderFactory.createLineBorder(Color.black));
//save.setPreferredSize(new Dimension(100,20));
save.setMaximumSize(new Dimension(75,27));
erase.setMaximumSize(new Dimension(75,27));
}
public void paintComponent(Graphics g)
{
try
{
g.drawImage(image, 0, 0, this);
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.black);
if(selected==("elipse"))
g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y));
else if(selected==("rect"))
g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y));
else if(selected==("line"))
g2.drawLine(start.x,start.y,end.x,end.y);
}
catch(Exception e)
{}
}
//Function to draw the shape on image
public void draw()
{
Graphics2D g2 = image.createGraphics();
g2.setPaint(color);
if(selected=="line")
g2.drawLine(start.x, start.y, end.x, end.y);
if(selected=="elipse")
g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
if(selected=="rect")
g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y));
repaint();
g2.dispose();
start=null;
}
//To add the point to the board which is broadcasted by the server
public synchronized void addPoint(Point ps,String varname,String shape,String event)
{
try
{
if(end==null)
end = new Point();
if(start==null)
start = new Point();
if(shape.equals("elipse"))
selected="elipse";
else if(shape.equals("line"))
selected="line";
else if(shape.equals("rect"))
selected="rect";
else if(shape.equals("erase"))
{
selected="erase";
erase();
}
if(end!=null && start!=null)
{
if(varname.equals("end"))
end=ps;
if(varname.equals("mp"))
mp=ps;
if(varname.equals("start"))
start=ps;
if(event.equals("drag"))
repaint();
else if(event.equals("release"))
draw();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
//To set the size of the image
public void setWidth(int x,int y)
{
System.out.println("("+x+","+y+")");
w=x;
h=y;
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setPaint(Color.white);
g2.fillRect(0,0,w,h);
g2.dispose();
}
//Function which provides the erase functionality
public void erase()
{
Graphics2D pic=(Graphics2D) image.getGraphics();
pic.setPaint(Color.white);
pic.fillRect(start.x, start.y, 10, 10);
}
//Function to add buttons into the panel, calling this function returns a panel
public JPanel addButtons()
{
JPanel buttonpanel=new JPanel();
JPanel row1=new JPanel();
JPanel row2=new JPanel();
JPanel row3=new JPanel();
JPanel row4=new JPanel();
buttonpanel.setPreferredSize(new Dimension(80,80));
//buttonpanel.setMinimumSize(new Dimension(150,150));
row1.setLayout(new BoxLayout(row1,BoxLayout.X_AXIS));
row1.setPreferredSize(new Dimension(150,150));
row2.setLayout(new BoxLayout(row2,BoxLayout.X_AXIS));
row3.setLayout(new BoxLayout(row3,BoxLayout.X_AXIS));
row4.setLayout(new BoxLayout(row4,BoxLayout.X_AXIS));
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS));
elipse.addActionListener(this);
rectangle.addActionListener(this);
line.addActionListener( this);
save.addActionListener( this);
erase.addActionListener( this);
buttonpanel.add(Box.createRigidArea(new Dimension(10,10)));
row1.add(elipse);
row1.add(Box.createRigidArea(new Dimension(5,0)));
row1.add(rectangle);
buttonpanel.add(row1);
buttonpanel.add(Box.createRigidArea(new Dimension(10,10)));
row2.add(line);
row2.add(Box.createRigidArea(new Dimension(5,0)));
row2.add(empty);
buttonpanel.add(row2);
buttonpanel.add(Box.createRigidArea(new Dimension(10,10)));
row3.add(save);
buttonpanel.add(row3);
buttonpanel.add(Box.createRigidArea(new Dimension(10,10)));
row4.add(erase);
buttonpanel.add(row4);
return buttonpanel;
}
//To save the image drawn
public void save()
{
try
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
JFileChooser fc = new JFileChooser();
fc.showSaveDialog(this);
encoder.encode(image);
byte[] jpgData = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg");
fos.write(jpgData);
fos.close();
//add replce confirmation here
}
catch (IOException e)
{
System.out.println(e);
}
}
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e)
{
if(selected=="line"||selected=="erase")
{
start=e.getPoint();
client.broadcast(start,"start", selected,"press");
}
else if(selected=="elipse"||selected=="rect")
{
mp = e.getPoint();
client.broadcast(mp,"mp", selected,"press");
}
}
public void mouseReleased(MouseEvent e)
{
if(start!=null)
{
if(selected=="line")
{
end=e.getPoint();
client.broadcast(end,"end", selected,"release");
}
else if(selected=="elipse"||selected=="rect")
{
end.x = Math.max(mp.x,e.getX());
end.y = Math.max(mp.y,e.getY());
client.broadcast(end,"end", selected,"release");
}
draw();
}
//start=null;
}
public void mouseDragged(MouseEvent e)
{
if(end==null)
end = new Point();
if(start==null)
start = new Point();
if(selected=="line")
{
end=e.getPoint();
client.broadcast(end,"end", selected,"drag");
}
else if(selected=="erase")
{
start=e.getPoint();
erase();
client.broadcast(start,"start", selected,"drag");
}
else if(selected=="elipse"||selected=="rect")
{
start.x = Math.min(mp.x,e.getX());
start.y = Math.min(mp.y,e.getY());
end.x = Math.max(mp.x,e.getX());
end.y = Math.max(mp.y,e.getY());
client.broadcast(start,"start", selected,"drag");
client.broadcast(end,"end", selected,"drag");
}
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==elipse)
selected="elipse";
if(e.getSource()==line)
selected="line";
if(e.getSource()==rectangle)
selected="rect";
if(e.getSource()==save)
save();
if(e.getSource()==erase)
{
selected="erase";
erase();
}
}
}
class Button extends JButton
{
String name;
public Button(String name)
{
this.name=name;
Dimension buttonSize = new Dimension(35,35);
setMaximumSize(buttonSize);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//g2.setStroke(new BasicStroke(1.2f));
if (name == "line") g.drawLine(5,5,30,30);
if (name == "elipse") g.drawOval(5,7,25,20);
if (name== "rect") g.drawRect(5,5,25,23);
}
}

Try maintaining a panel for each user, and layer them on top of each other. As long as the backgrounds are transparent, you should see them all fine.
Edit: To achieve the layers, you could try JLayeredPane.

I don't see any code there that handles requests arriving from the client. Assuming that is happening on a background thread, make sure you use SwingUtilities.invokeLater to make the changes on the EDT. Updating UI components from anywhere but the EDT will cause unpredictable behavior. See also Concurrency in Swing
Also, this sort of thing isn't going to work:
if (name == "line") g.drawLine(5,5,30,30);
In Java, the == operator performs an identity comparison. It evaluates true if name and "line" are the same object. It will evaluate false if they reference different objects, even if they both have the same value. To compare equality, you need to use the .equals() method.

Related

How to clip a BufferedImage with a shape created with Graphics2D?(Java)

Currently, I'm working on my first Java application with which a user can look through photos, cut them and rotate. I have an issue with clipping an image. What I want to achieve is the following:
User clicks on the "Cut" option
Rectangle shape called by repaint method appears on the image
By stretching the rectangle user chooses the area for cutting
When the user releases the mouse(which stops stretching the rectangle) the area that is surrounded with the rectangle is left and all the rest of the image is cut.
As of for now I have several issues:
My image is centralized on JLabel which in its turn is added to JPanel and the last is added to JFrame, so now, when I want to add a rectangle above JLable (so it is to be located on the picture) it's invisible and is added only on JPanel directly.
I drew an image with paintComponent but can't figure out how to move and stretch it and repaint the rectangle again.
Below is the part of my code which (I hope) will describe my problems more precisely:
public class GraphicalUserInterface {
static JPanel background;
static JLabel labelIcon;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GraphicalUserInterface().go();
}
});
}
public void go() {
buildGui();
}
public void buildGui() {
frame = new JFrame("PicMove");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout layout = new BorderLayout();
background = new JPanel(layout);
/**To center picture on the background**/
labelIcon = new JLabel();
labelIcon.setHorizontalAlignment(JLabel.CENTER);
labelIcon.setVerticalAlignment(JLabel.CENTER);
background.add(BorderLayout.SOUTH, bottom);
background.add(BorderLayout.PAGE_START, bar);
background.add(BorderLayout.CENTER, labelIcon);
background.add(BorderLayout.EAST, chatPanel);
frame.getContentPane().add(BorderLayout.CENTER, background);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
frame.setSize(1300, 1200);}
static class CutImage extends JPanel implements Runnable {
boolean clip;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if (clip) {
BasicStroke bs = new BasicStroke(50, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10, null, 0);
g2d.setStroke(bs);
QuadCurve2D.Float qc = new QuadCurve2D.Float(20, 50, 100, 140, 460, 170);
g2d.setClip(qc);
}
BasicStroke bs = new BasicStroke(5, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10, new float[]{10}, 0);
g2d.setStroke(bs);
g2d.drawRect(260, 50, 80, 120);
}
#Override
public void run() {
CutImage cutPanel = new CutImage();
GraphicalUserInterface.background.add(cutPanel).repaint();
}
}
public class PicChanges implements Runnable{
static BufferedImage newImage;
static File [] selectedFile;
static int currentImage;
FileNameExtensionFilter filter;
JFileChooser fileChooser;
public void openPic() {
currentImage = 0;
try {
fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new java.io.File((System.getProperty("user.home"))));
filter = new FileNameExtensionFilter("*.images", "jpg", "gif", "png");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setMultiSelectionEnabled(true);
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.OPEN_DIALOG) {
selectedFile = fileChooser.getSelectedFiles();
for (File image : selectedFile) {
if ((image.isFile()) && (selectedFile.length > 0)){
newImage = ImageIO.read(selectedFile[0]);
GraphicalUserInterface.labelIcon.setIcon(new ImageIcon(
new ImageIcon(newImage).getImage().getScaledInstance(
450, 620, Image.SCALE_DEFAULT)));
} else if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("No Pics Selected");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Thread.currentThread().interrupt();
openPic();
}
public static void nextPic() {
currentImage++;
try {
newImage = ImageIO.read(selectedFile[currentImage]);
} catch (IOException e) {
e.printStackTrace();
System.out.println("No pictures left");
System.out.println("next"+currentImage);
}
GraphicalUserInterface.labelIcon.setIcon(new ImageIcon(
new ImageIcon(newImage).getImage().getScaledInstance(
450, 620, Image.SCALE_DEFAULT)));
}
static class NextPicture implements Runnable{
#Override
public void run() {
Thread.currentThread().interrupt();
nextPic();
}
}
public static void previousPic () {
currentImage--;
try {
newImage = ImageIO.read(selectedFile[currentImage]);
} catch (IOException e) {
e.printStackTrace();
System.out.println("previous "+currentImage);
}
GraphicalUserInterface.labelIcon.setIcon(new ImageIcon(
new ImageIcon(newImage).getImage().getScaledInstance(
450, 620, Image.SCALE_DEFAULT)));
}
static class PreviousPic implements Runnable{
#Override
public void run() {
Thread.currentThread().interrupt();
previousPic();
}
}
}
My idea was to add MouseListeners but can I add it to the shape created with Graphics2D?
I would be greatful for the help :)
Thank you
Being in search of finding a solution to this question I've asked two more questions(maybe it will be helpful for someone) :
1) Why BufferedImage is not cut according to the drawn in paintComponent method rectangle(its height is calculated wrong)?
2) Repaint() method doesn't invoke paint() & paintComponent() methods one by one, only paintComponent () method is working
that further helped me to find out the way.
My solution is to create a separate frame for displaying copied BufferedImage in it and on this frame to draw a rectangle with the help of MouseListeners. This is the piece of code:
public class ImageScreenShot extends JFrame implements MouseListener, MouseMotionListener {
#Override
public Dimension getPreferredSize() {
return super.getPreferredSize();
}
private static Thread screenShotThread;
public static Thread getScreenShotThread() {
return screenShotThread;
}
public static void setScreenShotThread(Thread screenShot) {
ImageScreenShot.screenShotThread = screenShot;
}
private int drag_status = 0, c1, c2, c3, c4;
public int getC1() {
return c1;
}
public int getC2() {
return c2;
}
public int getC3() {
return c3;
}
public int getC4() {
return c4;
}
class AdditionalPanel extends JLabel {
private BufferedImage img;
public BufferedImage getImg() {
return img;
}
public AdditionalPanel(BufferedImage img) {
this.img = img;
setPreferredSize(new Dimension(2560, 1600));
getPreferredSize();
setLayout(null);
}
#Override
public Dimension getPreferredSize() {
return super.getPreferredSize();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
System.out.println("Additional panel class paint method was invoked");
}
}
public void cut() {
AdditionalPanel apanel = new AdditionalPanel(PicChanges.getNewImage());
JScrollPane scrollPane = new JScrollPane(apanel);
scrollPane.addMouseMotionListener(this);
scrollPane.addMouseListener(this);
getContentPane().add(scrollPane, BorderLayout.CENTER);
setPreferredSize(new Dimension(2560, 1600));
getPreferredSize();
pack();
setVisible(true);
}
private void draggedScreen() throws Exception {
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2, w, h));
File save_path = new File("screen1.jpg");
ImageIO.write(img, "JPG", save_path);
GraphicalUserInterface.getLabelIcon().setIcon(new ImageIcon(new ImageIcon(img).getImage().getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_SMOOTH)));
JOptionPane.showConfirmDialog(this, "Would you like to save your cropped Pic?");
System.out.println("Cropped image saved successfully.");
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
repaint();
c1 = arg0.getXOnScreen();
c2 = arg0.getYOnScreen();
System.out.println("pressed");
}
#Override
public void mouseReleased(MouseEvent arg0) {
repaint();
if (drag_status == 1) {
c3 = arg0.getXOnScreen();
c4 = arg0.getYOnScreen();
try {
repaint();
draggedScreen();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void mouseDragged(MouseEvent arg0) {
repaint();
drag_status = 1;
c3 = arg0.getXOnScreen();
c4 = arg0.getYOnScreen();
}
#Override
public void mouseMoved(MouseEvent arg0) {
}
#Override
public void paint(Graphics g) {
super.paint(g);
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
if (w < 0)
w = w * -1;
g.setColor(Color.RED);
g.drawRect(c1, c2, w, h);
System.out.println("Paint component was invoked in imagescreenshot class");
}
P.S. I know that adding JFrame is not the best solution but I'm still in search for the best way to implement it so do not hesitate to comment on my code and tell what is wrong or what is good)

Trouble With Color Changing In My Java Swing Paint Application

Should I still be practicing Java Swing?
I'm trying to add functionality to my Java Swing Paint Application by adding a choice to change brush colors. However, when I'm finished choosing a different color in the color chooser, all of the old marks change into that chosen color along with my new line marks. I wanted the old marks to stay the same color as before.
(Pictures below)
Using black ink. Drawing something.
Deciding to change the color to green
Both the old AND new lines change to green.
This is not the entire application(tell me if you need the rest), but I believe the problem has something to do with incorrect table manipulation. The "shapeFill" table which matches colors to the lines("shapes" table) is not working correctly.
public class TestPane extends JComponent{
private List<List<Point>> points;
private ArrayList<Shape> shapes = new ArrayList<Shape>();
public TestPane() {
points = new ArrayList<>(100);
MouseAdapter ma = new MouseAdapter() {
private List<Point> currentPath;
#Override
public void mousePressed(MouseEvent e) {
currentPath = new ArrayList<>(100);
currentPath.add(e.getPoint());
points.add(currentPath);
}
#Override
public void mouseDragged(MouseEvent e) {
Point dragPoint = e.getPoint();
currentPath.add(dragPoint);
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
currentPath = null;
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Iterator<Color> fillCounter = shapeFill.iterator();
for(Shape s : shapes) { // I believe problem is somewhere around here?
g2d.setPaint(fillCounter.next());
g2d.setStroke(new java.awt.BasicStroke(10));
}
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (List<Point> path : points) {
Point from = null;
for (Point p : path) {
if (from != null) {
Shape line = new Line2D.Float(from.x, from.y, p.x, p.y);
g2d.draw(line);
shapes.add(line);
shapeFill.add(lineColor);
}
from = p;
}
}
g2d.dispose();
}
}
public JButton createButton(String title) {
JButton button = new JButton(title);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == colorChooser) {
Color chooser = JColorChooser.showDialog(null, "Select color", lineColor);
lineColor = chooser;
shapeFill.add(chooser);
repaint();
}else if(e.getSource() == shapeFillArrayList) {
System.out.print("\n");
for(Color index : shapeFill) {
System.out.println(index);
}
}
}
});
return button;
}

Paint- Repaint-mechanism in Swing

I have a problem with Paint- Repaint-Mechanism in Swing java.:
i want to create GraphicEditor, which can create a rectangle and shape with the Mouse.
The application should look like this
My Code Look like this :
public class MiniGrafikEditor extends JFrame implements ActionListener {
private Vector rectList;
private Rectangle currentRect;
private Color color = Color.green;
private static int v = 0 ;
JPanel bp;
public static void main(String[] args) {
MiniGrafikEditor wnd = new MiniGrafikEditor();
}
public MiniGrafikEditor() {
super("Rechtecke zeichnen");
rectList = new Vector();
currentRect = new Rectangle(0, 0, 0, 0);
setLayout(new BorderLayout());
addWindowListener(new MyWindowListener());
addMouseListener(new MyMouseListener());
addMouseMotionListener(new MyMouseMotionListener());
bp = new JPanel();
bp.setBackground(Color.gray);
add("North", bp);
JRadioButton b = null;
bp.add(b = new JRadioButton("Rechteck"));
b.addActionListener(this);
bp.add(b = new JRadioButton("kreis"));
b.addActionListener(this);
bp.add(b = new JRadioButton("Standard"));
b.addActionListener(this);
setLocation(200, 200);
setSize(400, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String label = ((JRadioButton) e.getSource()).getLabel();
bp.repaint();
if (label.equals("Rechteck")) {
v=1;
bp.repaint();
}
if (label.equals("Blue")) {
color = Color.blue;
bp.repaint();
}
Graphics g = getGraphics();
drawRects(g);
}
public void drawRects(Graphics g) {
Rectangle r;
Enumeration e;
g.clearRect(0, 0, getSize().width, getSize().height);
g.setColor(color);
for (e = rectList.elements(); e.hasMoreElements();) {
r = (Rectangle) e.nextElement();
g.drawRect(r.x, r.y, r.width, r.height);
}
if (currentRect != null && (currentRect.x > 0 || currentRect.y > 0)) {
g.drawRect(currentRect.x, currentRect.y, currentRect.width,
currentRect.height);
}
bp.repaint();
}
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent event) {
bp.repaint();
if(v==1){
currentRect = new Rectangle(event.getX(), event.getY(), 0, 0);
}
}
public void mouseReleased(MouseEvent event) {
if(v==1){
if (currentRect.width > 0 || currentRect.height > 0) {
rectList.addElement(currentRect);
currentRect = null;
}
Graphics g = getGraphics();
drawRects(g);
}
bp.repaint();
}
}
class MyMouseMotionListener extends MouseMotionAdapter {
public void mouseDragged(MouseEvent event) {
if(v==1){
int x = event.getX();
int y = event.getY();
if (x > currentRect.x && y > currentRect.y) {
currentRect.width = x - currentRect.x;
currentRect.height = y - currentRect.y;
}
Graphics g = getGraphics();
drawRects(g);
}
}
}
class MyWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
setVisible(false);
dispose();
System.exit(0);
}
}
}
when i run the application its look like this:
When i try to draw a rectangle , i can see when the Jpanel repaint it self.
how can i repaint the Jpanel and i cant see it, when it repaint it self.
thx a lot for your Help.
You have to write an extension of JPanel that overrides paint(Graphics g) or even better paintComponent(Graphics g). Under the overridden version of the method you will have to call your drawRects method.
See Custom Painting Approaches for examples of how to do custom painting using:
A List of objects to paint
a BufferedImage to paint the objects.
The examples will paint rectangles of different colors. So you will need to add code to paint different shapes. But the idea is to understand the basic painting concepts first.

How to draw on the JFrame?

I have a pdf file, which is rendered as an image and added as a JLabel in the JFrame. Now i want to draw on the contents in the JFrame by mouseclick and keystrokes. And these drawings should appear on the image(JLabel). I have pasted my code below. Can anyone please help me to figure it out!!!
public class LinePanel extends JPanel{
public static final String RESOURCE = "G:/resource/A0TestFile.pdf";
private MouseHandler mouseHandler = new MouseHandler();
private Point p1;
private Point p2;
private Point p3;
private Point p4;
ArrayList<Point> points = new ArrayList<Point>();
public LinePanel() {
this.addMouseListener(mouseHandler);
this.addMouseMotionListener(mouseHandler);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(1,
BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL));
crop(g);
}
public void crop(Graphics g){
if(points != null && points.size()>0){
for(int i=0;i<points.size();i++){
p1 = points.get(i);
g.drawLine(p1.x, p1.y, p1.x-20, p1.y);
g.drawLine(p1.x, p1.y, p1.x, p1.y+20);
}
for( i=1;i<points.size();i++){
p2 = points.get(i);
g.drawLine(p2.x, p2.y, p2.x-20, p2.y);
g.drawLine(p2.x, p2.y, p2.x, p2.y-20);
}
for( i=2;i<points.size();i++){
p3 = points.get(i);
g.drawLine(p3.x, p3.y, p3.x+20, p3.y);
g.drawLine(p3.x, p3.y, p3.x, p3.y-20);
}
for( i=3;i<points.size();i++){
p4 = points.get(i);
g.drawLine(p4.x, p4.y, p4.x+20, p4.y);
g.drawLine(p4.x, p4.y, p4.x, p4.y+20);
}
}
}
private class MouseHandler extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
if(points.size()<4){
points.add(e.getPoint());
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
}
}
private class ControlPanel extends JPanel {
private static final int DELTA = 1;
public ControlPanel() {
new MoveButton("\u2190", KeyEvent.VK_LEFT, -DELTA, 0);
new MoveButton("\u2191", KeyEvent.VK_UP, 0, -DELTA);
new MoveButton("\u2192", KeyEvent.VK_RIGHT, DELTA, 0);
new MoveButton("\u2193", KeyEvent.VK_DOWN, 0, DELTA);
}
private class MoveButton extends JButton {
KeyStroke k;
int dx, dy;
public MoveButton(String name, int code,
final int dx, final int dy) {
super(name);
this.k = KeyStroke.getKeyStroke(code, 0);
this.dx = dx;
this.dy = dy;
this.setAction(new AbstractAction(this.getText()) {
#Override
public void actionPerformed(ActionEvent e) {
if(points.size()==1){
LinePanel.this.p1.translate(dx, dy);
LinePanel.this.repaint();
}
if(points.size()==2){
LinePanel.this.p2.translate(dx, dy);
LinePanel.this.repaint();
}
if(points.size()==3){
LinePanel.this.p3.translate(dx, dy);
LinePanel.this.repaint();
}
if(points.size()==4){
LinePanel.this.p4.translate(dx, dy);
LinePanel.this.repaint();
}
}
});
ControlPanel.this.getInputMap(WHEN_IN_FOCUSED_WINDOW)
.put(k, k.toString());
ControlPanel.this.getActionMap()
.put(k.toString(), new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
MoveButton.this.doClick();
}
});
}
}
}
private void display() throws IOException{
File file = new File(RESOURCE);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE,
0, channel.size());
PDFFile pdffile = new PDFFile(buf);
PDFPage page = pdffile.getPage(1);
Rectangle rect = new Rectangle(0,0,(int)page.getBBox().getWidth(),(int)page.getBBox().getHeight());
Image img = page.getImage(rect.width, rect.height,rect,null,true,true);
JFrame f = new JFrame("LinePanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(800, 800));
JPanel panel = new JPanel();
JLabel image = new JLabel(new ImageIcon(img));
panel.add(image);
JScrollPane jspane=new JScrollPane(panel);
f.add(jspane, BorderLayout.CENTER);
f.add(this);
f.add(new ControlPanel(),BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new LinePanel().display();
} catch (IOException ex) {
Logger.getLogger(LinePanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
Try this. It's a Panel with an Image. Add the Panel to the Frame;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("image name and path"));
} catch (IOException ex) {
// handle exception...
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
// draw other stuff
}
}
If you want your drawing to be painted on top of any component added to the panel/frame, you need to override the paint() method.
Take a look at A Closer Look at the Paint Mechanism

How do i use KeyListener in java?

How do I use KeyListener on this code to move up and down? Ii know how to use KeyListener but I don't know where it put it on this code.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class ControlPanel extends JPanel implements Runnable,ActionListener,KeyListener,MouseListener{
private MainPanel main;
private final static int maxWidth = 800, maxHeight = 600; //width & height of JPanel
private boolean running; //keeps track of state of the program
private Thread thread;
private Graphics2D graphics;
private Image image; //used for double buffering
private BufferedImage bgImage;
private String s = "";
Font f = new Font("Times New Roman",Font.PLAIN,50);
Timer t = new Timer(2000,this);
private int typed = 0;
private int x = 50,y = 500;
public ControlPanel(MainPanel main) {
this.setDoubleBuffered(false); //we'll use our own double buffering method
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(maxWidth, maxHeight));
this.setFocusable(true);
this.requestFocus();
this.main = main;
addKeyListener(this);
addMouseListener(this);
t.start();
}
public static void main(String[] args) {
new MainPanel();
}
public void addNotify() {
super.addNotify();
startGame();
}
public void stopGame() {
running = false;
}
//Creates a thread and starts it
public void startGame() {
if (thread == null || !running) {
thread = new Thread(this);
}
thread.start(); //calls run()
}
public void run() {
running = true;
init();
while (running) {
createImage(); //creates image for double buffering
///////////////USE THESE 2 METHODS////////////////////
update(); //use this to change coordinates, update values, etc
draw(); //use this to draw to the screen
//////////////////////////////////////////////////////
drawImage(); //draws on the JPanel
}
System.exit(0);
}
//Use this to create or initialize any variables or objects you have
public void init() {
}
public void initGame(){
}
//Use this to update anything you need to update
public void update() {
}
//Use this to draw anything you need to draw
public void draw() {
graphics.setColor(Color.WHITE);
graphics.fillRect(250, 450, 300,100);
graphics.setColor(Color.WHITE);
graphics.fillRect(250, 320, 300,100);
graphics.setColor(Color.GREEN);
graphics.setFont(f);
graphics.drawString(s, x, y);
typed = 0;
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("HANGMAN", 270,75);
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("PLAY", 330, 390);
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("QUIT", 330, 520);
graphics.setColor(Color.red);
graphics.drawRect(248, 318, 304,104);
}
//creates an image for double buffering
public void createImage() {
if (image == null) {
image = createImage(maxWidth, maxHeight);
if (image == null) {
System.out.println("Cannot create buffer");
return;
}
else
graphics = (Graphics2D)image.getGraphics(); //get graphics object from Image
}
if (bgImage == null) {
graphics.setColor(Color.black);
graphics.fillRect(0, 0, maxWidth, maxHeight);
//System.out.println("No background image");
}
else {
//draws a background image on the Image
graphics.drawImage(bgImage, 0, 0, null);
}
}
//outputs everything to the JPanel
public void drawImage() {
Graphics g;
try {
g = this.getGraphics(); //a new image is created for each frame, this gets the graphics for that image so we can draw on it
if (g != null && image != null) {
g.drawImage(image, 0, 0, null);
g.dispose(); //not associated with swing, so we have to free memory ourselves (not done by the JVM)
}
image = null;
}catch(Exception e) {System.out.println("Graphics objects error");}
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
typed = 1;
s+=Character.toString(e.getKeyChar());
s+=" ";
System.out.println(s);
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint());
}
#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
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
KeyListener isn‘t designated for listening of keyboard events for Swing JComponents, use KeyBindings instead, output to the Swing GUI should be from Swing Action
You have added key listener by calling this      
addKeyListener(this);

Categories

Resources