我有一个applet(这是一个SSCCE):
package tutoringcalculator;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;
public class TutoringCalculator extends JApplet {
private JPanel _root;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Tutoring Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet applet = new TutoringCalculator();
applet.init();
frame.setContentPane(applet.getContentPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
applet.start();
}
});
}
private JPanel swingContainer;
@Override
public void init() {
swingContainer = new JPanel(new BorderLayout());
add(swingContainer, BorderLayout.CENTER);
createScene();
setSize(600, 400);
}
private void createScene() {
JLabel lbl;
JTextField txt;
_root = new JPanel(new FlowLayout());
// build the session minutes
lbl = new JLabel();
lbl.setText("Session Minutes:");
_root.add(lbl);
txt = new JTextField();
_root.add(txt);
swingContainer.add(_root);
}
}
并且我想将大小设置为600x400 - 但我已在setSize(600, 400)
,applet
,frame
和swingContainer
上发布_root
并没有任何变化。我得到一个看起来像这样的屏幕:
答案 0 :(得分:5)
如上所述,applet通常会获得HTML的大小(强制它)。自由浮动JFrame
是不同的。相反,它具有建议大小的组件,然后在pack()
时计算。例如。在JTextField
的构造函数中设置大小后,这就是我们所看到的:
现在,我希望你会在完成之前添加更多组件,并且它们也会使大小更大,但是还有一些其他提示可以使内容更大。边界和布局填充。以下是其中一些内容。
因此,它归结为a)添加一大堆组件,使GUI更大,和/或b)添加布局构造器和放大器中定义的空白区域。边界。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TutoringCalculator {
private JPanel _root;
private JPanel swingContainer;
private JLabel lbl;
private JTextField txt;
TutoringCalculator() {
swingContainer = new JPanel(new BorderLayout());
// set an empty border to it
swingContainer.setBorder(new EmptyBorder(20,20,20,20));
// suggest a spacing of 20px between components
_root = new JPanel(new FlowLayout( FlowLayout.CENTER, 20, 20));
swingContainer.add(_root);
// add a line border so we can see the bounds of this container
_root.setBorder(new LineBorder(Color.BLACK, 1));
// this has a size as needed by the content
lbl = new JLabel("Session Minutes:");
_root.add(lbl);
// Suggest a size (in characters - 10) for the text field
txt = new JTextField(10);
_root.add(txt);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Tutoring Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TutoringCalculator calc = new TutoringCalculator();
frame.setContentPane(calc.swingContainer);
frame.pack();
// much better!
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}