How to drag and draw line between 2 points in Java Swing - java

I would like to draw a line between two xy coordinate with mouse drag, but cannot get anything to draw
its a gui application using swing and awt, I currently have the mouse log the initial and final xy positions using mouse events which are stored in an array as [x1,y1,x2,y2], however, cannot get a line to draw between them.
The drawline is its own function called into the main
edit:
say I have 2 classes;
public class mainApp extends JFrame implements ActionListener, Runnable {
private JPanel jpanel = new JPanel();
private mainApp(String title) throws HeadlessException {
super(title);
}
private void createGUI() {
// TODO
// ...
// cannot call unless is static
drawStraightLine.drawLine(jpanel);
this.pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {}
#Override
public void run() {createGUI();}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new mainApp("drawline"));
}
}
public class drawStraightLine extends JPanel {
public static void drawLine(JPanel jpanel) {
// content which conceivably works
// mouselisteners and repaint()
public void paintComponent (Graphics g){
super.paintComponent(g);
if (check != null) {
Color purple = new Color(128, 0, 128);
g.setColor(purple);
g.drawLine(x1, y1, x2, y2);
}
}
}
i cannot call drawline(jpanel) unless it is a static function, but making it static causes the mouselisteners and repaint to become invalid.
while as long as Graphics g is inside a function and not directly in the class it will become an invalid symbol (ignoring check and xy values as placeholders)

you don't need to have arrays or even X & Y.you can use the getPoint() method of mouseEvent.
try this:
public static void main(String args[]) throws Exception {
JFrame f = new JFrame("Draw a Line");
f.setSize(300, 300);
f.setLocation(300, 300);
f.setResizable(false);
JPanel p = new JPanel() {
Point pointStart = null;
Point pointEnd = null;
{
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointStart = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
pointStart = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
pointEnd = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
pointEnd = e.getPoint();
repaint();
}
});
}
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) {
g.setColor("put your color here");
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}
}
};
f.add(p);
f.setVisible(true);
}

Related

Why does this program only display the last graphic?

