Java AWT application window padding

I'm trying to build a simple AWT application in Java. I want all of the containers in the main window to be separated by bit. I can accomplish this by setting the Hgap and Vgap in the BorderLayout constructor (see below.)

However, I can't figure out how to put a cap between the containers and the edges of the main window. How do I add a few pixels of padding to the main window?

import java.awt.*; import java.applet.Applet; public class LayoutTest extends Applet { public void init() { BorderLayout layout = new BorderLayout(8, 8); setLayout(layout); add(new Button("Left"), BorderLayout.CENTER); add(new Button("Right"), BorderLayout.EAST); } }

Answer1:

I agree with the other answers and would recommend using Swing (use JApplet instead), which would make all kinds of things easier (you could just call setBorder and use BorderFactory to create a border, for example), but in your case you can set insets by overriding getInsets:

@Override public Insets getInsets() { return new Insets(10,10,10,10); }

Replace 10 with whatever you like.

There doesn't appear to be a setter, or I would say to use that instead. If there is a better way to do this in the case of an AWT Applet, someone please correct me.

If you decide to use Swing, see: How to Use Borders

Answer2:

AWT is not the newest technology on the block. So unless you have a specific requirement to do work in AWT, I would recommend you to check out the modern replacements Swing or SWT - much more comfortable, flexible customizable and predictable in their behaviour than AWT.

One reason behind developing them was exactly that the kind of visual fine-tuning you are trying to do here is unnecessarily difficult (if not impossible) with AWT.

Answer3:

Whilst you could probably get away with setting the insets of the applet, I suggest moving to Swing (extend javax.swing.JApplet). Then set a JPanel as the content pane with a EmptyBorder set of the appropriate widths.

Also note, you will probably quickly have to move up to a more sophisticated layout manager, such as GridBagLayout.

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Java AWT application window padding