Simple JPanel problem

In the below code I try to make a JPanel thats 300 * 300 pixels big where I can draw some shapes. Just to test the program so far I tryed adding a red line. When I run the program (compile is ok) I only get a small rectangular area with a white background but without the red line, the area that supposed to be the JPanel is way too small. What am I doing wrong ?
import javax.swing.*;
import java.awt.*;
class test extends JFrame
     public Sheet sheet = new Sheet();
     public static void main(String[] arg)
          new test();     
     public test()
          Toolkit kit = getToolkit();
          Dimension screen = kit.getScreenSize();
          setBounds(screen.width/3, screen.height/3, 400, 400);
          getContentPane().setLayout(new BorderLayout());
          JPanel main = new JPanel();     
          getContentPane().add(main, BorderLayout.CENTER);
          main.add (sheet);
          setVisible (true);          
     public class Sheet extends JPanel
          public Sheet ()
               setSize(300,300);
               setBackground(Color.white);
               setVisible (true);     
          public void paintComponent(Graphics g)
               super.paintComponent(g);
               g.setColor(Color.red);     
               g.drawLine(1,1,300,300);
}

Of course not.
As a default, a JPanel has a FlowLayout. In a flow layout, all components are added left to right, top to bottom in the center of the container. The flow layout ignores your size settings as well. As of these facts, a FlowLayout mostly isn't very useful.
A BorderLayout stretches out your panel (when you add it to the center). The JPanel (LayoutManager) constructor takes a layout manager (such as BorderLayout), that's why I created main that way.
When you want to have your panel exactly some size you can try BoxLayout, null or GridBagLayout.
I hope this information will help you on your way.
Greetings,
Levi

