문제

아래에 표시된 두 가지 예는 동일합니다. 둘 다 동일한 결과를 생성해야합니다. 예를 들어 JPANEL에 표시된 이미지의 좌표가 생성됩니다. 예 1에서는 완벽하게 작동하지만 (이미지의 좌표를 인쇄), 예 2는 좌표에 대해 0을 반환합니다.

두 예에서 패널을 추가 한 후 SetVisible (True)을 넣었 기 때문에 왜 궁금합니다. 유일한 차이점은 사용 된 예제 1입니다 extends JPanel 및 예 2 extends JFrame

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

EXAMPLE 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();
    }
   }
도움이 되었습니까?

해결책

문제는 두 번째 예에서 구성 요소가 컨테이너에 추가되기 전에 구성 요소의 한계를 인쇄하려고한다는 것입니다 ( add()) 그리고 프레임의 내용이 배치되기 전에 (전화로 pack()).

예제 1을 재현하려는 나의 시도는 다음과 같습니다.

다음은 예제 2를 재현하려는 시도입니다. SwingUtilities 올바른 스레드에 물건을 넣으려고 전화를 걸어 GetCoordiates 귀하의 의견에 도움이되는 생성자 :

class GetCoordinate extends JLabel {
    public GetCoordinate() {
        setText("Foo!");
        System.out.println("Coordinate: " + this.getBounds());
    }
}

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
        final 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) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Grid();
            }
        });
    }
}

설명한 것처럼 0의 크기를 인쇄합니다.

좌표 : java.awt.rectangle [x = 0, y = 0, 너비 = 0, 높이 = 0

그러나 구성 요소가 추가되고 프레임이 포장 된 후 크기를 인쇄하면 작동해야합니다. 다음은 내 예제 2의 수정 된 버전입니다. 여기서 메소드를 추가했습니다. GetCoordinate.printBounds() 그리고 그 방법을 부르고 모든 것이 추가되고 배치되었습니다.

class GetCoordinate extends JLabel {
    public GetCoordinate() {
        setText("Foo!");
        // Let's not try to do this here anymore...
//        System.out.println("Coordinate: " + this.getBounds());
    }

    public void printBounds() // <-- Added this method
    {
        System.out.println("Coordinate: " + this.getBounds());
    }
}

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
        final JPanel pDraw = new JPanel();
        m.setConstraints(pDraw, con);
        final GetCoordinate content = new GetCoordinate();
        pDraw.add(content);
        c.add(pDraw);

        pack();
        setVisible(true);
        content.printBounds();  // <-- Added this
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Grid();
            }
        });
    }
}

이러한 변경 사항을 통해 내 컨텐츠의 0이 아닌 크기를 포함하여 다음과 같은 콘솔 출력을 얻습니다.

좌표 : java.awt.rectangle [x = 5, y = 5, 너비 = 23, 높이 = 16

다른 팁

그러한 변칙의 일반적인 원인은 edt. 이 경우 코드에서 다른 점을 알 수 없습니다. 특히 두 번째 예제가 어디에 있는지 명확하지 않습니다.

Contoh

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);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top