Reduce size of EditField - java

I am creating five EditFields with corresponding label fields.
The EditFields use the full width of the screen but I need only want them to use a particular width.

try this code:-
BasicEditField bef = new BasicEditField("BBDeveloper","")
{
public int getPreferredHeight()
{
return 30;
}
public int getPreferredWidth()
{
return 100;
}
public void layout(int width, int height)
{
setExtent(getPreferredWidth(), getPreferredHeight());
super.layout(getPreferredWidth(), getPreferredHeight());
}
};
alter the getPreferredWidth() and getpreferredHeight() returning values... and see if this help you out....

set the change font bellow the rewritable methods like these:
lbDesc = new LabelField(title, LabelField.USE_ALL_WIDTH)
{
protected void paint(Graphics g)
{
//Font font = Font.getDefault().derive(Font.PLAIN,6,Ui.UNITS_pt);
//g.setFont(font);
g.setColor(Color.BLACK);
invalidate();
super.paint(g);
}
};
Font font = Font.getDefault().derive(Font.PLAIN,6,Ui.UNITS_pt);
lbDesc.setFont(font);

Related

how do you draw a line that resize when window size change? [duplicate]

I've written an app that custom draws everything inside paint() based on fixed pixel positions. Then I disabled resize of the frame so its always visible.
However, now I would like to be able to resize it but I dont want to change my drawling code. I was hoping I could grab the 300x300 square of the Graphics g object and resize it to the JFrame current size after all of my drawling code, but I have no idea what I'm doing.
Here sample code. In this I want the 100x100 square to remain in the middle, proportionate to the resized JFrame:
package DrawAndScale;
import java.awt.Color;
import java.awt.Graphics;
public class DASFrame extends javax.swing.JFrame {
public DASFrame() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setSize(300, 300);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DASFrame().setVisible(true);
}
});
}
#Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fill3DRect(100, 100, 100, 100, true);
}
}
Thanks.
Assuming you rename your method that paints for 300x300 as paint300, define a buffered image:
#Override public void paint(Graphics g) {
Image bufferImage = createImage(300, 300); // empty image
paint300(bufferImage.getGraphics()); // fill the image
g.drawImage(bufferImage, 0, 0, null); // send the image to graphics device
}
Above is when you want to draw at full size (300x300).
If your window is resized:
#Override public void paint(Graphics g) {
Image bufferImage = createImage(300, 300);
paint300(bufferImage.getGraphics());
int width = getWidth();
int height = getHeight();
CropImageFilter crop =
new CropImageFilter((300 - width)/2, (300 - height)/2 , width, height);
FilteredImageSource fis = new FilteredImageSource(bufferImage, crop);
Image croppedImage = createImage(fis);
g.drawImage(croppedImage, 0, 0, null);
}
The new classes are from from java.awt.image.*.
I didn't test this code. It's just to send you in the right direction.
if you want to painting Custom paint then look for JLabel or JPanel and including Icon/ImageIcon inside, simple example about that
import java.awt.*;
import javax.swing.*;
public class MainComponentPaint extends JFrame {
private static final long serialVersionUID = 1L;
public MainComponentPaint() {
setTitle("Customize Preffered Size Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void display() {
add(new CustomComponent());
pack();
setMinimumSize(getSize());
setPreferredSize(getSize());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
setVisible(true);
}
});
}
public static void main(String[] args) {
MainComponentPaint main = new MainComponentPaint();
main.display();
}
}
class CustomComponent extends JComponent {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
for (int i = 0; i < Math.max(w, h); i += 20) {
g.drawLine(i, 0, i, h);
g.drawLine(0, i, w, i);
}
}
}
Not an expert, but you could just scale the Graphics2D object (the passed Graphics is in fact a Graphics2D instance), where the x and y ratios are the ratios of the fixed size you chose to draw and the actual size of the frame.
See http://download.oracle.com/javase/6/docs/api/java/awt/Graphics2D.html#scale%28double,%20double%29
You could do this with some math.
public void paint(Graphics g){
int height = 100;
int width = 100;
int x = (this.getWidth() / 2) - (width / 2);
int y = (this.getHeight() / 2) - (height / 2);
g.setColor(Color.BLACK);
g.fill3DRect(x, y, width, height, true);
}
Or if you wanted to keep the width and height of the box with the same proportion, use int width = this.getWidth() / 3; and int height = this.getHeight() / 3.
The other option is to use Graphics2D.scale(), as JB pointed out, the passed Graphics object is actually a Graphics2D object.

