2012-12-13 34 views
1

我使用setLocation(x,y)将组件放置在基于AWT的小程序中,但是当切换选项卡时,组件的位置会回到其默认布局。Applet组件在切换选项卡后转到默认布局

import java.applet.*; 
import java.awt.*; 

public class AppletEx extends Applet { 

    Label test; 

    public void init() { 

     test = new Label("test"); 
     add(test); 

    } 

    public void start() { 
    } 

    public void stop() { 
    } 

    public void destroy() { 
    } 

    public void paint() { 
     test.setLocation(10, 10); 
    } 

} 

回答

-1

如果你想使用绝对定位,你需要不使用布局管理器:

setLayout(null); 
test = new Label("test"); 
add(test); 
test.setLocation(10, 10); 
test.setSize(test.getPreferredSize()); 
1
import java.awt.BorderLayout; 
// it is the 3rd millennium, time to use Swing 
import javax.swing.*; 
import javax.swing.border.EmptyBorder; 

/** <applet code='AppletEx' width='120' height='50'></applet> */ 
public class AppletEx extends JApplet { 

    JLabel test; 

    public void init() { 
     test = new JLabel("test"); 
     // a border can be used for component padding 
     test.setBorder(new EmptyBorder(10,10,10,10)); 
     // default layout of Applet is FlowLayout, 
     // while JApplet is BorderLayout 
     add(test, BorderLayout.PAGE_START); 
    } 
} 

其他提示。

  • 不要尝试创建或更改paint()中的任何组件,它将导致循环。
  • 除非做自定义绘画,否则不要覆盖paint()
  • 请勿在AppletFrame等顶级容器中覆盖paint(),但可以将其添加到PanelJPanel之类的顶级容器中。
  • 使用布局(而不是一个null布局的该无义)。