이 프로그램에서는 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);
}
}
'JFrame'이 JComponent''확장하지 않고, 'paintComponent' 메소드를 가지고 있지 않습니다. 1)'Jpanel'을 확장하여'Jframe'의 내용 창으로 설정하십시오. 2)'JPanel'에서'paintComponent'를 오버라이드합니다. 3) 오버 라이딩을한다고 생각하지만 실제로 그렇게하지 않은 상황을 막기 위해 @ @ Override라는 주석을 사용하십시오. –
@GuillaumePolet 답변으로 추가 할 수 있습니까? – Reimeus
'SelectShape' 클래스는'JFrame'을'JFrame'을'JPanel'에'JFrame'을 추가하려고합니다. 그 반대의 경우는 예외입니다. –