2015-06-07 86 views
0

我想要一個帶有按鈕的JFrame,當我點擊它時,球會出現在左上角。然後,如果我再次點擊它,x,y位置會發生變化,並且會移動。問題是我似乎無法讓球在JFrame上出現後,我點擊按鈕。只有按鈕出現。Java Paint和JButton

我的源代碼:

package prac; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Prac extends JComponent { 
    private int x = 0; 
    private int y = 0; 

    private void moveBall() { 
     x = x + 1; 
     y = y + 1; 
    } 

    @Override 
    public void paint(Graphics g) { 
     super.paint(g); 
     Graphics2D g2d = (Graphics2D) g; 
     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON); 
     g2d.fillOval(x, y, 50, 50); 
    } 

    public static void main(String[] args) { 

     JFrame frame = new JFrame("Sample Frame"); 
     JPanel buttonPanel = new JPanel(); 
     JButton moves = new JButton("Click to move ball"); 
     Prac game = new Prac(); 

     buttonPanel.add(moves); 
     frame.setSize(500, 500); 

     frame.add(game); 
     frame.add(buttonPanel); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


     moves.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent action) { 
       game.moveBall(); 
       game.repaint(); 
      } 
     }); 

    } 
} 

感謝

回答

0

創建Prac對象後,加入這一行。

Prac game = new Prac(); 
game.setSize(500, 500); 

結果:

Result

+0

謝謝,Gosu。 ^。^ – Denominator

+0

@Denominator沒問題:) – Gosu

0

您應該重寫油漆成分,而不是paint()方法。

此外,您應該將組件添加到Jframe的內容窗格而不是JFRAME本身。

最有可能您的組件沒有合適的大小。我會建議:

JFrame frame = new JFrame("Sample Frame"); 
    JPanel buttonPanel = new JPanel(); 
    JButton moves = new JButton("Click to move ball"); 
    Prac game = new Prac(); 

    buttonPanel.add(moves); 
    frame.setSize(500, 500); 
    Container c = frame.getContentPane(); 
    c.setLayout (new BorderLayout()); 
    c.add(game, BorderLayout.CENTER); 
    c.add(buttonPanel, BorderLayout.NORTH); 

這將導致您的game組件在大部分框架上展開。