问题
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimpleExample extends JFrame {
public SimpleExample() {
setTitle("Simple example");
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton jb = new JButton("TEST");
jb.setBorderPainted(true);
jb.setBounds(5, 5, 1, 1); ---> This line
add(jb);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SimpleExample ex = new SimpleExample();
ex.setVisible(true);
}
});
}
}
Just creating a simple button of a preferred size. The setBounds
method doesn't seem to work. Where am I going wrong?
回答1:
Your frame is under the control of a layout manager, it is making the decisions on how best to layout your components and is overriding the values you have specified using setBounds
Modern GUIs need to run (even on the same OS) in a variety of different graphical environments, including different DPI, screen sizes and font settings for example.
The layout manager makes it possible for you to worry (less) about these issues and it is highly recommended that you make use of them
Take a look at
- Using Layout Managers
- A Visual Guide to Layout Managers
For more details
回答2:
As a good practice, you should not add the button directly to the JFrame
. Instead, add a JPanel
to the frame, set the panel's layout to null
, and add the JButton
to the JPanel
.
来源:https://stackoverflow.com/questions/17481559/jbutton-setboundsx-y-w-h-doesnt-seem-to-work