Roshnal
Roshnal

Reputation: 1314

How can I draw a solid square in BlackBerry?

I'm making a BlackBerry OS 6+ application and I need to draw a solid square of a specific color (given at runtime) but it should be add-able to a VerticalFieldManager. So I think custom-drawing using a Graphics object is not an option.

I already tried setting the background color of a LabelField to the color I want and adding that LabelField to the VerticalFieldManager. To get the square-shaped appearance, I tried overriding the getPreferredWidth() and getPreferredHeight of LabelField to return a higher value (eg: 150). But although the width was correctly displayed, the height stayed the same no matter what value I returned.

So is there any way I can achieve this? In summary, what I want is:

Thanks in advance!

Upvotes: 1

Views: 229

Answers (2)

iKushal
iKushal

Reputation: 2899

VerticalFieldManager vfm = new VerticalFieldManager();

    Field f = new Field() {

        protected void paint(Graphics graphics) {
            graphics.setBackgroundColor(Color.RED);
            graphics.clear();
            graphics.drawRect(10, 10, 100, 100);
            graphics.fillRect(10, 10, 100, 100);
        }

        protected void layout(int width, int height) {
            // TODO Auto-generated method stub

            setExtent(200, 200);
        }
    };
    vfm.add(f);

    add(vfm);

Upvotes: 0

rfsk2010
rfsk2010

Reputation: 8611

try this code , Pass in the color in the constructor.

import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;

public class CustomField extends Field
{

private int backgroundColour; 
private int fieldWidth;
private int fieldHeight; 
private int padding = 8;

public CustomField(int color)
{
    super(Field.FOCUSABLE); 
    fieldHeight = 100;
    fieldWidth = 100;
    this.setPadding(2, 2, 2, 2);
    this.backgroundColour=color;
} 

public int getPreferredWidth()
{
    return fieldWidth;
}

public int getPreferredHeight()
{
    return fieldHeight;
}

protected void layout(int arg0, int arg1)
{
    setExtent(getPreferredWidth(), getPreferredHeight());
}

protected void drawFocus(Graphics graphics, boolean on)
{

} 

protected void paint(Graphics graphics)
{
    graphics.setColor(backgroundColour);
    graphics.fillRect(0, 0, fieldWidth, fieldHeight); 
}
}

Upvotes: 3

Related Questions