【发布时间】:2017-03-26 20:32:21
【问题描述】:
我尝试制作一个 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;
}
}
【问题讨论】:
-
@HovercraftFullOfEels,请查看图片和代码(在您重复关闭问题之前)。当使用简单的 BorderLayout 时,为什么要在其他组件上绘制洋红色面板?洋红色面板应该在中间。问题在于我们看不到的代码..
-
这个问题最初是作为一个副本关闭的:stackoverflow.com/questions/7223530/…。我重新打开它是因为我不相信它是重复的。如果将“MyPanel”替换为“JPanel”,则面板将显示在中心。所以问题出在自定义“MyPanel”类中,我们无权访问该代码,所以我们无能为力。
-
我怀疑您的代码正在更改面板的 x/y 位置而不是圆圈。如果没有
MyPanel代码,我们不知道您的自定义绘画在做什么。 -
@camickr 谢谢。你说的对。看起来问题出在 x,y 整数上,就像你说的那样。
标签: java swing jframe jpanel awt