这就是我需要得到的结果
左侧有一个游戏区域,大小应为(800,600)。右侧窗口的其余部分应该是菜单/分数区域。
我有两个标签(scoreLabel;pointsLabel;),我想将其放在菜单区域的顶部,如图所示。在我的版本中,我使用 gridlayout,但它没有按我想要的方式工作:)
import javax.swing.*;
import java.awt.*;
public class PongFrame extends JFrame {
private JLabel scoreLabel;
private JLabel pointsLabel;
public PongFrame () {
this.setTitle("Game");
this.setSize(1100,600);
this.scoreLabel = new JLabel("score");
this.pointsLabel = new JLabel("");
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new GridLayout(1,2));
labelPanel.add(scoreLabel);
labelPanel.add(pointsLabel);
JPanel gameArea = new JPanel();
gameArea.setBackground(Color.orange);
gameArea.setSize(800,600);
Container con = this.getContentPane();
con.setLayout(new GridLayout(1,2));
con.add(gameArea);
con.add(labelPanel);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void setPoints (String labeltext){
this.pointsLabel.setText(labeltext);
}
public static void main (String [] args){
PongFrame window = new PongFrame();
window.pointsLabel.setText("0");
}
}
最佳答案
您可以使用BorderLayout
获得此布局。
一个用于内容面板,将游戏面板(具有其首选尺寸)放置在西边,将得分面板放置在中心(它将获得所有额外空间)。
另一个用于分数面板,以便您可以将标签(labelPanel
)放置在北边。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class PongFrame extends JFrame {
private final JLabel scoreLabel;
private final JLabel pointsLabel;
public PongFrame() {
this.setTitle("Game");
this.setSize(1100, 600);
scoreLabel = new JLabel("score");
pointsLabel = new JLabel("");
Container con = this.getContentPane();
con.setLayout(new BorderLayout());
//create score/menu panel
JPanel scorePanel = new JPanel();
scorePanel.setLayout(new BorderLayout());
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new GridLayout(1, 2));
labelPanel.add(scoreLabel);
labelPanel.add(pointsLabel);
// add the labels to the north
scorePanel.add(labelPanel, BorderLayout.NORTH);
// create game panel with a preferred size
JPanel gameArea = new JPanel() {
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
};
gameArea.setBackground(Color.orange);
// add the game panel to the west
con.add(gameArea, BorderLayout.WEST);
// add the score/menu panel to the center
con.add(scorePanel, BorderLayout.CENTER);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void setPoints(final String labeltext) {
pointsLabel.setText(labeltext);
}
public static void main(final String[] args) {
PongFrame window = new PongFrame();
window.pointsLabel.setText("0");
}
}
请注意,您可能需要稍微调整一下 labelPanel
和 JLabel
的文本对齐方式。
关于 java 。游戏的布局。如何将标签放置在窗口的右上角?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36914498/