2013-04-20 1 views
2

이 프로그램에서는 JPanel 탭에 표시되는 다각형이 생성됩니다.JPanel에 맞게 모양 만들기 및 재정의?

순서대로 표시하려면 모양을 오버라이드하고 설정 메서드를 만들어야했습니다. 불행히도 프로그램이 실행되고 있지 않습니다.

오류 : 작동 할

Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
  at SelectShape component1 = new SelectShape(x, y, vert); in method Page1.

유일한 방법은 프레임을 제작하고 JTab를 제거하고 프레임 위에 모양을 지정하는 것입니다하지만 내가 만들고 싶어 것이 아니다. 하나의 그래픽 방식을 사용하여 다른 탭 *에 도형을 배포 할 수있는 프로그램을 만들고 싶습니다.

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


/* This program create a graphics component that draws a polygon 
*/ 
public class SelectShape extends JFrame 
{ 
    private JTabbedPane tabbedPane; 
    private JPanel panel1; 

    // ////////////////////////// 

    static int[] x = { 20, 40, 50, 65, 80, 95 }; // Co-ords for a polygon 
    static int[] y = { 60, 105, 105, 110, 95, 95 }; 
    static int vert = 6; 

    public SelectShape() throws IOException // Builds GUI 
    { 
     setTitle("Program"); 
     setSize(900, 600); 
     setBackground(Color.gray); 

     JPanel topPanel = new JPanel(); 
     topPanel.setLayout(new BorderLayout()); 
     getContentPane().add(topPanel); 

     // Create the tab pages 
     createPage1(); 

     // Create a tabbed pane 
     tabbedPane = new JTabbedPane(); 
     tabbedPane.addTab("Shape Panel", panel1); 
    } 

    public void createPage1() throws IOException // Creates JPanel 
    { 
     panel1 = new JPanel(); 
     panel1.setLayout(null); 

     SelectShape component1 = new SelectShape(x, y, vert); //error 
     SelectShape component2 = new SelectShape(x, y, vert); //over-rides shape 

     component1.setBounds(290, 70, 120, 40); 
     component2.setBounds(290, 70, 120, 40); 

     panel1.add(component1); // is not displayed! 
     panel1.add(component2); // component2 overwrites component1!!! 
     panel1.setVisible(true); 

    } 

    // overrides javax.swing.JComponent.paintComponent 
    public void paintComponent(Graphics g) { 
     // Recover Graphics2D 
     Graphics2D g2 = (Graphics2D) g; 

     // Construct a polygon then draw it 
     Polygon polygon = new Polygon(x, y, vert); 
     g2.draw(polygon); 
     g2.fill(polygon); 
    } 

    public SelectShape(int[] x, int y[], int vert) { // setter method 
     this.x = x; 
     this.y = y; 
     this.vert = vert; 
    } 

    public static void main(String[] args) throws IOException { 

     SelectShape mainFrame = new SelectShape(); //Frame 
     mainFrame.setVisible(true); 

    } 
} 
+2

'JFrame'이 JComponent''확장하지 않고, 'paintComponent' 메소드를 가지고 있지 않습니다. 1)'Jpanel'을 확장하여'Jframe'의 내용 창으로 설정하십시오. 2)'JPanel'에서'paintComponent'를 오버라이드합니다. 3) 오버 라이딩을한다고 생각하지만 실제로 그렇게하지 않은 상황을 막기 위해 @ @ Override라는 주석을 사용하십시오. –

+4

@GuillaumePolet 답변으로 추가 할 수 있습니까? – Reimeus

+0

'SelectShape' 클래스는'JFrame'을'JFrame'을'JPanel'에'JFrame'을 추가하려고합니다. 그 반대의 경우는 예외입니다. –

답변

3

난 당신이 결국 ununderstandable 코드로 연결 코드에서 함께 많은 개념을 혼합 생각 : 여기

