在這個程序中創建一個多邊形,以顯示在JPanel
選項卡中。創建並覆蓋適合JPanel的形狀?
爲了讓它表現出來,我必須重載形狀併爲它創建一個setter方法。不幸的是,它沒有顯示,程序也沒有運行。
錯誤:
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'註釋來防止這種情況發生,如果你認爲你的東西沒有被覆蓋,但實際上沒有。 – 2013-04-20 15:54:42
@GuillaumePolet你可以添加這個答案嗎? – Reimeus 2013-04-20 15:56:30
'SelectShape'類擴展了'JFrame',從這個意義上說,你試圖向'JPanel'添加一個'JFrame',而不是相反,這是造成異常的原因。 – 2013-04-20 15:58:39