2014-10-22 57 views
0

我目前正在學習java,而現在我已經陷入了這個問題。 我已經重新安裝了java(最新版本,1.8.0_25),但問題仍然存在。java中奇怪的JCompnent視覺錯誤

每當我嘗試從JComponent類添加任何可視化的東西時,它會得到這個奇怪的錯誤,我無法弄清楚是什麼導致了它。

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

class Start { 

    public static void main(String[] args) { 

     JFrame frame = new JFrame("Hello!"); 
     JButton button = new JButton("Click me!"); 
     JLabel label = new JLabel("woah"); 
     JTextField textField = new JTextField(12); 

     frame.setDefaultCloseOperation(3); 
     frame.setVisible(true); 
     frame.setSize(250, 250); 

     JPanel p1 = new JPanel(); 
     JPanel p2 = new JPanel(); 

     p1.setLayout(new FlowLayout()); 

     p1.add(textField); 
     p1.add(label); 

     p2.add(button); 

     frame.add(p1, BorderLayout.NORTH); 
     frame.add(p2, BorderLayout.SOUTH); 

    } 


} 

And here is a link to a picture of the result.

回答

0
  • 開始通過確保你的事件指派線程的上下文中啓動程序,請參閱Initial Threads瞭解更多詳情。
  • 不要使窗口可見,直到你準備它的初始視圖
  • 不要依賴於幻數(frame.setDefaultCloseOperation(3)),他們沒有多大意義對於大多數人來說,值可以改變,使用一個常量,例如frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

例如

import java.awt.BorderLayout; 
import java.awt.EventQueue; 
import java.awt.FlowLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

class Start { 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Hello!"); 
       JButton button = new JButton("Click me!"); 
       JLabel label = new JLabel("woah"); 
       JTextField textField = new JTextField(12); 

       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

       JPanel p1 = new JPanel(); 
       JPanel p2 = new JPanel(); 

       p1.setLayout(new FlowLayout()); 

       p1.add(textField); 
       p1.add(label); 

       p2.add(button); 

       frame.add(p1, BorderLayout.NORTH); 
       frame.add(p2, BorderLayout.SOUTH); 

       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 

      } 
     }); 
    } 
} 

還有與Java 8某些機器上的一個問題,但是這應該糾正他們的「最」 ......

+0

它沒有解決這個問題,但我在另一臺機器上測試過,它工作正常,所以我猜這是你所說的java 8的問題。感謝您的快速回答! – Pontusblue 2014-10-24 16:09:04