Im using JPanel and JFrame to create a program that can draw lines and circles. The problem is that my program only redraws the last object added.
I have tried moving around the repaint. For some reason, when I directly draw shapes onto the graphic in paintComponent(), they show up and refresh each frame. However, I have methods inside of paintComponent that pass the graphic variable to elsewhere methods that draw to the graphic object, these are the shapes that do not show up.
Painter Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Painter implements ActionListener, MouseListener, MouseMotionListener {
/**
*
*/
Color temp = Color.RED;
// 0 = line, 1 = circle
int object = 0;
PaintingPanel canvas;
Point startPoint = new Point();
Point endPoint = new Point();
Painter() {
//buttons
JButton circleBut = new JButton();
JButton lineBut = new JButton();
//frame
//close operation
//resizes
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
//holder holds the information
JPanel holder = new JPanel();
JPanel leftPanel = new JPanel();
holder.setLayout(new BorderLayout());
leftPanel.setLayout(new GridLayout(3, 1)); // 3 by 1 grid
JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(1, 2)); // 3 by 1 grid
frame.add(holder);
// circle and line buttons
circleBut.setText("Circle");
lineBut.setText("Line");
northPanel.add(circleBut);
northPanel.add(lineBut);
circleBut.setActionCommand("1");
lineBut.setActionCommand("0");
//
holder.add(northPanel, BorderLayout.NORTH);
// red
JButton redPaint = new JButton();
redPaint.setBackground(Color.RED);
redPaint.setOpaque(true);
redPaint.setBorderPainted(false);
leftPanel.add(redPaint);
redPaint.setActionCommand("red");
// green
JButton greenPaint = new JButton();
greenPaint.setBackground(Color.GREEN);
greenPaint.setOpaque(true);
greenPaint.setBorderPainted(false);
leftPanel.add(greenPaint);
greenPaint.setActionCommand("green");
// blue
JButton bluePaint = new JButton();
bluePaint.setBackground(Color.BLUE);
bluePaint.setOpaque(true);
bluePaint.setBorderPainted(false);
leftPanel.add(bluePaint);
bluePaint.setActionCommand("blue");
holder.add(leftPanel, BorderLayout.WEST);
// still need to add painting panel to the CENTER panel
canvas = new PaintingPanel();
holder.add(canvas, BorderLayout.CENTER);
circleBut.addActionListener(this);
lineBut.addActionListener(this);
redPaint.addActionListener(this);
greenPaint.addActionListener(this);
bluePaint.addActionListener(this);
canvas.addMouseListener(this);
//holder.addMouseMotionListener(this);
// still need to add chat panel to the SOUTH panel
frame.setContentPane(holder);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("red")) {
temp = Color.RED;
System.out.println("received r");
} else if (e.getActionCommand().equals("green")) {
temp = Color.GREEN;
System.out.println("received g");
} else if (e.getActionCommand().equals("blue")) {
temp = Color.BLUE;
System.out.println("received b");
} else if (e.getActionCommand().equals("0")) {
object = 0;
System.out.println("received 0");
} else if (e.getActionCommand().equals("1")) {
object = 1;
System.out.println("received 1");
}
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
startPoint.setLocation(e.getPoint());
}
#Override
public void mouseReleased(MouseEvent e) {
// and this one
endPoint.setLocation(e.getPoint());
if (object == 0) {
canvas.addPrimitive(new Line(startPoint, endPoint, temp));
}
if (object == 1){
canvas.addPrimitive(new Circle(startPoint, endPoint, temp));
}
canvas.repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
Painter game1 = new Painter();
}
}
PaintingPrimitives:
`
import java.awt.Graphics;
import java.awt.Color;
public abstract class PaintingPrimitive{
Color color;
PaintingPrimitive(Color color) {
this.color = color;
}
// This is an example of the Template Design Pattern
// this is all invariant code
public final void draw(Graphics g) {
g.setColor(color);
drawGeometry(g);
}
public void setColor(Color color) {
this.color = color;
}
protected abstract void drawGeometry(Graphics g);
}
Line Class:
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Color;
public class Line extends PaintingPrimitive{
Point startPoint = new Point();
Point endPoint = new Point();
public Line(Point start, Point end, Color c) {
super(c);
this.startPoint = start;
this.endPoint = end;
}
public void drawGeometry(Graphics g) {
System.out.println("graw geo called");
g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
}
#Override
public String toString() {
return "Line";
}
}
Painting Panel:
import java.util.ArrayList;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
public class PaintingPanel extends JPanel {
ArrayList<PaintingPrimitive> primitives = new ArrayList<PaintingPrimitive>();
PaintingPanel() {
setBackground(Color.WHITE);
}
public void addPrimitive(PaintingPrimitive obj) {
primitives.add(obj);
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// i'm confident that this is not painting to the right graphics
for (PaintingPrimitive shape : primitives) {
//g.dispose();
//this line works. this line is drawn each time its updated.
g.drawLine(0,0,100,100);
shape.draw(g);
}
}
}
`
Okay, that was weird, until it wasn't. Your problem basic centers around...
public void mousePressed(MouseEvent e) {
startPoint.setLocation(e.getPoint());
}
#Override
public void mouseReleased(MouseEvent e) {
// and this one
endPoint.setLocation(e.getPoint());
if (object == 0) {
canvas.addPrimitive(new Line(startPoint, endPoint, temp));
}
You create a single instance of startPoint and endPoint and simply update the location of each Point. You then pass these to each primitive you create. This means that each primitive is using the SAME instance of startPoint and endPoint. So, each time you call setLocation ALL the primitives are been updated.
Instead, do something more like...
#Override
public void mousePressed(MouseEvent e) {
startPoint = new Point(e.getPoint());
}
#Override
public void mouseReleased(MouseEvent e) {
// and this one
endPoint = new Point(e.getPoint());
And because I'm paranoid and don't trust any one, I'd probably also do...
public class Line extends PaintingPrimitive {
Point startPoint = new Point();
Point endPoint = new Point();
public Line(Point start, Point end, Color c) {
super(c);
this.startPoint = new Point(start);
this.endPoint = new Point(end);
}
Just to be sure

Action is not getting triggered when using Event handlers- KeyListener

So I am new to event handlers, and I wanted to create a program where I made a Purple panel inside a frame and if the user clicks the mouse button in the area of the panel and then types % with their keyboard, I want the panel to draw a line segment in the area of the panel. This is just testing the event handlers. Right now, I am trying it but it does not work. All help will be appreciated. After I get the hand of this, I want to try out the repaint() method, where if someone does the same actions as before, I wanted to check the background of the Panel. If you can help me with both, that'd be awesome but it is not a priority. Thank you.
import java.awt.Graphics; // for classes Graphics, Color, Font, Image
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent; // for classes KeyListener, MouseListener
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame; // for classes JFrame, JPanel, JLabel
import javax.swing.JPanel;
public class GardenGrows
{
public GardenGrows()
{
}
public static void main(String[] args)
{
GardenGrows gg = new GardenGrows();
gg.runIt();
}
// makes the frame and handles all properties of the frame
// also instantiates the Garden.java object
public void runIt()
{
JFrame frame = new JFrame ("Garden");
frame.setDefaultCloseOperation( frame.EXIT_ON_CLOSE );
frame.setLayout(null);
frame.setBackground(Color.GRAY);
frame.setSize( 1200,700);
frame.setLocation( 50, 10);
frame.setResizable(true);
frame.setVisible(true);
Garden gar = new Garden();
frame.getContentPane().add(gar);
}
}
class Garden extends JPanel implements KeyListener, MouseListener
{
private boolean mouseClicked;
private boolean keyClicked;
private int xpos;
private int ypos;
public Garden()
{
mouseClicked = false;
keyClicked = false;
addKeyListener(this);
addMouseListener(this);
setBackground(Color.PINK);
setLocation(50,50);
setSize(1000,500);
}
public void mousePressed(MouseEvent evt)
{
int x = evt.getX();
int y = evt.getY();
if(x>=50 || x<=1050 && y<=50 || y>=550)
{
mouseClicked = true;
}
}
public void mouseClicked(MouseEvent evt){}
public void mouseReleased(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseExited(MouseEvent evt){}
public void keyReleased(KeyEvent evt){}
public void keyPressed(KeyEvent evt){}
public void keyTyped(KeyEvent evt)
{
int letter = evt.getKeyCode();
if (letter == 13)
{
keyClicked =true;
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(keyClicked && mouseClicked)
g.drawLine(50,0,110,120);
}
}
Making a key listener work in a JPanel, will not be so simple, because it is not focusable. (Think about a JTextField, when you write text on it, it is focused). So, in order to make this work you will have to use KeyBindings. In practice, remove the KeyListener implementation from your JPanel, and use KeyBindings.
public class GardenGrows {
public GardenGrows() {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
// All swing applications must run on EDT Thread
GardenGrows gg = new GardenGrows();
gg.runIt();
});
}
// makes the frame and handles all properties of the frame
// also instantiates the Garden.java object
public void runIt() {
JFrame frame = new JFrame("Garden");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setBackground(Color.GRAY);
frame.setSize(1200, 700);
frame.setLocation(50, 10);
frame.setResizable(true);
frame.setVisible(true);
Garden gar = new Garden();
frame.getContentPane().add(gar);
}
}
class Garden extends JPanel implements MouseListener {
private boolean mouseClicked;
private boolean keyClicked;
private int xpos;
private int ypos;
public Garden() {
mouseClicked = false;
keyClicked = false;
addMouseListener(this);
setBackground(Color.PINK);
setLocation(50, 50);
setSize(1000, 500);
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_5, KeyEvent.SHIFT_MASK),
"percentageClicked");
getActionMap().put("percentageClicked", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
keyClicked = true;
repaint(); // Try to draw the line
}
});
}
public void mousePressed(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
if (x >= 50 || x <= 1050 && y <= 50 || y >= 550) {
mouseClicked = true;
repaint(); // Try to draw the line
}
}
public void mouseClicked(MouseEvent evt) {
}
public void mouseReleased(MouseEvent evt) {
}
public void mouseEntered(MouseEvent evt) {
}
public void mouseExited(MouseEvent evt) {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (keyClicked && mouseClicked)
g.drawLine(50, 0, 110, 120);
}
}

