我知道人们可能会告诉我使用布局而不是这个,但对于我正在做的项目,我真的很希望能够自己设置定位。
我遇到的问题是,我在面板中的所有定位和尺寸都是正确的,但是当我运行代码时,它根本没有我设置的尺寸或定位,我不明白为什么。
import javax.swing.*;
import java.awt.*;
class MyFrame extends JFrame {
MyFrame() {
SwingUtilities.invokeLater(() -> {
JPanel combatPanel = new JPanel();
combatPanel.setLayout(null);
combatPanel.setBounds(0,0,1380,805);
combatPanel.setBackground(Color.darkGray);
JPanel combatImage = new JPanel();
combatImage.setLayout(null);
combatImage.setBounds(0,0,1380,575);
combatImage.setBackground(Color.black);
JPanel combatActions = new JPanel();
combatActions.setLayout(null);
combatActions.setBounds(0,575,480,230);
combatActions.setBackground(Color.gray);
JPanel combatActionInfo = new JPanel();
combatActionInfo.setLayout(null);
combatActionInfo.setBounds(480,575,900,115);
combatActionInfo.setBackground(Color.lightGray);
JPanel combatPlayerInfo = new JPanel();
combatPlayerInfo.setLayout(null);
combatPlayerInfo.setBounds(480,690,900,115);
combatPlayerInfo.setBackground(Color.red);
ImageIcon icon = new ImageIcon("image.png");
this.setTitle("F&H 342"); // sets title of frame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exit out of application
this.setResizable(false); // prevent frame from being resized
this.setSize(1380, 805); // sets the x-dimension, and y-dimension of frame
this.setVisible(true); // make frame visible
this.getContentPane().setBackground(Color.yellow);
this.setIconImage(icon.getImage());
this.setLayout(null);
combatPanel.add(combatImage);
combatPanel.add(combatActions);
combatPanel.add(combatActionInfo);
combatPanel.add(combatPlayerInfo);
this.add(combatPanel);
});
}
}
public class Main {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
}
}
尝试制作如图所示的尺寸。
标题栏会计入您设置窗口的大小,并且由于某种原因它似乎还会修剪边缘,将宽度添加 13,将高度添加 36 似乎可行。