所以我已经看了很多关于这个的话题,但似乎没有解决我的问题! 当我尝试在JLabel或JButton上使用setBounds()或setLocation()时,它只是不起作用!它似乎只是随机地放置它们。 这是我的代码:
public static void main(String[] args) {
final JFrame frame = new JFrame(TITLE);
final JLabel fpsLabel = new JLabel("FPS: ERROR");
final JLabel fpsDone = new JLabel("FPS done: ERROR");
final JPanel contentPanel = new JPanel();
frame.setSize(WIDTH, HEIGHT);
frame.setContentPane(contentPanel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fpsLabel.setLocation(WIDTH / 2, HEIGHT / 6);
fpsDone.setLocation(200, HEIGHT / 6);
frame.setJMenuBar(menubar);
frame.setResizable(false);
frame.add(fpsLabel);
frame.add(fpsDone);
frame.setVisible(true);
}
如果需要,我可以添加图片。
SSCCE:
public static void main(String[] args) {
final JFrame frame = new JFrame("Example SSCCE");
final JLabel fpsLabel = new JLabel("FPS: ERROR");
final JLabel fpsDone = new JLabel("FPS done: ERROR");
final JPanel contentPanel = new JPanel();
final int HEIGHT = 400 / 16 * 9;
frame.setSize(400, HEIGHT);
frame.setContentPane(contentPanel);
fpsDone.setLocation(200, HEIGHT / 2);
fpsLabel.setLocation(200, HEIGHT / 2 + 50);
contentPanel.add(fpsDone);
contentPanel.add(fpsLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
我希望它看起来像什么(ASCII艺术?):
__________________________________
| |
| |
| |
| |
| |
| FPS: ERROR |
| FPS done: ERROR |
| |
| |
| |
| |
| |
__________________________________
答案 0 :(得分:4)
尝试调整此示例:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class SingleColumnFrame {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
// the GUI as seen by the user (without frame)
// the values of '20' are for gaps between components
JPanel gui = new JPanel(new GridLayout(0,1,20,20));
// adjust numbers as required
gui.setBorder(new EmptyBorder(40, 200, 40, 200));
gui.add(new JLabel("FPS: ERROR",SwingConstants.CENTER));
gui.add(new JLabel("FPS done: ERROR",SwingConstants.CENTER));
JFrame f = new JFrame("Demo");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
f.setResizable(false);
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}