我有一个位于firstPanel
的网格,我希望这适合当前的外部大小,然后将第二个面板rightSidePanel
放在旁边。但是firstPanel
比网格延伸得更远,这意味着rightSidePanel
更远离网格。我不想要的。我如何更改firstPanel
的大小我不关心组件的大小调整 - 由布局管理器给出 - 因为屏幕不可调整大小。
package com.aqagame.harrykitchener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Game
{
private JButton moveC1But, moveC2But, rollDiceButton;
public Game()
{
JFrame window = new JFrame ("Main Game");
final JPanel firstPanel = new JPanel(new GridLayout(3,1))
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
int width = getWidth() / 4;
int height = getHeight() / 11;
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 600);
}
for(int i = 0; i < 11; i++)
{
g.drawLine(0, i * height, 455, i * height);
}
g.drawOval(170, 515, 50, 50);
g.drawOval(240, 515, 50, 50);
g.drawOval(320, 515, 50, 50);
g.drawOval(390, 515, 50, 50);
}
};
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(firstPanel, BorderLayout.CENTER);
JPanel rightSidePanel = new JPanel(new BorderLayout());
moveC1But = new JButton("Move Counter 1");
moveC2But = new JButton("Move Counter 2");
rollDiceButton = new JButton("Roll Dice");
rightSidePanel.add(moveC1But, BorderLayout.NORTH);
rightSidePanel.add(rollDiceButton, BorderLayout.SOUTH);
mainPanel.add(rightSidePanel, BorderLayout.EAST);
rightSidePanel.setBackground(Color.cyan);
firstPanel.setBackground(Color.red);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(mainPanel);
window.setSize(800, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new Game();
}
});
}
}
答案 0 :(得分:1)
如果JFrame
也可重新调整大小,它也能正常工作。
for (int i = 0; i < 4; i++) {
g.drawLine(i * width, 0, i * width, getHeight());
}
for (int i = 0; i < 11; i++) {
g.drawLine(0, i * height, getWidth(), i * height);
}
- 编辑 -
完整代码将椭圆也设置在最后一行的中心
int ovalSize = 0;
if (width < height) {
ovalSize = width;
} else {
ovalSize = height;
}
int center = (width - ovalSize) / 2;
for (int i = 0; i < 4; i++) {
g.drawLine(i * width, 0, i * width, getHeight());
g.drawOval(i * width + center, height * 10, ovalSize, ovalSize);
}
for (int i = 0; i < 11; i++) {
g.drawLine(0, i * height, getWidth(), i * height);
}
截图: