下面显示的两个示例是相同的。两者都应该产生相同的结果,例如生成在JPanel上显示的图像的坐标。示例1完美地工作(打印图像的坐标),但是示例2返回坐标0。
我想知道为什么,因为在两个示例中,我在添加面板之后都放入了setvisible (true)。唯一的区别是示例1使用extends JPanel,示例2使用extends JFrame
示例1:
    public class Grid extends JPanel{
       public static void main(String[] args){
          JFrame jf=new JFrame();
          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
          final Grid grid = new Grid();
          jf.add(grid);
          jf.pack();
          Component[] components = grid.getComponents();        
          for (Component component : components) {
           System.out.println("Coordinate: "+ component.getBounds());       
          }   
          jf.setVisible(true);        
        }
    }示例2:
public class Grid extends JFrame {
  public Grid () {
    setLayout(new GridBagLayout());
    GridBagLayout m = new GridBagLayout();
    Container c = getContentPane();
    c.setLayout (m);
    GridBagConstraints con = new GridBagConstraints();
    //construct the JPanel
    pDraw = new JPanel();
    ...
    m.setConstraints(pDraw, con);
    pDraw.add (new GetCoordinate ()); // call new class to generate the coordinate
    c.add(pDraw);
    pack();
    setVisible(true);
    }
    public static void main(String[] args) {
       new Grid();
    }
   }发布于 2010-03-09 10:07:12
此类异常的常见原因是无法在EDT上启动。在这种情况下,我不能从您的代码中看出有什么不同:尤其是,不清楚第二个示例的打印位置。
发布于 2017-07-15 00:31:31
持续时间
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author LENOVO G40
 */
public class Main {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new FrmMenuUTama().setVisible(true);
    }
}https://stackoverflow.com/questions/2406147
复制相似问题