JSlider image behind track

I want to put an image (visualization of an audio) behind the JSlider which represents the audioplayer, the process of playing.
First I tried to overwrite the paint-method of the Slider
public void paintComponent(Graphics g) {
// Draw the previously loaded image to Component
g.drawImage(img, 0, -100, null);
super.paintComponent(g);
}
this worked, but the image is higher than the slider, so my next try was a JLayeredPane, where I put the JSlider above a JLabel with the image. Looks good for the first moment. But I mentioned that I need the image behind the track of the slider, not the whole slider. There is space to the left and right. Can anybody tell me a way how to calculate this space? Or the width and offset of the track to the border of the slider? This should run under Windows and MacOs, so different LookAndFeels, so I think hard coded values will not work.
Example Slider with background image
Thankyou.
My solution for this Problem is now to overwrite the SliderUI. So this is a very special component, so it's nonrelevant that it looks the same on all LookAndFeels.
It supports also jumping directly to mouse position, which is different to BasicSliderUI.
/**
*
* Custom SliderUI for AudioPlayer with audioimage in background
*/
public class AudioSliderUI extends BasicSliderUI {
private BasicStroke stroke = new BasicStroke(1f, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND, 0f);
public AudioSliderUI(AudioSlider b) {
super(b);
}
#Override
public void paint(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
super.paint(g, c);
}
#Override
protected Dimension getThumbSize() {
return new Dimension(2, 200);
}
#Override
public void paintTrack(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Stroke old = g2d.getStroke();
g2d.setStroke(stroke);
g2d.setPaint(Color.WHITE);
if (slider.getOrientation() == SwingConstants.HORIZONTAL) {
g2d.drawLine(trackRect.x, trackRect.y + trackRect.height / 2,
trackRect.x + trackRect.width, trackRect.y + trackRect.height / 2);
} else {
g2d.drawLine(trackRect.x + trackRect.width / 2, trackRect.y,
trackRect.x + trackRect.width / 2, trackRect.y + trackRect.height);
}
g2d.setStroke(old);
Image img = ((AudioSlider)slider).getImage();
g2d.drawImage(img, trackRect.x, trackRect.y, trackRect.width, trackRect.height, slider);
}
#Override
public void paintThumb(Graphics g) {
Rectangle knobBounds = thumbRect;
int w = knobBounds.width;
int h = 100;
int newStarty = knobBounds.height/2- h/2;
g.translate(knobBounds.x, knobBounds.y);
// "plain" version
g.setColor(Color.YELLOW);
g.fillRect(0, newStarty, w, h);
}
#Override
protected TrackListener createTrackListener(JSlider slider) {
return new TrackListener() {
#Override
public void mousePressed(MouseEvent e) {
if (UIManager.getBoolean("Slider.onlyLeftMouseButtonDrag")
&& SwingUtilities.isLeftMouseButton(e)) {
JSlider slider = (JSlider) e.getComponent();
switch (slider.getOrientation()) {
case SwingConstants.VERTICAL:
slider.setValue(valueForYPosition(e.getY()));
break;
case SwingConstants.HORIZONTAL:
slider.setValue(valueForXPosition(e.getX()));
break;
default:
throw new IllegalArgumentException(
"orientation must be one of: VERTICAL, HORIZONTAL");
}
super.mousePressed(e); // isDragging = true;
super.mouseDragged(e);
} else {
super.mousePressed(e);
}
}
#Override
public boolean shouldScroll(int direction) {
return false;
}
};
}
}
Matching Slider:
public class AudioSlider extends JSlider {
private Image img;
public AudioSlider() {
setOpaque(false);
}
/**
* #return the img
*/
public Image getImage() {
return img;
}
public void setImage(Image img) {
this.img = img;
}
}
Works for me, maybe covers not all prospects.

Margin for Custom JButton - Java

