Jump to content

Java applet JButton - strange behaviour

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Fae

Fae

    Learning Programmer

  • Members
  • PipPipPip
  • 80 posts
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));
content.add(button1);

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

} //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!

~Fae

#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
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());
     buttonPanel.add(button1);
     buttonPanel.add(button2);
     getContentPane.add(buttonPanel);

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)

#3
Fae

Fae

    Learning Programmer

  • Members
  • PipPipPip
  • 80 posts
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! ^_^