Java AWT application window padding

≡放荡痞女 提交于 2020-01-04 09:21:29

问题


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);
    }
}

回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2089098/java-awt-application-window-padding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!