2015-11-05 65 views
0

我試圖創建一個程序,每隔幾秒就繪製100條隨機行。我想添加一個文本字段,允許用戶調整每次刷新之間的時間量。如何創建包含文本框和畫圖組件的JFrame?

但是,每當我嘗試添加更多的組件到我的JFrame中,paintComponent就會完全消失。如何使用文本字段和圖形創建窗口?

這是我迄今爲止

{ 
    import java.awt.*; 
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 
    import javax.swing.*; 
    import javax.swing.Timer; 
    import java.util.*; 

    public class Screensaver extends JPanel implements ActionListener { 

    public static void main (String[] args){ //Create Canvas 
     JFrame one = new JFrame("ScreenSaver"); 
     one.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Screensaver f = new Screensaver(); 
     one.add(f); 
     one.setSize(600,600); 
     one.setVisible(true); 
    } 

    public void paintComponent (Graphics a){ 
     super.paintComponent(a); 
     this.setBackground(Color.WHITE); 
     a.setColor(Color.BLUE); //Outline 
     Random rand = new Random(); 
     Timer time = new Timer(4000, this); 
     time.start(); 
     for(int i =0; i<100; i++){ 
      int x1 =rand.nextInt(600); 
      int y1 =rand.nextInt(600); 
      int x2 =rand.nextInt(600); 
      int y2 =rand.nextInt(600); 
      a.drawLine(x1, y1, x2, y2); 
     } 
    } 

    public void actionPerformed(ActionEvent e) { 
     repaint(); 
    } 

} 

回答

1
JTextField textField = new JTextField(10); 
one.add(textField, BorderLayout.PAGE_START); 
one.add(f, BorderLayout.CENTER); 

一幀的默認佈局管理器是BorderLayout的,所以你需要tomponens添加到佈局的不同區域。有關更多信息和示例,請參閱How to Use BorderLayout的Swing教程部分。本教程還提供其他佈局管理器的示例,並向您展示如何更好地設計您的課程。

本教程還有一個關於Custom Painting的部分,您應該閱讀,因爲您還應該設置自定義繪畫面板的首選大小。

+0

非常有幫助。非常感謝! – user5531310

相關問題