Nested canvas in GridLayout can't get its width and height
Hello,
I have a class entitled DisplayCanvas, which will accept some parameters from an invocation in another class including a shape and message parameters. These parameters must be centered in the instance of DisplayCanvas.
For some reason, when I use this.getWidth() and this.getHeight() within my DisplayCanvas class, I get 0 and 0! I need the width and height in order to center the parameters the user will enter.
Why does the width and height result at 0? What can I do to get the width and height?
In my DisplayCanvas class notice the lines:
canWidth = this.getWidth();
canHeight = this.getHeight();
For some reason the result is 0 for each!
Here is my code for the DisplayCanvas class:
//import the necessary clases
import java.awt.*;
import java.applet.*;
import javax.swing.*;
//begin the DisplayCanvas
public class DisplayCanvas extends Canvas
//declare private data members to house the width and height of the canvas
private int canWidth;
private int canHeight;
//declare private data members for the shape and message
private String message;
private String shape;
private Color sColor;
private int sWidth;
private int sHeight;
private String font;
private Color ftColor;
private int ftSize;
//declare public data members
//constructor of DisplayCanvas
public DisplayCanvas()
//set the width and height
canWidth = this.getWidth();
canHeight = this.getHeight();
//set all data members to defaults
message = "";
shape = "";
sColor = null;
sWidth = 0;
sHeight = 0;
font = "";
ftColor = null;
ftSize = 0;
} //end the constructor
//begin the setParams function
public void setParams(String m, String s, Color c, int w, int h,
String f, Color ftC, int ftS)
//set all private data members of DisplayShape to the arguments
//this function assumes error checking was done by DemoShape
message = m;
shape = s;
sColor = c;
sWidth = w;
sHeight = h;
font = f;
ftColor = ftC;
ftSize = ftS;
} //end the setParams function
//begin the public paint function of ShowShape
public void paint(Graphics g)
//set and output the shape according to the arguments
//determine the x and y of the shape
int x = (canWidth - sWidth) / 2;
int y = (canHeight - sHeight) / 2;
//set the color for the graphic object
g.setColor(sColor);
//output the shape
g.drawRect(x, y, sWidth, sHeight);
//set and output the message according to the arguments
//set the color and the font for the graphic object
g.setColor(ftColor);
g.setFont(new Font(font, Font.PLAIN, ftSize));
//determine the centering of the message
//output the message with the settings
g.drawString(canWidth + " " + canHeight, 10, 10);
} //end the paint function of ShowShape class
} //end the DisplayCanvas classHere is my form entry class using the nested DisplayCanvas instance entitled drawCanvas:
//import the necessary java packages
import java.awt.*; //for the awt widgets
import javax.swing.*; //for the swing widgets
import java.awt.event.*; //for the event handler interfaces
//no import is needed for the DisplayCanvas class
//if in the same directory as the DemoShape class
public class DemoShape extends JApplet
//declare private data members of the DemoShape class
//declare the entry and display panel containers
private Container entire; //houses entryPanel and displayCanvas
private JPanel entryPanel; //accepts the user entries into widgets
private DisplayCanvas drawCanvas; //displays the response of entries
//required control buttons for the entryPanel
private JTextField xShapeText, yShapeText, messageText, fontSizeText;
private ButtonGroup shapeRadio;
private JRadioButton rect, oval, roundRect;
private JComboBox shapeColorDrop, fontTypeDrop, fontColorDrop;
//declare public data members of the DemoShape class
//init method to initialize the applet objects
public void init()
//arrays of string to be used later in combo boxes
//some are used more than once
String fonts[] = {"Dialog", "Dialog Input", "Monospaced",
"Serif", "Sans Serif"};
String shapes[] = {"Rectangle", "Round Rectangle", "Oval"};
String colors[] = {"Black", "Blue", "Cyan", "Dark Gray",
"Gray", "Green", "Light Gray", "Magenta", "Orange",
"Pink", "Red", "White", "Yellow"};
//declare variables to assist with the layout
//these are the left and right justified x coordinates
int ljX = 10; int rjX = 150;
//this is the y coordinates for the rows
int yRow1 = 10; //the shape rows
int yRow2 = 40;
int yRow3 = 60;
int yRow4 = 130;
int yRow5 = 150;
int yRow6 = 210; //the message rows
int yRow7 = 240;
int yRow8 = 260;
int yRow9 = 300;
int yRow10 = 320;
int yRow11 = 360;
int yRow12 = 380;
//these are the widths for the text boxes, drop downs
//message entry, big message entry and radio buttons
int tWidth = 30; int dWidth = 100;
int mWidth = 250; int bmWidth = 250;
int rWidth = 125;
//the height is universal, even for the messages!
int height = 25;
//set a content pane for the entire applet
//set the size of the entire window and show the entire applet
entire = this.getContentPane();
entire.setLayout(new GridLayout(1, 2));
//create the entry panel and add it to the entire pane
entryPanel = new JPanel();
entryPanel.setLayout(null);
entire.add(entryPanel);
//create the display canvas and add it to the entire pane
//this will display the output
drawCanvas = new DisplayCanvas();
entire.add(drawCanvas);
//entry panel code
//add the form elements in the form of rows
//the first row (label)
JLabel entryLabel = new JLabel("Enter Shape Parameters:");
entryPanel.add(entryLabel);
entryLabel.setBounds(ljX, yRow1, bmWidth, height);
//second row (labels)
JLabel shapeTypeLabel = new JLabel("Select Shape:");
shapeTypeLabel.setBounds(ljX, yRow2, mWidth, height);
entryPanel.add(shapeTypeLabel);
JLabel shapeColorLabel = new JLabel("Select Shape Color:");
shapeColorLabel.setBounds(rjX, yRow2, mWidth, height);
entryPanel.add(shapeColorLabel);
//third row (entry)
rect = new JRadioButton("Rectangle", true);
oval = new JRadioButton("Oval", false);
roundRect = new JRadioButton("Round Rectangle", false);
rect.setBounds(ljX, yRow3, rWidth, height);
oval.setBounds(ljX, yRow3 + 20, rWidth, height);
roundRect.setBounds(ljX, yRow3 + 40, rWidth, height);
shapeRadio = new ButtonGroup();
shapeRadio.add(rect);
shapeRadio.add(oval);
shapeRadio.add(roundRect);
entryPanel.add(rect);
entryPanel.add(oval);
entryPanel.add(roundRect);
shapeColorDrop = new JComboBox(colors);
shapeColorDrop.setBounds(rjX, yRow3, dWidth, height);
shapeColorDrop.addFocusListener(new focusListen());
entryPanel.add(shapeColorDrop);
//the fourth row (labels)
JLabel xShapeLabel = new JLabel("Enter Width:");
xShapeLabel.setBounds(ljX, yRow4, mWidth, height);
entryPanel.add(xShapeLabel);
JLabel yShapeLabel = new JLabel("Enter Height:");
yShapeLabel.setBounds(rjX, yRow4, mWidth, height);
entryPanel.add(yShapeLabel);
//the fifth row (entry)
xShapeText = new JTextField("200", 3);
xShapeText.setBounds(ljX, yRow5, tWidth, height);
xShapeText.addFocusListener(new focusListen());
entryPanel.add(xShapeText);
yShapeText = new JTextField("200", 3);
yShapeText.setBounds(rjX, yRow5, tWidth, height);
yShapeText.addFocusListener(new focusListen());
entryPanel.add(yShapeText);
//the sixth row (label)
JLabel messageLabel = new JLabel("Enter Message Parameters:");
messageLabel.setBounds(ljX, yRow6, bmWidth, height);
entryPanel.add(messageLabel);
//the seventh row (labels)
JLabel messageEntryLabel= new JLabel("Enter Message:");
messageEntryLabel.setBounds(ljX, yRow7, mWidth, height);
entryPanel.add(messageEntryLabel);
//the eighth row (entry)
messageText = new JTextField("Enter your message here.");
messageText.setBounds(ljX, yRow8, mWidth, height);
messageText.addFocusListener(new focusListen());
entryPanel.add(messageText);
//the ninth row (label)
JLabel fontTypeLabel = new JLabel("Select Font:");
fontTypeLabel.setBounds(ljX, yRow9, mWidth, height);
entryPanel.add(fontTypeLabel);
JLabel fontColorLabel = new JLabel("Select Font Color:");
fontColorLabel.setBounds(rjX, yRow9, mWidth, height);
entryPanel.add(fontColorLabel);
//the tenth row (entry)
fontTypeDrop = new JComboBox(fonts);
fontTypeDrop.setBounds(ljX, yRow10, dWidth, height);
fontTypeDrop.addFocusListener(new focusListen());
entryPanel.add(fontTypeDrop);
fontColorDrop = new JComboBox(colors);
fontColorDrop.setBounds(rjX, yRow10, dWidth, height);
fontColorDrop.addFocusListener(new focusListen());
entryPanel.add(fontColorDrop);
//the eleventh row (label)
JLabel fontSizeLabel = new JLabel("Select Font Size:");
fontSizeLabel.setBounds(ljX, yRow11, mWidth, height);
entryPanel.add(fontSizeLabel);
//the final row (entry)
fontSizeText = new JTextField("12", 2);
fontSizeText.setBounds(ljX, yRow12, tWidth, height);
fontSizeText.addFocusListener(new focusListen());
entryPanel.add(fontSizeText);
//display panel code
//use test parameters
//these will later be retrieved from the entries
drawCanvas.setParams("Hello", "roundRect", Color.red,
100, 100, "Serif", Color.black, 12);
//set the applet to visible
//set to visible and display
entire.setSize(800, 600);
entire.setVisible(true);
} //end the init method
//declare an inner class to handle events
private class focusListen implements FocusListener
//supply the implementation of the actionPerformed method
//pass an event variable as the argument
public void focusLost(FocusEvent e)
{ JOptionPane.showMessageDialog(null, "Focus lost."); }
//declare an empty focus gained function
public void focusGained(FocusEvent e) {}
} //end testListen class
} //end DemoShape class
Sorry for glossing over your code sample, particularly as it looks like one of the best I've seen so far on the forums, but I'm pretty sure the answer you are looking for is as follows:
Java doesn't render a component until paint() is called so until then you are not going to have any size settings because the jvm simply doesn't know how big the visual component is. This makes sense when you think about what the jvm is doing. The layout manager controls the display of the components depending on the settings it is supplied. So until it knows how many components you want, where, what kind of spacing, etc, etc, etc, how can the size be determined.
The true cycle of events is therefore:
create an instance of DisplayCanvas,
add it to your container,
make the container visible (which renders the component),
get the size of the DisplayCanvas instance.
You are being hampered because your desired chain of events is:
create an instance of DisplayCanvas,
get the size of the DisplayCanvas instance,
add it to your container,
make the container visible.
This state of affairs is highly annoying and then leads to the next question "what do we do about that?". There is a cunning trick which is to get the jvm to render the component to an off-screen image, thus calculating the dimensions of the component so that you can do precisely the kind of enquiry on the object that you have been looking for. It should be noted that this may not be the visual size for all the reasons given above, but it is the "preferred size" for the component. Check the Swing tutorials and have a look at the section on Layout Managers for a run down on what that means.
Anyway, we can use this handy code sample to determine the preferred size for your component. Notice the call to "paint()" (normally you would never make a direct call to paint() in swing) and the "g.dispose()" to free resources:
package com.coda.swing.desktool.gui;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class PaintUtil
public PaintUtil()
super();
public static Component paintBuffer(Component comp)
Dimension size = comp.getPreferredSize();
comp.setSize(size);
BufferedImage img = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
comp.paint(g2);
g2.dispose();
return comp;
}Before you make a call to getWidth() or getHeight() put in a call to "PaintUtil.paintBuffer(this);" and see what happens.
By the way, I can't claim credit for this code ... and I really wish I could remember where I got it from myself so I can thank them :)
Similar Messages
-
How to get the width and height of the selected rectangle
Hi,
I need to get the width and height of the selected rectangle in indesign cs3 and display the values in a dialog box for user verification.
Regards,
saranHi Saran,
InterfacePtr<IGeometry> itemGeo ( objectUIDRef, UseDefaultIID() );
PMRect ItemCoord = itemGeo->GetStrokeBoundingBox();
PMReal width = ItemCoord->Width();
PMReal height = ItemCoord->Height(); -
Getting maximum width and height of frame
In my Flash CS4 application I have a problem working out the maximum x and y coordinates of the display objects that have been created in a frame using the frame editor. This is the sequence
1. Using the frame editor on the timeline, I create a keyframe with a mixture of library symbols and text/graphics which are not symbols.
2. In AS3 I take all of the screen objects and make them children of a Sprite that I created in my AS3 script. I then delete the objects off the screen and pass the parent Sprite to a class that I use to manage the screen.
3. In the manage screen class the first thing I do is go through the child display objects to work out the maximum x and y coordinates so that I can centralise them on the screen later on.
The problem is that I'm not able to work out the maximum x & y coordinates correctly. There is no problem with the symbol objects, I just add the x and width for example, for the maximum x coordinate. But for the non symbol objects this does not work. They appear to be combined in some way and the x/y & width/height do not seem to correspond to anything in the frame editor.
Is there a writeup anywhere on how Flash manages the graphics/text obects which are not symbols and are created by the editor in keyframes on the timeline? Finding the maximum x and y coordinates of a screen full of objects should be fairly simple, but I cannot see a way of doing it at the moment.
JerryOn my JPanel I want to draw stuff, and for this I need to know the > > width and height of the JPanelIf you are drawing stuff, then you are in control off
how big you want to draw the stuff. You can make the
panel as big or small as you want and do your drawing
accordingly.But doesn't the Layoutmanager of the frame set the size of the added panel according to the rest of the layout, or am I way off here?
Do I need to setPreferredSize() or anything on thepanel before pack()?
Try it and see what happens. If you don't give the
panel a size then the pack() method basically ignores
it as you have found out.Perhaps if I gave an example, you could point me in the right direction? The code below creates a JPanel of size 200x200, and draws a ball at a random spot on the panel. But since the frame is way bigger than 200x200 the panel gets stretched by the layoutmanager (right?). So what I really want to use when I calculate the x and y position is the width and height of the panel as it is displayed in the frame.
Here goes:
import javax.swing.*;
import java.awt.*;
class MyFrame extends JFrame {
public MyFrame() {
super("A ball");
JPanel panel = new JPanel();
panel.setSize(200, 200);
int x = (int)(Math.random()*200);
int y = (int)(Math.random()*200);
panel.add(new Ball(x, y)); // Object Ball draws a ball at x,y
getContentPane().add(panel, BorderLayout.CENTER);
setSize(640, 480);
show();
public static void main(String[] args) {
new MyFrame();
} -
Can I adjust pixel width and height in iPhoto?
I'm trying to find out if it's possible to adjust pixel width and height of a photo without cropping it. iPhoto Help was no help at all.
Thanks.
iBook Mac OS X (10.4.4)For uploading to a site this is the way to do it.
If you wanted to use in another application, you can drag and drop if it is supported, and then use that other application to resize. You can also set up a graphic application as an external editor.
I find it just as quick and easy to export to the desktop, then delete the photos on the desktop when I am done. -
Get image width and height?
In loading an image using the File Browse capability, is there any way to obtain the height and width of the image being loaded? I want to save that along with the MIME type and file name.
Hello,
Take a look at the ORDImage object type, which you can use to obtain the properties of the image -
http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28414/ch_imgref.htm
You can do much more than just accessing the properties too, such as rescaling the image, greyscaling, making a thumbnail etc.
Scott Spendolini did a good blog post on this a while back -
http://spendolini.blogspot.com/2005/10/manipulating-images-with-database.html
John.
(by the way, doesn't this highlight a short-coming of the new forum points system? Scott does a nice long detailed blog post...I just link to it and hopefully get the points ;). -
Hi I have my containers set out to 100% width and 100% height. In the end the actual size will always vary depending on the screen you are viewing it on. How would I go about in finding the containers size during runtime..
Look at the height and width properties. They will be in pixels.
-
How to get WIDTH and HEIGHT fields from applet tag?
I am developing an applet using JDK1.1 (to ensure microsoft jvm compatability).
A problem I'm facing is that there are no getWidth() or getHeight() method for Applet in 1.1, so I am hoping I can get this info from my html: <APPLET CODE="MyApplet" WIDTH=600 HEIGHT=856></APPLET>
getParameter didn't work, so does anyone have any ideas how I could get the width and height?
Cheers,
JamesWrite a jpeg decoder that can figure out how to determine the width/height of a jpeg file? Google it.
Or if you're really lazy, load each jpeg using the
Toolkit.loadImage( URL ) function and use getWidth/getHeight from there, but that's slow. -
Get image properties (width and height)
Hi there,
Does anyone know if there is a way that I could get the width and height of an image to be displayed in a JSP.Image has methods to get the width & height.
-
Hiya.
I'm loading with SWFLoader games that where written using stage functions to get the width and height of the stage and to draw the game and calculate game movements accordinly. When I load a game using SWFLoader, the stage size changes from the stage size of the flash application that i loaded with SWFLoader to the stage size of my entire flex application with breaks the loaded flash application.
is there a way to override the stage related functions in the loaded flash application in order for them to return the proper value ?
if my flash application is width=50px height=50px and it's located at my flex stage at x=20px width=20px,
then the width and height of the stage of the flash application will return 70px.
is there a way to resolve that ?If an app has dependencies on stage size, it will not behave well as a
sub-app. -
I bought a budget sheet app from the apple store, there is no option of sub category given and therefore the app doesn't function can I get its money back ?
Actually, wrong.
The tech support people can help with Playbook purchased apps. If you've called and they said they cannot, you were lied to.
Even in the link you posted, in #10, it states clearly "App Refund related matters are handled by BlackBerry Customer Care." That, my friend is accessed by the support number. Again, if you were told otherwise, you should inform them of such or ask for a manage/supervisor.
And, you don't have a "Partner ID" because you are not a "Partner". The section you're referring to applies to mobile providers, which are the Partners.
Good luck.
1. If any post helps you please click the below the post(s) that helped you.
2. Please resolve your thread by marking the post "Solution?" which solved it for you!
3. Install free BlackBerry Protect today for backups of contacts and data.
4. Guide to Unlocking your BlackBerry & Unlock Codes
Join our BBM Channels (Beta)
BlackBerry Support Forums Channel
PIN: C0001B7B4 Display/Scan Bar Code
Knowledge Base Updates
PIN: C0005A9AA Display/Scan Bar Code -
My IPad was stolen. Where can I get its serial number?
My IPad was stolen. Where can I get its serial number?
Pornwara wrote:
Where can I get its serial number?
See > http://support.apple.com/kb/ht1349
Pornwara wrote:
My IPad was stolen.
Lost or Stolen iOS device > http://support.apple.com/kb/HT5668 -
There is an locked iphone,I can't get its info.Its serial number is 70******A4S.Can you tell me about info of this iphone, and if I want to unlock it,how I do.Thanks.
<Edited by Host>I don't know the meaning about the info of the picture above.Do you know what is the meaning? Thanks.
-
How can we get Dynamic columns and data with RTF Templates in BI Publisher
How can we get Dynamic columns and data with RTf Templates.
My requirement is :
create table xxinv_item_pei_taginfo(item_id number,
Organization_id number,
item varchar2(4000),
record_type varchar2(4000),
record_value CLOB,
State varchar2(4000));
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'USES','fever','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'HOW TO USE','one tablet daily','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'SIDE EFFECTS','XYZ','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'DRUG INTERACTION','ABC','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'OVERDOSE','Go and see doctor','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'NOTES','Take after meal','TX');
select * from xxinv_item_pei_taginfo;
Item id Org Id Item Record_type Record_value State
493991 224 1265-D30 USES fever TX
493991 224 1265-D30 HOW TO USE one tablet daily TX
493991 224 1265-D30 SIDE EFFECTS XYZ TX
493991 224 1265-D30 DRUG INTERACTION ABC TX
493991 224 1265-D30 OVERDOSE Go and see doctor TX
493991 224 1265-D30 NOTES Take after meal TX
Above is my data
I have to fetch the record_type from a lookup where I can have any of the record type, sometime USES, HOW TO USE, SIDE EFFECTS and sometimes some other set of record types
In my report I have to get these record typpes as field name dynamically whichever is available in that lookup and record values against them.
its a BI Publisher report.
please suggestif you have data in db then you can create xml with needed structure
and so you can create bip report
do you have errors or .... ? -
I am in Saudi and trying to download navigon middle east. Every time I try to buy the app it will show up, says waiting and disappears. How can I get around it and not get lost on these crazy roads?
I recently purchased a second hand new macbook air, although it was second hand to me the previous owner had never actually turned it on.
Something doesn't make sense here, though I'm not saying the previous owner is lying....
Time to send your serial # to iTS and let them see what's happening here.
iTunes Store Support
http://www.apple.com/emea/support/itunes/contact.html -
How can I get the "Open" and "Save As" dialog boxes to open at larger than their default size?
How can I get the "Open" and "Save As" dialog boxes to open at larger than their default size? I would like them to open at the size they were previously resized like they used to in previous operating systems. They currently open at a very small size and the first colum is only a few letters wide necessitating a resize practically every time one wants to use it. Any help would be appreciated.
hi Prasanth,
select werks matnr from ZVSCHDRUN into table it_plant.
sort it_plant by matnr werks.
select
vbeln
posnr
matnr
werks
erdat
kbmeng
vrkme
from vbap
into table it_vbap
for all entries in it_plant
where matnr = it_plant-matnr and
werks = it_plant-werks.
and again i have to write one more select query for vbup.
am i right?
Maybe you are looking for
-
I upgraded to the latest version of Mozilla Firefox and ever since then, every time I open Firefox it asks me if I want to allow Mozilla to make changes to my hard drive. I have to answer "Yes" or else it won't open Firefox. Then when I open my AOL W
-
App's will not go from itunes to ipod!
This is really frustrating me, and I hope someone can help. I recently got a new computer, and I decided that I wanted to put apps onto my itouch. So to do so i restored my ipod and synced my ipod to the new itunes. I downloaded apps from the store a
-
Running reports in background?
hi, is it possible to run reports in background? i'm trying to find a way where in i can run / submit a process/procedure/report then go back to it after its done. this will help me allow do some other things while waiting for a report to finish. has
-
About iCloud: 1. How much storage is provided? 2. Is a limited amount of storage free, then more must be subscribed to and paid for? 3. Do you store music and photos only, or also videos? 4. What about music and videos previously purchased on iTunes?
-
Hi, Anybody here with practical experience regarding transporting changes to org plan from a test to a productive client? What changes can be distributed/transported, what is the tool (ALE or report), what are the restrictions? - org units, EBP users