2012-12-13 79 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佈局的該無義)。