我在向JButton
绘制2D JFrame
数组时遇到问题。除了最后一个JButtons
之外,所有JButton
都正确绘制,最后一个要呈现的JFrame
适合JButtons
。我已将所有100x100
的宽度和高度设置为JButton
,但要渲染的最后一个100x100
的宽度和高度不是494X496
。我打印了控制台的属性,它说按钮的高度和宽度为package gameData;
import javax.swing.*;
public class GameRun {
JFrame frame;
ActionHandle AH = new ActionHandle();
Screen screen = new Screen();
public GameRun() {
beginSession();
screen.renderScreen(frame, AH);
}
public void beginSession() {
JFrame frame = new JFrame();
frame.setSize(500, 525);;
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Game");
this.frame = frame;
}
public static void main(String[] args) {
new GameRun();
}
}
。
运行一切的主类:
JButtons
如何绘制package gameData;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Screen {
public void renderScreen(JFrame frame, ActionListener AL){
JButton[][] button = new JButton[5][5];
for(int i =0; i<button.length;i++){
for(int j = 0; j<button[i].length; j++){
button[i][j] = new JButton(i+" "+j);
button[i][j].setBounds(i*100, j*100, 100, 100);
button[i][j].addActionListener(AL);
frame.add(button[i][j]);
}
}
}
}
:
{{1}}
答案 0 :(得分:1)
JFrame
默认使用BorderLayout
,因此您将所有按钮添加到框架上的相同位置,可能会重叠它们。相反,您应该考虑使用GridBagLayout
。有关详细信息,请参阅How to Use GridBagLayout getPreferredSize
方法。setResizable
pack
而不是setSize
,框架的窗口装饰会装在窗口内部,而不会添加到窗口中,这会影响您对内容的可查看空间量{ {1}}将为您完成所有这些计算例如......
pack
在使用import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
JButton[][] button = new JButton[5][5];
for (int i = 0; i < button.length; i++) {
gbc.gridx = 0;
for (int j = 0; j < button[i].length; j++) {
button[i][j] = new JButton(i + " " + j) {
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
add(button[i][j], gbc);
gbc.gridx++;
}
gbc.gridy++;
}
}
}
}
时要小心,在所有平台上,字体通常不会呈现相同的效果,这会影响程序在不同平台上的外观。在您的情况下,按下按钮的getPreferredSize
可能更安全