How to add a JPanel to the center of a JFrame?
我尝试制作一个JFrame,其中有一个JPanel(包含一个圆圈),并且以四个按钮(北,南,东,西)为边界。 圆圈将按所按按钮指示的方向移动。
我的问题是我无法将JPanel放在中心:
JFrame的类如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 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类如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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; } } |
不要覆盖自定义面板的
相反,您应该具有