는 코드입니다.

  • JFrame하지 않습니다 JComponent을 확장하고 paintComponent 방법이 없습니다. 다른 것을 재정의하는 메소드에 @Override 주석을 사용하는 것을 고려하십시오. 이렇게하면 쉽게 실수 할 수 있습니다.
  • 최상위 컨테이너의 paint() 방법 오버라이드 (override) 결코 어쨌든 JFrame을 연장하지 않고 필요가 없습니다 (JDialog, JFrame를, ...)
  • 항상 paintXXX 방법
  • public SelectShape(int[] x, int y[], int vert) { // setter method
  • 의 슈퍼 메소드를 호출은 세터 방법이 아닙니다 . 이것은 3 개의 인수를 취하여 할당하는 생성자입니다. 모든 경우에있어서, 당신이 그러한 변수를 만들었 기 때문에 당신의 경우에는 전혀 아무것도하지 않습니다. static. 상수를 설명하는 경우가 아니면 static을 사용하지 마십시오.이 경우 뒤에 final 키워드가 와야합니다.
  • UI를 시작하고 EDT (Event Dispatching Thread)에서 UI 수정을 모두 수행하십시오. 이는 SwingUtilities.invokeLater()을 사용하여 쉽게 수행 할 수 있습니다.
  • 은 당신이보고있는 오류 : 스레드 "주요"java.lang.IllegalArgumentException가에 예외 : 당신이 JFrame 금지되어 있습니다 JComponent A를 추가하려고하기 때문에 컨테이너에 창을 추가 슬로우됩니다. JFrame을 (를) 추가 할 수 없습니다. 그렇게하고 싶다면 JDesktopPane을 사용하고 JInternalFrame을 추가해야합니다 (단, 이는 다른 이야기입니다).

내가 여기 당신이 달성하려고하는 무엇을 너무 잘 모르겠지만, 훨씬 더 잘 작동하는 당신에서 파생 된 작업 코드 :

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Polygon; 
import java.awt.Rectangle; 
import java.awt.Shape; 
import java.awt.geom.Ellipse2D; 
import java.io.IOException; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JTabbedPane; 
import javax.swing.SwingUtilities; 

/* This program create a graphics component that draws a polygon 
*/ 
public class SelectShape extends JPanel { 

    // Constants 
    private static final int[] x = { 20, 40, 50, 65, 80, 95 }; // Co-ords for a polygon 
    private static final int[] y = { 60, 105, 105, 110, 95, 95 }; 

    private static final Polygon POLYGON = new Polygon(x, y, Math.min(x.length, y.length)); 
    private static final Ellipse2D CIRCLE = new Ellipse2D.Double(100, 40, 45, 45); 

    // Class variables 
    private final Shape shape; 
    private Dimension preferredSize; 

    public SelectShape(Shape shape) { 
     this.shape = shape; 
     Rectangle bounds = shape.getBounds(); 
     this.preferredSize = new Dimension(bounds.x + bounds.width, bounds.y + bounds.height); 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return preferredSize; 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g; 
     g.setColor(Color.BLUE); 
     g2.draw(shape); 
     g2.fill(shape); 
    } 

    public static void main(String[] args) throws IOException { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       JFrame mainFrame = new JFrame("Program"); 
       mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       SelectShape polygon = new SelectShape(POLYGON); 
       SelectShape circle = new SelectShape(CIRCLE); 
       // Create a tabbed pane 
       JTabbedPane tabbedPane = new JTabbedPane(); 
       tabbedPane.addTab("Polygon", polygon); 
       tabbedPane.addTab("Circle", circle); 
       mainFrame.add(tabbedPane); 
       mainFrame.pack(); 
       mainFrame.setVisible(true); 
      } 
     }); 

    } 
} 
+1

그래서 명시적인 프레임을 사용하고 JFrame에 반대되는 JPanel로 확장해야한다고 가정합니다. 좋구나. 고맙습니다! 그리고 내 실수를 설명해 주셔서 감사합니다. – BDillan