I've created a custom button for my application by extending Jbutton, and I've got it to paint the way I want, but for some reason, even though I call setMargin() in the constructor, the buttons have 0 margin, like so:
Is there something I'm doing wrong in my code? How is it that standard JButtons have margins, but my custom buttons don't?
The java code for my button:
public class CToolbarButton extends JButton
{
private static final Dimension SIZE = new Dimension(48, 48);
private static final int MARGIN_VAL = 50;
private static final Insets MARGIN = new Insets(MARGIN_VAL, MARGIN_VAL, MARGIN_VAL, MARGIN_VAL);
private static final Color FILL_NORM = Color.GRAY;
private static final Color FILL_ACTIVE = new Color(FILL_NORM.getRed()-25, FILL_NORM.getGreen()-25, FILL_NORM.getBlue()-25);
private static final Color BORDER_NORM = Color.BLACK;
private static final Color BORDER_ACTIVE = Color.YELLOW;
public CToolbarButton()
{
super();
setContentAreaFilled(false);
setFocusable(false);
setMargin(MARGIN);
}
#Override
public void paintComponent(Graphics g)
{
if (getModel().isArmed())
{
g.setColor(FILL_ACTIVE);
}
else
{
g.setColor(FILL_NORM);
}
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override
public void paintBorder(Graphics g)
{
if (getModel().isArmed())
{
g.setColor(BORDER_ACTIVE);
}
else
{
g.setColor(BORDER_NORM);
}
g.drawRect(0, 0, getWidth(), getHeight());
}
#Override
public boolean contains(int x, int y)
{
return (x >= 0 &&
x <= getWidth() &&
y >= 0 &&
y <= getHeight());
}
#Override
public Dimension getPreferredSize()
{
return SIZE;
}
#Override
public Dimension getMinimumSize()
{
return SIZE;
}
#Override
public Dimension getMaximumSize()
{
return SIZE;
}
}
Instead of trying to override the paint method for the button, I'm just going to use images to simulate different looks for buttons instead.

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:
A solid square-shaped block of color (color decided at runtime).
Which should be added to a VerticalFieldManager.
Thanks in advance!
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);
}
}
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);

PhoneScreenVerticalManager weirdness on incoming call

Im making an app which has a listener on incoming calls and then adds fields til the phonescreen..
However i cannot seem to really control the width of either labelfields or the PhoneScreenVerticalManager i use.
If i try to set a border or background on the PhoneScreenVerticalManager nothing happens at all.
It also seems like USE_ALL_WIDTH in the labelfield constructor doesn't change anything.
And getting the labelfields to left align i also couldn't get to work (tried DrawStyle.Left in the labelfield constructor).
here is my code:
public Incoming(int callId) {
this.callId = callId;
PhoneCall call = Phone.getCall(callId);
String number = call.getPhoneNumber();
Vector contact = ContactUtil.getContactByPhone(number);
screenModel = new ScreenModel(callId);
phoneScreenPortrait = screenModel.getPhoneScreen(PhoneScreen.PORTRAIT, PhoneScreen.INCOMING);
final XYRect rect = screenModel.getDimensions(PhoneScreen.PORTRAIT, PhoneScreen.INCOMING);
PhoneScreenVerticalManager manager = new PhoneScreenVerticalManager()
{
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.setBackgroundColor(Color.WHITE);
g.clear();
super.paint(g);
}
protected void sublayout(int width, int height)
{
super.sublayout(rect.width, height);
super.setExtent(rect.width, height);
}
};
manager.setBackground(BackgroundFactory.createSolidBackground(Color.RED));
manager.setBorder(BorderFactory.createSimpleBorder(new XYEdges(BORDER_PADDING, BORDER_PADDING, BORDER_PADDING, BORDER_PADDING), Border.STYLE_SOLID));
String s = res.getString(FOUND_IN_CONTACTS);
LabelField header = new LabelField(s, LabelField.USE_ALL_WIDTH)
{
protected void layout(int width, int height)
{
super.layout(rect.width, height);
setExtent(rect.width, height);
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.setBackgroundColor(Color.WHITE);
g.clear();
super.paint(g);
}
};
header.setBackground(BackgroundFactory.createSolidBackground(Color.WHITE));
manager.add(header);
LabelField label = new LabelField(contact.firstElement().toString(), LabelField.USE_ALL_WIDTH)
{
protected void layout(int width, int height)
{
super.layout(rect.width, height);
setExtent(rect.width, height);
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.setBackgroundColor(Color.WHITE);
g.clear();
super.paint(g);
}
};
label.setBackground(BackgroundFactory.createSolidBackground(Color.WHITE));
manager.add(label);
phoneScreenPortrait.add(manager);
screenModel.sendAllDataToScreen();
}
Any ideas would be greatly appreciated!ยจ
Thanks
though the phonescreen managers are derived from the field manager it doesn't support all the field manager properties.
so the solution is to set up normal field manager and then add those to the phonescreen managers

Categories