Similar Messages

  • Real simple xslt problem/question

    Hi, i have a real simple xslt problem but i just cant figure out how to do it by looking at various examples on the net. i have a xml document and in it are some elements with a "result" tag name. i want to use xslt to reproduce exactly the same xml document except with an attribute called "id" added to those elements with a "result" tag name. i'm sure that theres a simple solution to it but i just cant figure it out. any helps greatly appreciated, thanks

    Start with the XSLT identity transform (I don't have it handy and it's fairly long, but you should be able to google it up). Add this:<xsl:template match="result">
      <result id="">
        <xsl:apply-templates>
      </result>
    </xsl:template>

  • JDeveloper IDE simple setting problem

    Hi,
    Recently we switched to JDeveloper from Visual Cafe .I have a simple setting problem.How can I set the options so that IDE gives, the core java classes and packages,and our application classes and packeges, prompts in imports as well as in code.Where to set the options.
    eg: when I write
    import java. it should prompt all the pakages.
    Thanks in advance.
    -Gopal
    null

    I am not sure I understand what you are requesting, but ...
    You can configure JDeveloper projects to include various libraries by default.
    This is done by selecting menu Tools | Default Project Properties.../ Libraries tab.
    You should define a library for your classes.
    You can import any of the packages / classes from all the libraries which your project includes.
    It would be incorrect for a tool to automatically add a bunch of import lines at the top of every file because each file should import what it needs and just as importantly, not import what it does not need depending on the component type (e.g. a servlet should not include javax.swing.* ).
    An easy way to import elements into JDeveloper is to type in something like:
    import java.
    // and then type in Ctrl Space
    and this launches the package browser, you can select packages or classes to import.
    You can also do this at the variable declaratiton point such as typing in:
    foo() {
    Frame x
    // Press Control Alt Space
    and this will correctly change the type (Frame) to the type you select in the package browser and add the import statement.
    -John
    null

  • Simple OOP Problem. Help!

    This is just a simple OOP problem that i cant decide on a best
    implementation for.
    im passing an object to an instance of, 'TabbedFrame', which is just
    a frame with a Tabbed Pane in it that is holding custom panels.
    however, these custom panels need access to the object being
    passed to 'TabbedFrame' and to some methods in it.
    i cant make them static however so how do i gain access to them?
    is my only option to pass the 'TabbedFrame' to each panel?
    like - jtabbedpane.add( "Panel 1", new mypanel1(this));
    here is code:
    new TabbedFrame( DataObject );
    public class TabbedFrame{
    public TabbedFrame(DataObject do){
    this.do = do;
    jtabbedpane.add( "Panel 1", new mypanel1() );
    DataObject do;
    public class mypanel1{
    public mypanel1(){
    // need access to DataObject of the 'TabbedFrame' object that instantiated
    // this 'mypanel1' and to some of its methods
    }i would just pass the DataObject to evey panel (there are 12) but
    i also need to be able to call methods in the 'TabbedFrame'.
    Any help would be appreciated!

    Modify mypanel1's constructor:
    public class mypanel1{
    TabbedFrame tf;
    public mypanel1(TabbedFrame tf){
    this.tf = tf;
    // need access to DataObject of the 'TabbedFrame' object that instantiated
    // this 'mypanel1' and to some of its methods
    DataObject theDo = tf.getDataObject();
    tf.someMethod(); // Call method on the TabbedFrame
    }In TabbedFrame:
    public TabbedFrame(DataObject do){
    this.do = do;
    // Modify call to constructor to pass "this" TabbedFrame.
    jtabbedpane.add( "Panel 1", new mypanel1(this) );
    }

  • Simple button problem

    I am having a real problem creating a simple button - I have
    created a Flash file using Action script 2, and when I create a
    simple button - text with a rectangle as a background, (see
    http://www.elkhavenestate.com),
    and the over state is behaving in a bizarre fashion. This is my
    first time using CS3, so is there a new control that I'm
    missing?

    I take it that it's the Home button. It appears to have a
    selectable text field or something in it, which is causing the
    problem. Either change that to a static text field or set its
    selectable property to false. The other two buttons appear to be
    fine, so maybe you can just duplicate one of them and turn it into
    the Home button.
    If I picked the wrong button, let me know.

  • Logo/picture to menubar? simple css problem?

    Hi, I'm having a problem getting a logo to appear correctly in a horizontal menu bar. It appears to be fine in IE 8, Safari 5, Chrome, and Firefox. However in IE 7 and lower it does not seem to display correctly. The only conditional notes I have for IE 7 and lower deals with the slideshow on the page which shouldn't be affecting the menubar as it is in a different div.
    Here is the url: www.elementcentral.com
    Any advice? I could really use some help- I've tried quite a few things but to no avail...
    Thanks for any help you can offer and I'm more than happy to clarify or anything else!
    Sincerely,
    Matt

    Anyone? I'm thinking its just something simple but I can't figure it out for the life of me heh.

  • Jsp and JPanel problem

    Hello. I've been to this forum many times, but have always been a bit gunshy about posting anything of my own. Now I have a problem I haven't seen before, so here goes. I have a JPanel in a java program that has all sorts of other componants added to it. I am trying to display the whole thing in a jsp page. This is what I am doing in the java file to return the image ("display" is the JPanel):
    public byte[] getImage(){
        int w = display.getWidth();
        int h = display.getHeight();
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        display.paint(img.createGraphics());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(img, "jpeg", os);
        return os.toByteArray();
    }and then in the jsp page I say:
    <%@ page contentType="image/jpeg" %>
    <%@ page import="myPackage.MyClass" %>
    <%
         MyClass picture = new MyClass();
         byte[] b = picture.getImage();
         OutputStream os;
         os = response.getOutputStream();
         os.write(b);
         os.flush();
    %>And the problem is that the page is displaying a blank JPanel and none of the componants that were added to it. If I save the the JPanel as a jpeg in the java program, though, it does contain all the componants, so I am not sure what I am doing wrong here. If there is some way to get the all the JPanel componants returned, that would be great to know. Thanks for any help.

    nope, that didn't work.
    Maybe I am going about solving the problem all wrong. The JPanel and its componants are kind of like a template. When a user of the system submits their information it automatically puts the data into the template and displays it on screen as a jpg. It works when I save the jpg as a file from the java program but not when i send the byte array to the jsp server. It just shows the blank panel....
    Is there a better way to go about doing this?

  • Paint JPanel problem

    Hi All
    I have 2 classes
    class1. has a Jframe with a JPanel.
    class1 2. A Has a JPanel called contact
    I am calling class2 from class1.
    It is placing the the contact Panel onto the JPanel in class1 but does not show. If I resize class1 it the shows that it is there.
    I have tried repaint(); with out any luck
    any other help would be helpfull
    Thanks
    Craig

    Ok Here you go
    I have class1 witch is my main frame called Command class
    I have a menu class that has a jTree on it called Menu_Panel
    Then I have a class called DataClient which is the panel that I am have Problems with.
    Here is the Code
    This is the jbInit in the Command Class.
        mainPanel.setLayout(borderLayout3);
        mainPanel.setLayout(borderLayout4);
        topPanel = new Panel_Top();
        mainPanel.add(topPanel, BorderLayout.NORTH);
        menuPanel = new Menu_Panel();
        dataPanel = new DataPanel();
        setMenuItems();
        contentPane = (JPanel)this.getContentPane();
        contentPane.setLayout(borderLayout1);
        this.setSize(new Dimension(900, 600));
        this.setTitle("Frame Title");
        jMenuFile.add(jMenuFileExit);
        jMenuHelp.add(jMenuHelpAbout);
        jMenuBar1.add(jMenuFile);
        jMenuBar1.add(jMenuHelp);
        contentPane.add(mainPanel, BorderLayout.CENTER);
        mainPanel.add(menuPanel, BorderLayout.WEST);
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(dataPanel, BorderLayout.CENTER);
        mainPanel.revalidate();
        this.setJMenuBar(jMenuBar1);
        fontResize();
        menuPanel.setDataPanel(dataPanel);   // This is where the Menu_Panel calls the show of DataPanel This is from the Menu_Panel at which point fires the menuPanel.setDataPanel(dataPanel); in the Command Class.
    /** Required by TreeSelectionListener interface. */
      public void valueChanged(TreeSelectionEvent e) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
            tree.getLastSelectedPathComponent();
        if (node != null) {
          fromMenu = tree.getLastSelectedPathComponent().toString();
          checkMenuNames ();
    public void checkMenuNames (){
      if(fromMenu.equals("Client")){
              dataPanel.showClient();
    }This is the DataPanel Class
    public class DataPanel
        extends JPanel {
      private DataClient dataClient;
      public void showClient() {
        //  dClient = new Data_Client();
    if (dataClient == null){
      System.out.println("This worked");
    dataClient = new DataClient();
    this.add(dataClient);
    }and this is the DataClient class
    public class DataClient  extends JPanel{
      XYLayout xYLayout1 = new XYLayout();
      JLabel jLabel1 = new JLabel();
      public DataClient() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        jLabel1.setText("This is Client");
        this.setLayout(xYLayout1);
        this.add(jLabel1,    new XYConstraints(110, 95, 179, -1));
    }Hope you can help me :)
    Craig

  • Printing jpanel problem

    So I am trying to print a JPanel. When I print to a pdf after bringing up a page setup dialog and a print dialog, either one of two things is happening.
    1) all drawn lines are shifted down and to the right.
    or
    2) all text is shifted up and to the left.
    Everything on the screen of the program looks great. I think it might have something to do with the fact that I am deriving fonts by scaling them. This would not be a problem if everything was shifting. It is clear that when rendered to a pdf it is handling the text of the fonts that I am using somehow differently than all the lines I am drawing. I do not understand why this is happening. Everything looks so good on the screen.
    If anybody knows what this problem is, your help would be much appreciated.
    Thanks in advance!

    Oh... it's just a mistake because of copy and paste.
    I did also have these code (without if (pageIndex > 0) {
    return(NO_SUCH_PAGE); ) but with these
    /* calculate the no. of pages to print */
    int totalNumPages = (int)Math.ceil((panelHeight) /
    height );
    if (pageIndex >= totalNumPages) return NO_SUCH_PAGE;
    and when I use :
    System.out.println("totalNumPages: " + String.valueOf(totalNumPages));
    I can see at there are two pages. But when it prints it can only print one. So...

  • Simple DLL problem

    I'm dabbling with DLL writing and can't figure out how to pass a string to a
    DLL. As far as I can see, it should be simple.
    My DLL function, in the DLL "test.dll", is simply
    TEST_API int test(LPCTSTR WinName)
    return 0;
    Instead of LPCTSTR I've also tried the more conventional "char *WinName",
    and a few others. All give the same error; "The exception Priviledged
    Instruction occurred in the application at location (blah)." The error
    message doesn't seem too specific; exactly the same thing happens if I
    deliberately copy some text to an uninitialised pointer.
    I'm calling the function using a "Call Library Node", passing a
    pre-generated string in the form of a C string pointer. The calling
    convention is set to "winapi" but doesn't seem too relevant.
    If I remove the string argument and change the function definition to take
    (void) then it works, in that I can put integers in the return code and pass
    them back to Labview, so it's the passing of the string that's the problem.
    However, if I have more code in there and I use the Visual C++ debugger, the
    error message is only generated on hitting the "return" line, and I can see
    the string that has been passed in when I look at "WinName" in the debugger.
    Can anyone shed some light on this?
    Craig Graham
    Physicist/Labview Programmer
    Lancaster University, UK

    Craig;
    I am going to throw some random thoughts that may help you in your situation:
    - I avoid to use VC's wizard. It gives (and gave me) a lot of headaches. All it does it to add a lot of garbage to your project that nobody understand.
    - If your source file is a .cpp, wrap your function prototypes inside the extern "C" declaration.
    - Always initialize every variable in LabVIEW side. For example, for your function you should wire an empty string in the input side of the "Call Library Node" for the "WinName" variable.
    - I claim ignorance in this one, but seems to simplify my projects. Exclude rarely-used Windows header files by adding the following statement before your headers "include":
    #define VC_EXTRALEAN
    I hope this can be of help. If I co
    me up with some more suggestion, I'll let you know.
    Best regards;
    Enrique
    www.vartortech.com

  • Another simple classpath problem question

    Hi All
    Yes I know, there are a lots of questions about this matter, but I couldn't found a solution to my problem.
    I have a simple program:
    public class prueba {
            public static void main(String[] args) {
                    System.out.println("Ahi va...");
    }placed in /tmp/javier/prueba.java
    After compiled, I've tried to run it from / and then problems started:
    cd /
    java /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    I said, ok...it could be a classpath problem...then:
    java -cp /tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba
    Damn, another try...
    java -cp .:/tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Jesus Christ....may be the last slash....
    java -cp .:/tmp/javier /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Oh...no.... may be classpath to java classes..
    java -cp .:/usr/java/j2sdk1.4.2_01/lib/jre/:/tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Well, I don't know why this error happens....
    Please, could somebody help me !!!
    Thanks in advance...
    <jl>

    It's not too early to start following the Sun coding
    conventions for Java:
    http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.
    tmlHi
    thanks for your reply.
    Yes, I agree. I use conventions with my programs. But my real problem was with a real application and then I did quickly this simple code to help others to understand the problem and give a fast reply...
    Let me know if that works. (It was fine on my
    machine.) - MODYes it works fine, thanks.... and Damn...Murphys law again, the only option I didn't tried is the solution to my problem... :)
    Thanks again...

  • Urgent- Printing JPanel problem

    I want to print a JPanel by calling a Print utility class. JPanel is drawing with different shapes (Rectangle2D etc..)
    The problem is that I can only print the first page of the JPanel.
    My Print utility:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    public class PrintUtilities {
    private Component componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    BookComponentPrintable printable1 = new BookComponentPrintable(componentToBePrinted);
    PageFormat pageFormat1 = printJob.pageDialog(printJob.defaultPage());
    Book book = new Book();
    book.append(printable1, pageFormat1);
    // Print the Book.
    printJob.setPageable(book);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    class BookComponentPrintable
    implements Printable {
    private Component mComponent;
    public BookComponentPrintable(Component c) {
    mComponent = c;
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    else
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    mComponent.paint(g2);
    return Printable.PAGE_EXISTS;
    What did I do wrong? Thanks in advance !!!

    Oh... it's just a mistake because of copy and paste.
    I did also have these code (without if (pageIndex > 0) {
    return(NO_SUCH_PAGE); ) but with these
    /* calculate the no. of pages to print */
    int totalNumPages = (int)Math.ceil((panelHeight) /
    height );
    if (pageIndex >= totalNumPages) return NO_SUCH_PAGE;
    and when I use :
    System.out.println("totalNumPages: " + String.valueOf(totalNumPages));
    I can see at there are two pages. But when it prints it can only print one. So...

  • Help!!! Please!!! jPanel problem.....

    Hi,
    I have MainFrame that contains jPanel1. ANd jPanel1 contains jPanel2, jPanel3, jPanel4.
    My problem is with jPanel2. jPanel2 contains jScrollPane.
    Let me just give tell you what i am doing.
    I wrote something which gets the image from database & displays the Multipage Tiff IMages in
    jScrollPane which is in jPanel2. I also have something which zooms the image from 10% to 120%.
    When i zoom the image to 30% the image is shown with only Vertical Scroll Bars. The image looks fine
    the first time its loaded. But when i move the vertical scroll bar the outside the image portion is shown
    with white and gray small areas each time i move the scroll bar.
    But when i zoom the image to 50% the image is shown with both scroll bars. SO when i scroll down or sideways
    I have no problem.
    Its only when i have vertical scroll bars.
    I have done repaint and validate on jPanel2 & jScrollPane but noting was solved.
    Any help or suggestions are always appreciated.
    Thanks in advance.

    Make sure you are calling invalidate() and validate() prior to the repaint. And since you are using a JPanel, try calling revalidate() as well. When ever I run into paint problems I just use trial an error on those 3 calls along with repaint() untill I find a combination that works. I really should spend 5 minutes figuring out which order to make these calls in and when but I have yet to do that :-(
    Bryan

  • Simple Form Problem: Cant press Enter in form without getting error message: Invalid Input

    The problem is very simple,
    I have several forms on my site such as the 'quick enquiry'
    form on the home page about half way down.
    http://www.party-invitation.co.uk/index.htm
    The user enters name- Works Fine
    user enters email address- Works Fine
    User enters a question- This is were the problem occurs when
    the users presses the Enter key. This seems to bring up a message
    that says Invalid Input.
    Does anyone know how i can allow people to use the Enter key
    in my forms to skip lines without causing this error message?
    Any help would be appreciated.
    Feel free to use the form to test it out.
    Thanks.
    Here is my php code for the form.
    <?
    function checkOK($field)
    if (eregi("\r",$field) || eregi("\n",$field)){
    die("Invalid Input!");
    $Name=$_POST['Name'];
    checkOK($Name);
    $Email=$_POST['Email'];
    checkOK($Email);
    $Question=$_POST['Question'];
    checkOK($Question);
    $to="[email protected]";
    $message="
    A Quick Enquiry has been submitted from
    www.Party-Invitation.co.uk
    Here are the details:
    Name: $Name
    Email: $Email
    Question: $Question
    if(mail($to,"Quick Enquiry: $Email $Name" ,$message,"From:
    $email\n")) {
    echo "";
    } else {
    echo; "There was a problem sending the mail. Please check
    that you filled in the form correctly.";
    ?>

    .oO(stuckinthesystem)
    > Here is my php code for the form.
    > <?
    This should be <?php for portability reasons. Short open
    tags are an
    optional feature and can be disabled.
    > function checkOK($field)
    > {
    > if (eregi("\r",$field) || eregi("\n",$field)){
    The old ereg_* functions should not be used anymore. Better
    would be
    something like
    if (preg_match("/[\n\r]/", $field)) {...}
    > $Name=$_POST['Name'];
    > checkOK($Name);
    > $Email=$_POST['Email'];
    > checkOK($Email);
    > $Question=$_POST['Question'];
    > checkOK($Question);
    The last check causes the error if the user enters multiple
    lines in the
    text area. You can remove that check, because line breaks in
    the email
    body are safe.
    > if(mail($to,"Quick Enquiry: $Email $Name"
    ,$message,"From: $email\n")) {
    > echo "";
    There's a typo in the last parameter. Variable names in PHP
    are
    case-sensitive, so $Email != $email. You should set
    error_reporting to
    E_ALL in your php.ini, so PHP will let you know about such
    errors.
    Micha

  • SIMPLE ILLUSTRATOR PROBLEM..HELP PLEASEEE

    INTRO
    hey so i am designing a logo for my uni course, and its due quite soon and i need help on a very simple thing.
    OVERVIEW
    I've drawn a picture using the line tool, all the lines are connected creating various shapes...
    PROBLEM
    i need to know how to fill them with colour.... i can slect the shapes i want to fill and use object-live paint-make. but tht means i can only fill...i need to be able to use the mesh tool to create effects....
    any help would be greatly appreciated. Thanks

    Problem is when you use the line tool, where two lines intersect, they stay as seperate entities. In other words the line tool was design to just create a line. However if you want to take the time you can use the point selection tool (lowercase a on keyboard) Drag select the corner where they intersect, right click and select join (windows) (also object>path>join or ctrl-j will work), select the type of corner you want, then hit ok. And repeat for each corner.
    When you are done you can give it a fill or a path color and size.
    Or create a new layer, (Optional: change the color of the path to make it easier to see what you are doing)
    lock the old layer,
    select the pen tool and click on top of each corner (point or anchor).
    When you reach the last point the cursor will change to tell you that you are closing the path.
    At this point you can change the fill and path color/size.

Maybe you are looking for

  • Does iPhone do Video Out via video cables?

    I can't find any reference to this in the iPhone user guide, so I'm guessing it can't, but I thought I'd ask here. Can iPhone send video out to an external TV using the iPod Video Connection Cable?

  • Jsp classpath

    hello every one, i have designed a project in the JSP with some Javabeans classes, what when ever i m started my indexfile in which i m using some of my beans files. the error is coming that beans class is not found i.e is the beans is not instantiat

  • My illustrator CS won't open

    I have the first version, CS and am working on an older MacBook; it was working up until yesterday, and I have a big project to finish.

  • Playing files over a network - choppy & stuttering playback

    I have all my movies on a Maxtor external hard drive connected to my iMac. This is shared out over AFP so my powerbook can see all the files. I can play mp3s no problem, but if I play any AVI files in Quicktime, the playback is extremely choppy. When

  • IPhoto suggestion for Apple

    I hate one thing about iPhoto!! I hate the photo organization via Rolls restrictions. I wish Apple would change something. TWO ideas: Idea #1. make it so we can click "organize photo library by finder style interface". Then we get a photo library wit