2013-09-05 3 views
2

일부 숙제 때문에 저울을 나타내는 막 대형 차트를 만들어야합니다. 그래픽/구성 요소에 익숙해지기 위해 화면에 두 개의 상자를 배치하기 만하면됩니다. 첫 번째 상자가 '그려진'다음 두 번째 상자가 그냥 덮어 쓰는 것 같습니다? 다음 두 클래스가 있습니다.JFrame에서 동일한 클래스의 두 구성 요소 추가

메인 클래스 - BalanceChart.java

package balancechart; 

import javax.swing.*; 

public class BalanceChart { 

Double[] Props = new Double[6]; 

public static void main(String[] args) { 
    JFrame f = new JFrame("Balance Chart"); 
    f.setSize(500, 500); 
    f.setDefaultCloseOperation(
    JFrame.EXIT_ON_CLOSE); 
    ChartComponent ccOne = new ChartComponent(50, 50, 100, 200); 
    ChartComponent ccTwo = new ChartComponent(10, 10, 10, 10); 
    f.add(ccOne); 
    f.add(ccTwo); 
    f.setVisible(true); 
} 

private void getProps(){ 
    //ignore 
} 

} 

구성 요소 클래스 - ChartComponent.java

package balancechart; 

import javax.swing.*; 
import java.awt.*; 

public class ChartComponent 
extends JComponent { 

private int x, y, w, h; 

public ChartComponent(int x, int y, int w, int h){ 
    this.x = x; 
    this.y = y; 
    this.w = w; 
    this.h = h; 
} 

public void paintComponent(Graphics g){ 
    Graphics2D g2 = (Graphics2D) g.create(); 
    g2.setColor(Color.RED); 
    g2.fillRect(w, h, x, y); 
} 

} 

나는 내가 위해이 절차를 추가하려면이 함께 할 수있는 뭔가가 생각 JFrame, 나는 그것에 대해 어떻게 가야할지 모르겠다.

미리 감사드립니다.

답변

5

가장 가까운 레이아웃 관리자 자습서로 이동해야합니다. 여기서 JFrame의 contentPane은 기본적으로 BorderLayout을 사용하고 추가 상수없이 BorderLayout- 사용 컨테이너에 구성 요소를 추가하면 이전에 추가 된 항목을 모두 포함하여 BorderLayout.CENTER 위치에 기본적으로 추가된다는 것을 알 수 있습니다.

해결 방법은 선택한 레이아웃을 사용하는 다른 JPanel을 만드는 것입니다. JPanel의 기본 FlowLayout을 그대로두고 구성 요소를 추가 한 다음 JPanel을 JFrame에 추가하는 것만으로도됩니다. 즉

,

ChartComponent ccOne = new ChartComponent(50, 50, 100, 200); 
ChartComponent ccTwo = new ChartComponent(10, 10, 10, 10); 
JPanel container = new JPanel(); // JPanel uses FlowLayout by default 
container.add(ccOne); 
container.add(ccTwo); 
f.add(container, BorderLayout.CENTER); // just to be clear 
f.pack(); 
f.setVisible(true); 

이 튜토리얼 링크를 확인하시기 바랍니다 : Laying Out Components Within a Container


편집을
MadProgrammer가 지적 하듯이, 여기서 또 다른 문제했습니다 :

public void paintComponent(Graphics g){ 
    Graphics2D g2 = (Graphics2D) g.create(); 
    g2.setColor(Color.RED); 
    g2.fillRect(w, h, x, y); 
} 

당신이 슈퍼 메서드를 호출하지 않는다는 점에서, 그리고 필요하다면 오래된 이미지는 지워지지 않을 것입니다. 그리고 여러분이 w, h, x, 또는 y를 변경하여 어떤 애니메이션을하려고하면 크게 달라질 것입니다. 스윙 타이머. 이 문제를 해결하려면 super 메서드를 호출해야합니다. 또한 paintComponent는 protected이 아니고 public이어야하며 메소드를 올바르게 재정의하려면 @Override 주석을 사용해야합니다. 그리고 새로운 그래픽 콘텍스트를 절대적으로 만들어야한다면, 리소스가 부족하지 않도록 처리해야한다. JVM이 (가 제공 한 그래픽 문맥의 하지 폐기를 수행하는 원치 않는 부작용이있을 수있는 사람이 당신의 paintComponent(...) 메서드의 매개 변수로 전달과 같은 :

@Override 
protected void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    Graphics2D g2 = (Graphics2D) g.create(); 
    g2.setColor(Color.RED); 
    g2.fillRect(w, h, x, y); 
    g2.dispose(); // only do this if you create your own Graphics context 
} 

편집 2
을 또한 크기를 설정하지 않고 GUI 구성 요소와 레이아웃 관리자가 자신에게 맞는 크기로 설정하도록하는 습관을 가져야합니다. 이렇게하면 더 기쁘고 유연한 GUI 프로그램이 생길 수 있습니다.


편집 3
코멘트에서 당신의 상태 : 내가 코드를 고정하지만 난이 개 빨간색 사각형 어디서나 표시하고 창가에서 시작해야하지 않는 것

정말 작은 크기. 나는 아직도 많은 것을 배우기 때문에 추가 된 코드가 왜 이렇게되는지를 알 수 없다.

귀하의 문제는 귀하의 JComponent, ChartComponent의 기본 preferredSize가 0,0 또는 1,1; 나는 어느 것이 든, 구성 요소가 보이기에 충분하지 않을 것이기 때문에 어느 것이 중요하지만, 그것은 중요하지 않다는 것을 잊었다. 이 문제를 해결하려면 클래스의 크기를 설정하는 getPreferredSize() 메서드 재정의를 클래스에 제공하십시오. 예 :

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D;  
import javax.swing.*; 

public class BalanceChart { 

    Double[] Props = new Double[6]; 

    public static void main(String[] args) { 
     JFrame f = new JFrame("Balance Chart"); 
     // f.setSize(500, 500); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     ChartComponent ccOne = new ChartComponent(50, 50, 100, 200); 
     ChartComponent ccTwo = new ChartComponent(10, 10, 10, 10); 
     JPanel container = new JPanel(); 
     container.add(ccOne); 
     container.add(ccTwo); 
     f.add(container); 
     f.pack(); 
     f.setLocationByPlatform(true); 
     f.setVisible(true); 
    } 

    private void getProps() { 
     // ignore 
    } 

} 

class ChartComponent extends JComponent { 

    private static final int PREF_W = 400; 
    private static final int PREF_H = PREF_W; 
    private int x, y, w, h; 

    public ChartComponent(int x, int y, int w, int h) { 
     this.x = x; 
     this.y = y; 
     this.w = w; 
     this.h = h; 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(PREF_W, PREF_H); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g.create(); 
     g2.setColor(Color.RED); 
     g2.fillRect(w, h, x, y); 
     g2.dispose(); 
    } 

} 
+1

(super.paintComponent)) – MadProgrammer

+0

@MadProgrammer : thanks. –

+0

빠른 답장과 자습서에 대한 링크를 보내 주셔서 감사합니다. 코드를 수정했지만 두 개의 빨간색 사각형이 어디에도 나타나지 않고 창 크기가 매우 작아 보입니다. 나는 아직도 많은 것을 배우기 때문에 추가 된 코드가 왜 그렇게되었는지 알 수 없다. –

관련 문제