[英]How to add a JPanel to the center of a JFrame?
我嘗試制作一個JFrame,其中有一個JPanel(包含一個圓圈),並且以四個按鈕(北,南,東,西)為邊界。 圓圈將按所按按鈕指示的方向移動。
我的問題是我無法將JPanel放在中心:
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;
}
}
不要覆蓋自定義面板的getX()
和getY()
方法。 Swing使用這些方法來確定組件的位置。
相反,您應該具有setCirleX(...)
, setCircleY(...)
, getCircleX()
和getCircleY()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.