Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Topics

Recent Status Updates

View All Updates

- - - - -

Java applet JButton - strange behaviour

jbutton setpreferredsize

  • Please log in to reply
2 replies to this topic

#1 Fae


    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 77 posts

Posted 11 August 2010 - 08:00 AM

Hi all, newbie here :) I hope y'all can help me with this, and I'll be glad to offer what help I can in return.

I've started my first venture into using Java to create an Applet, it's going to be a simple web-based tutorial set with a back and forward button, text and pictures intended to help people who are struggling with using certain basic programs.

I'm currently testing how everything works before I assemble it into a full-fledged program, but I'm having horrible trouble with the JButtons. Here is the code I have so far.

import java.awt.*;
import javax.swing.*;

public class tp extends JApplet {

Container content;

public void init () {

content = getContentPane();

JButton button1 = new JButton("Test 1");
button1.setPreferredSize(new Dimension(50,50));

JButton button2 = new JButton("Test 2");
button2.setPreferredSize(new Dimension(50,50));

} //end init

} //end class tp

Now, when I run this in a HTML page, I get one of two results; this in IE:
Posted Image

And this in FireFox:
Posted Image

...note, that the smaller button in the firefox picture is invisible until you clickon where it is, then it shows until the mouse pointer leaves the area.

I'm only running the applet as a 100x100 window in this example, however, whichever is the 'dominant' button takes up the entire applet space, regardless of how I try to size it. I've trawled the internet for hours looking for someone with a similar problem but alas, have found none, so I thought I'd ask for some help :)

Please and thank you!

  • 0

#2 Sinipull


    CC Addict

  • Validating
  • PipPipPipPipPip
  • 384 posts

Posted 11 August 2010 - 12:35 PM

You need to use panels and layout styles. Right now you have no definition how the buttons should be displayed, so no wonder they look like this.

for example:
     JPanel buttonPanel = new JPanel(new FlowLayout());

I've learned, that nicest layouts can be created using a mix of GridLayout and FlowLayout.
More about layouts: A Visual Guide to Layout Managers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Laying Out Components Within a Container)
  • -1

#3 Fae


    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 77 posts

Posted 12 August 2010 - 04:25 AM

hehe, so total newbie mistake then? :) Heh... I thought I could just do it all in one large container for simplicity.

But still, that's brilliant.Thanks for the help, Sinipull! ^_^
  • 0

Also tagged with one or more of these keywords: jbutton, setpreferredsize

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download