Java Reference
In-Depth Information
just draws an empty or filled rectangle, depending on the boolean value given to the constructor.
Besides the DynLayout with the two instances of RectComponent ( rect1 and rect2 ), the
application frame contains text fields for setting the width and height variables. These are useful for
demonstrating the effects of the dynamic layout because the screen size itself is usually fixed. The
constructor of the DynLayout arranges the control components and sets the listener. The
itemSelected() method is responsible for changing the displayed RectComponent if the choice
control is switched.
Although this example is limited to a special case, it serves as a demonstration for some principles of
dynamic layout. Feel free to extend it as needed, for example by querying the actual sizes of child
components instead of using the width and height variables or by adding support for more than two
child components.
Listing 4.10 DynLayout.java
import java.awt.*;
import java.awt.event.*;
import javax.microedition.midlet.*;
public class DynLayout extends MIDlet implements ActionListener,
ItemListener {
int width = 100;
int height = 100;
Frame frame = new Frame ("DynLayout");
TextField widthField = new TextField ("100");
TextField heightField = new TextField ("100");
Choice cardChoice = new Choice();
Button applyButton = new Button ("Apply");
DynPanel dynPanel = new DynPanel();
class RectComponent extends Component {
boolean fill;
public RectComponent (boolean fill) {
this.fill = fill;
}
public void paint (Graphics g) {
Dimension d = getSize();
g.setColor (Color.black);
if (fill)
g.fillRect ((d.width - (width - 5)) / 2,
(d.height - (height - 5)) / 2,
width - 5, height - 5);
else
g.drawRect ((d.width - (width - 5)) / 2,
(d.height - (height - 5)) / 2,
width - 5, height - 5);
}
public Dimension getPreferredSize() {
return new Dimension (width, height);
}
public Dimension getMinimumSize() {
 
Search WWH ::




Custom Search