2016-11-12 100 views
0

我嘗試製作一個JFrame,其中包含一個JPanel(其中包含一個圓圈),並且它由四個按鈕(北,南,東,西)界定。圓圈將按照按下的按鈕指示的方向移動。
我的問題是,我不能設法把我的JPanel的中心:如何將JPanel添加到JFrame的中心?

https://i.stack.imgur.com/Cv12Q.png

Jframe的階級是這樣的:

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 

@SuppressWarnings("serial") 
public class Frame extends JFrame implements ActionListener { 

JButton north, south, east, west; 
int x = 10, y = 10; 
MyPanel panel; 

public Frame() { 
    setLayout(new BorderLayout()); 
    panel = new MyPanel(); 
    panel.setBackground(Color.MAGENTA); 

    north = new JButton("NORTH"); 
    south = new JButton("SOUTH"); 
    east = new JButton("EAST"); 
    west = new JButton("WEST"); 

    add(panel, BorderLayout.CENTER); 
    add(north, BorderLayout.NORTH); 
    add(south, BorderLayout.SOUTH); 
    add(east, BorderLayout.EAST); 
    add(west, BorderLayout.WEST); 

    north.addActionListener(this); 
    south.addActionListener(this); 
    east.addActionListener(this); 
    west.addActionListener(this); 

    setBounds(100, 100, 300, 300); 
    setVisible(true); 
} 

@Override 
public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == north) { 
     y -= 3; 
     panel.setY(y); 
     panel.repaint(); 
    } 

    if (e.getSource() == south) { 
     y += 3; 
     panel.setY(y); 
     panel.repaint(); 
    } 

    if (e.getSource() == east) { 
     x += 3; 
     panel.setX(x); 
     panel.repaint(); 
    } 

    if (e.getSource() == west) { 
     x -= 3; 
     panel.setX(x); 
     panel.repaint(); 
    } 
} 
} 

而且MyPanel類看起來是這樣的:

import java.awt.Color; 
import java.awt.Graphics; 

import javax.swing.JPanel; 

@SuppressWarnings("serial") 
public class MyPanel extends JPanel { 
private Color color = Color.CYAN; 
private int x = 10, y = 10; 

public void paint(Graphics g) { 
    super.paintComponent(g); 
    g.setColor(color); 
    g.fillOval(x, y, 20, 20); 
} 

public int getX() { 
    return x; 
} 

public void setX(int x) { 
    this.x = x; 
} 

public int getY() { 
    return y; 
} 

public void setY(int y) { 
    this.y = y; 
} 
} 
+0

[many duplicates](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+swing+center+jpanel+ in + jframe) –

+0

@HovercraftFullOfEels,請查看圖片和代碼(在將問題保留爲重複之前)。當使用簡單的BorderLayout時,爲什麼洋紅色面板會被塗在其他組件上?洋紅色的面板應該在中間。問題是我們看不到的代碼.. – camickr

+0

此問題最初是作爲以下副本而封閉的:http://stackoverflow.com/questions/7223530/how-can-i-properly-center-a-jpanel-fixed -size-內-A-的JFrame。我重新開放它,因爲我不相信它是重複的。如果將「MyPanel」替換爲「JPanel」,面板將顯示在中心。所以問題出在自定義的「MyPanel」類中,我們無法訪問該代碼,因此我們無法提供幫助。 – camickr

回答

1

不要覆蓋您的自定義的getX()getY()方法面板。 Swing使用這些方法來確定組件的位置。

相反,您應該有像setCirleX(...),setCircleY(...),getCircleX()getCircleY()這樣的方法。

+0

非常感謝! – Barbi