【发布时间】:2015-02-27 21:12:47
【问题描述】:
我遇到了问题。问题在于向 JFrame 添加多个组件,所有组件都在单独的类中。我必须将 DrawBoard 和 QuestionBox 这两个组件添加到 Board 类的 JPanel“面板”中。 DrawBoard 和 QuestionBox 将执行不同的功能。
DrawBoard 组件应为 600x600 像素,而 QuestionBox 组件应为 600x120 像素。 DrawBoard 位于底部,而 QuestionBox 位于顶部。我不确定要使用什么布局。
运行时我得到这个结果。
游戏类
package snake;
//This class is used to run the game.
public class Game {
/**
* @author HyperBlue
*/
public static Board board;
public static void main(String[] args) {
// TODO Auto-generated method stub
//Creates an object board from the Board() construct
board = new Board();
}
}
板级
public class Board implements ActionListener {
public DrawBoard drawBoard;
public QuestionBox questionBox;
public Timer ticker = new Timer(20, this);
public Board() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
JFrame frame = new JFrame("Snake");
frame.pack();
Insets insets = frame.getInsets();
JPanel container = new JPanel();
questionBox = new QuestionBox();
drawBoard = new DrawBoard();
container.setLayout(new BorderLayout());
container.add(questionBox, BorderLayout.NORTH);
container.add(drawBoard, BorderLayout.SOUTH);
frame.setMinimumSize(new Dimension(600+insets.left + insets.right, 720 +insets.bottom + insets.top));
frame.add(container);
//Sets the frame in middle of screen
frame.setLocation((dim.width / 2) - (frame.getWidth() / 2), (dim.height / 2) - (frame.getHeight() / 2));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
画板类
package snake;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
//Warnings will not be thrown (are suppressed).
@SuppressWarnings("serial")
public class DrawBoard extends JPanel{
public static Color yellow = new Color(13816442);
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(yellow);
g.fillRect(0, 0, 600, 600);
}
}
问题框类
package snake;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class QuestionBox extends JPanel{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 600, 120);
}
}
【问题讨论】:
-
仅供参考:您可以使用
setBackground更改组件的背景颜色,而不必覆盖paintComponent
标签: java swing layout jpanel components