Reputation: 31
I'm new to Java and teaching myself and trying to build this program. It will create dots when the mouse clicks, but won't draw a line when the button is pushed. (eventually the line will connect the dots, but I'm not there yet.) First I just need to get it to draw something when pushed and work from there. I've tried multiple things and I can't get it to work. Here is my code:
public void init()
{
LineDrawListener listener = new LineDrawListener ();
addMouseListener (listener);
Button lineGraph = new Button("Graph Line");
lineGraph.addActionListener (this);
add (lineGraph, BorderLayout.EAST);
setBackground (Color.yellow);
setSize (APPLET_WIDTH, APPLET_HEIGHT);
}
public void paint(Graphics g)
{
// draws dots on screen
g.setColor(Color.blue);
if (current != null)
{
xcoordinates.addElement (current.x);
ycoordinates.addElement (current.y);
count++;
g.fillOval (current.x-4, current.y-4, 10, 10);
repaint();
}
if (push == true)
{
g.drawLine (5, 5, 30 , 30);
repaint();
}
}
class LineDrawListener extends MouseAdapter
{
public void mouseClicked (MouseEvent event)
{
current = event.getPoint();
repaint();
}
}
public void actionPerformed (ActionEvent event)
{
Object action = event.getSource();
if(action==lineGraph)
{
push = true;
}
}
Any help on how to get the button to work would be much appreciated. Thanks in advance.
Upvotes: 3
Views: 117
Reputation: 324108
Don't override paint(). Don't invoke repaint() in a painting method, this can cause in infinite loop.
Check out Custom Painting Approaches for working examples of the two common ways to do custom paintint:
Upvotes: 4
Reputation: 208974
JApplet
Rather paint on a JPanel
and override the paintComponent
method and call super.paintComponet(g)
@Override
protected void paintComponent(Graphic g){
super.paintComponent(g);
...
}
Don't call repaint()
from inside the paint()
method. Call it in your actionPerformed()
Number 3 is your most dire problem
Upvotes: 4
Reputation: 114250
The reason you can not get the line to draw is that repaint()
posts a request to repaint the component. You are using it as if it refreshes the view somehow. You need to change three things in your code, all in paint()
:
repaint()
in paint()
paintComponent()
rather than paint()
so your borders get drawn if you should ever have them at a later time. super.paintComponent()
in paintComponent()
to do some initialization for you. It is probably OK not to for something this simple, but good practice for the future.Here is what the code would look like:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// draws dots on screen
g.setColor(Color.blue);
if (current != null)
{
xcoordinates.addElement (current.x);
ycoordinates.addElement (current.y);
count++;
g.fillOval (current.x-4, current.y-4, 10, 10);
}
if (push == true)
{
g.drawLine (5, 5, 30 , 30);
}
}
Upvotes: 4