• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Replace Canvas on User demand

 
Tony Thyer
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code works, but only if the applet is re-sized by the user.
Grateful for any help.
import java.awt.*;
import java.awt.event.*;
/**
* The control buttons should display alternate canvases, but the first time the blue is displayed the user has to get the applet to re-paint. From then on, it works.
(This is not about changing colours - I need a canvas to accept mouse events and one to be free from the overhead of mouseListener)
*/
public class CanvasOnDemand extends java.applet.Applet
{
private CanvasRed canvasRed;//Works faster - no listener
private CanvasBlue canvasBlue;//implement a listener
private MyControls controls;
public void init()
{
canvasRed = new CanvasRed();
canvasBlue = new CanvasBlue();
controls=new MyControls();
this.setSize(320,360);
setLayout(new BorderLayout());
add("North",controls);
add("Center",canvasRed);
//add("Center",canvasBlue);//NOT BOTH
}
public void showRed()
{
remove(canvasBlue);
add("Center",canvasRed);
}
public void showBlue()
{
remove(canvasRed);
add("Center",canvasBlue);
}
class CanvasRed extends Canvas
{
public CanvasRed()
{
setBackground(Color.red);
}
}
class CanvasBlue extends Canvas //implements a listener
{
public CanvasBlue()
{
setBackground(Color.blue);
}
}

class MyControls extends Panel implements ActionListener
{
private Button redButton,blueButton;
public MyControls()
{
setLayout(new FlowLayout());
setBackground(Color.lightGray);
Panel p = new Panel();
redButton = new Button("Red");
p.add(redButton);
redButton.addActionListener(this);
blueButton = new Button("Blue");
p.add(blueButton);
blueButton.addActionListener(this);
add("North", p);
}
public void actionPerformed(ActionEvent ae)
{
String buttonPressed = ae.getActionCommand();
if (buttonPressed.equals("Red")) showRed();
if (buttonPressed.equals("Blue")) showBlue();
}
}
}
 
Paul Bailey
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you need to repaint after you change the canvas.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tony,
You should also look into using the CardLayout. It would make your life much easier ... instead of reinventing the wheel.
Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic