2017-05-12 31 views
0

最近,我遇見了的paintComponent功能沒有在函數調用的問題,我發現,當我使用splitpane功能,將禁用塗料的功能,並給出錯誤:如何在Java的揮杆分割面板漆

cannot add to layout: unknown constraint: null

我認爲這幅畫功能可能被添加到正確的方式,下面是我的代碼(部分):

類:測試

public class Test extends JFrame{ 

    public Test() throws IOException{ 
     //JFrame jf = new JFrame("my frame"); 
     this.add(new NewPanel(this)); 

     this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
     this.setBounds(300,200,1050,600); 
     this.setVisible (true); 

    } 

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

     Test test = new Test(); 
     test.setTitle("Hello"); 
      //frame.pack(); 
    } 
} 

類:NewPanel

public class NewPanel extends JPanel{ 
    public NewPanel(JFrame frame) throws IOException{ 
      JTabbedPane jTabbedpane = new JTabbedPane(); 
      JSplitPane splitPane = new JSplitPane(); 
      JPanel p1    = new JPanel(); 

      p1.setLayout(null); 
      p2.setLayout(new FlowLayout()); 

      splitPane.setOneTouchExpandable(true); 
      splitPane.setContinuousLayout(true); 
      //splitPane.setPreferredSize(new Dimension (250,500)); 
      splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); 
      splitPane.setLeftComponent(p1); 
      splitPane.setRightComponent (p2); 
      splitPane.setDividerSize(3); 
      splitPane.setDividerLocation(250); //balance two panels width 

      jTabbedpane.addTab("ABC",p2); 
      jTabbedpane.addTab("AB",p3); 
      jTabbedpane.addTab("AC",p4); 
      jTabbedpane.addTab("BC",p5); 

      frame.setContentPane(splitPane); 
      frame.add(jTabbedpane); 

      } 
    } 
    public void paintComponent(Graphics g){ 
     super.paint(g); 
     g.setColor(Color.BLUE); 
     g.drawLine(303, 90, 303, 200); 
     g.drawLine(583, 90, 583, 200); 
     g.drawLine(863, 90, 863, 200); 
    } 
} 

當我評論frame.add(jTabbedpane),該行可以在面板上繪製,它只是在一個面板中提供,我無法將其拉入另一個分裂面板,我不不知道爲什麼..當我取消註釋frame.add(jTabbedpane)時,它彈出上面提到的錯誤。

回答

0

你的UI組件沒有意義。你正在調用'setContentPane'到splitpane,它是OK(但不尋常),但是你調用add()到框架,然後嘗試添加其他內容到contentPane(JSplitPane)。在將splitPane添加到JPanel之前,您應該將JTabbedPane添加到SplitPane,或者以不同的方式設置您的佈局。

//These don't make sense together. 
frame.setContentPane(splitPane); 
frame.add(jTabbedpane); 

關於繪製藍線的第二個問題比較複雜。 你正在做一堆瘋狂的東西 - 你正在創建一個NewPanel並試圖將它添加到JFrame,但是之後你將JFrame的contentPane設置爲一個不同的組件。您需要通過Swing教程並更好地佈置UI。

0

I think the paint function may not be added to the right way,

public void paintComponent(Graphics g){ 
    super.paint(g); 

要覆蓋paintComponent(...),那麼,爲什麼你叫super.paint(...)

首先閱讀Swing基礎知識的Swing Tutorial。本教程中的所有部分都有可以下載和測試的工作示例。

所以,你可能開始:

  1. 如何使用拆分窗格 - 它會告訴你如何分割窗格中添加一幀
  2. 表演風俗畫 - 這將解釋如何繪畫作品和表演如何重寫paintComponent(...)方法。