label that shows Coordinates of mouse

At university we started Java programming and got the task to write a program that draws a vertical and a horizontal line at the location where the mouse currently is. Also we should add a Label that shows the coordinates of the mouse. I got the drawing thing working but when I try to add a label, it won't show up? I started with a test-label, but even that isn't shown inside the frame. Can someone help me?
public class Coordinates extends JPanel implements MouseListener, MouseMotionListener {
private Point currentPoint = new Point(-50, -50);
public Coordinates(){
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.blue);
g.drawLine(currentPoint.x, currentPoint.y+1000, currentPoint.x, currentPoint.y-1000);
g.drawLine(currentPoint.x+1000, currentPoint.y, currentPoint.x-1000, currentPoint.y);
}
public void mousePressed(MouseEvent e){
currentPoint = e.getPoint();
repaint();
};
static JLabel label = new JLabel();
public static void main(String[] args) {
JFrame frame = new JFrame("Koordinaten");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(label);
JComponent newContentPane = new Coordinaten();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
label.setText(currentPoint.toString());
currentPoint = e.getPoint();
repaint();
}
}
Do all your painting within the JPanel's paintComponent method not the paint method, and be sure to call the super's paintComponent method within your override, usually at the start of the override method.
You need to add a JLabel to your JPanel to have it display anything. Your code does not do this. And then in the MouseMotionListener, set the JLabel's text with the mouse coordinates.
For example:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class DrawPanel extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private JLabel locationLabel = new JLabel();
public DrawPanel() {
add(locationLabel);
addMouseMotionListener(new MyMouseAdapter());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // this allows JPanel to do housekeeping painting first
// do drawing here!
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
// get Point location and turn into a String
String location = String.format("[%d, %d]", e.getX(), e.getY());
// set the label's text with this String
locationLabel.setText(location);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
With the cross-hairs:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class DrawPanel extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private JLabel locationLabel = new JLabel();
private int mouseX = 0;
private int mouseY = 0;
public DrawPanel() {
add(locationLabel);
addMouseMotionListener(new MyMouseAdapter());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // this allows JPanel to do housekeeping
// painting first
// do drawing here!
g.drawLine(0, mouseY, getWidth(), mouseY);
g.drawLine(mouseX, 0, mouseX, getHeight());
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
// get Point location and turn into a String
String location = String.format("[%d, %d]", mouseX, mouseY);
// set the label's text with this String
locationLabel.setText(location);
repaint();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Basically, a JLabel is made like this, defined outside of the main method:
static JLabel label = new JLabel();
In your main method
frame.add(label);
And in your mouseMoved method you would put this:
label.setText(currentPoint.toString());

can't draw on a JPanel after repaint method

I'm experimenting on a GUI that I programmed and I don't understand how I can fix my problem:
My GUI contains a jPanel that on receiving a mouseclick, paints a point with filloval command.
private void myPnlMousePressed(java.awt.event.MouseEvent evt) {
changed = true;
p.x = evt.getX();
p.y = evt.getY();
drewPoints(p.x, p.y);
}
private void drewPoints (int x, int y) {
if (gf == null) {
gf = (Graphics)myPnl.getGraphics();
}
myPointsList.add(new Point(x, y));
gf.fillOval(x, y, 5, 5);
xVal.setText("X = " + x);
yVal.setText("Y = " + y);
}
everything works fine but when I want to open an XML file that I created to save all the points it doesn't work.
The problem is that when I use the repaint method on the jPanel after choosing a file, all the points loads fine but the panel can't draw the points.
If I put the repaint method in the open button listener (before the choosing file) it works, but then if the user cancels the open option so the panel stays blank and I don't want to draw the points again.
I think it happens because the repaint process is not finished.
All the points added to a private List.
private void OpenFile() {
try {
File thisFile;
JFileChooser of = new JFileChooser();
int option = of.showOpenDialog(of);
if (option == JFileChooser.APPROVE_OPTION){
thisFileName = of.getSelectedFile().getPath();
thisFile = new File(thisFileName);
if (!of.getSelectedFile().getName().endsWith(".xml")) {
String error = "Error, You didn't select XML file";
JOptionPane.showMessageDialog(this, error, "Wrong type of file", JOptionPane.INFORMATION_MESSAGE);
return;
}
myPnl.repaint();
myPointsList.clear();
....
....
....
for (int i = 0; i < pointsList.getLength(); i++) {
Element point = (Element) pointsList.item(i);
p.x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
p.y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(p.x, p.y);
}
....
how can I make it work??
Don't use gf = (Graphics)myPnl.getGraphics();, this is not how painting in Swing works. The getGraphics method can return null and is nothing more then a snap shot of the last paint cycle, any thing you paint to it will be erased on the next paint cycle (repaint).
Instead, override the JPanels paintComponent and put all you painting logic there. There is an expectation that when called, you are expected to fully re-paint the current state of the component.
See Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing
You have to use the repaint() and override the paint() method:
class MyPanel extends JPanel implements MouseListener
{
private int x;
private int y;
public MyPanel() {
super();
addMouseListener(this);
}
#Override public void mouseEntered(MouseEvent e) { }
#Override public void mouseExited(MouseEvent e) { }
#Override public void mouseClicked(MouseEvent e) { }
#Override public void mousePressed(MouseEvent e) { }
#Override public void mouseReleased(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
#Override public void paint(Graphics g) {
super.paint(g);
g.fillOval(x, y, 10, 10);
}
}
If you want to draw all points, don't use x and y but a list of points:
class MyPanel extends JPanel implements MouseListener
{
private ArrayList<Point> points = new ArrayList<>();
public MyPanel() {
super();
addMouseListener(this);
}
#Override public void mouseEntered(MouseEvent e) { }
#Override public void mouseExited(MouseEvent e) { }
#Override public void mouseClicked(MouseEvent e) { }
#Override public void mousePressed(MouseEvent e) { }
#Override public void mouseReleased(MouseEvent e) {
points.add(new Point(e.getX(), e.getY()));
repaint();
}
#Override public void paint(Graphics g) {
super.paint(g);
for (Point p : points)
g.fillOval(p.getX(), p.getY(), 10, 10);
}
}
where:
class Point
{
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Then use it:
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
MyPanel myPanel = new MyPanel();
frame.add(myPanel);
frame.setVisible(true);
}

using paintComponent method in JApplet

I have create a program in Java which allows dragging of two oval shapes. Now I want to convert it to a JApplet so I made the class extend JApplet instead of original JPanel. The problem with this is that super.paintComponent(g) does not work as it is no longer a parent class.
I have tried creating a JPanel within the class then referring to this but I get the error: The method paintComponent(Graphics) from the type JComponent is not visible
Any heads up on what I need to do or any help would be much appreciated thanks.
Here is my code.
public class Main extends JPanel
{
private static final String TITLE = "Drag me!";
private static final int W = 640;
private static final int H = 480;
private Point origin = new Point(W / 2, H / 2);
private Point mousePt;
public Main() {
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
this.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
mousePt = e.getPoint();
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter()
{
#Override
public void mouseDragged(MouseEvent e)
{
int dx = e.getX() - mousePt.x;
int dy = e.getY() - mousePt.y;
origin.setLocation(origin.x + dx, origin.y + dy);
mousePt = e.getPoint();
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(0, origin.y, getWidth(), origin.y);
g.drawOval(origin.x, 0, origin.x, getHeight());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame(TITLE);
f.add(new Main());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
Instead of modifying your JPanel, keep it and create a new class, your JApplet class:
public class YourJApplet extends JApplet{
public void init(){
final JPanel panel = new YourPanel();
this.setContentPane(panel);
}
}
That's it--now whatever was going on with your panel is now your JApplet.

Categories

Resources