我试过 use this而且它不起作用
singleplayerButton.setBounds(20, 20, 200, 100);
我不知道为什么,有人可以帮我解决这个问题吗?
我的整页代码是here
package gmine;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class gmine implements ActionListener {
JFrame interfaceFrame;
JButton singleplayerButton, multiplayerButton, optionsButton, quitButton;
public gmine() {
JFrame.setDefaultLookAndFeelDecorated(false);
interfaceFrame = new JFrame("G-Mine B0.4");
interfaceFrame.setSize(800,600);
interfaceFrame.setLayout(new GridLayout(9,1, 20, 15));
singleplayerButton = new JButton("SinglePLayer");
singleplayerButton.addActionListener(this);
interfaceFrame.add(singleplayerButton);
singleplayerButton.setBounds(20, 20, 200, 100);
multiplayerButton = new JButton("MultiPlayer");
multiplayerButton.addActionListener(this);
interfaceFrame.add(multiplayerButton);
optionsButton = new JButton("Options");
optionsButton.addActionListener(this);
interfaceFrame.add(optionsButton);
quitButton = new JButton("Quit");
quitButton.addActionListener(this);
interfaceFrame.add(quitButton);
interfaceFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
interfaceFrame.setVisible(true);
}
public void actionPerformed(ActionEvent a) {
}
public static void main(String[] args) {
new gmine();
}
}
我正在努力使按钮变小,这样就不会触及页面的侧面。
最佳答案
我个人会使用布局管理器,它可以让您更灵活地决定按钮的布局方式,并努力满足您的组件首选尺寸,但您可以自由地根据需要进行调整。 .
对我来说,这就是 GridBagLayout
public class ButtonsLayout {
public static void main(String[] args) {
new ButtonsLayout();
}
public ButtonsLayout() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MenuPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MenuPane extends JPanel {
public MenuPane() {
setLayout(new GridBagLayout());
JButton singleplayerButton = new JButton("SinglePLayer");
JButton multiplayerButton = new JButton("MultiPlayer");
JButton optionsButton = new JButton("Options");
JButton quitButton = new JButton("Quit");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 20;
gbc.ipady = 20;
add(singleplayerButton, gbc);
gbc.gridy++;
add(multiplayerButton, gbc);
gbc.gridy++;
add(optionsButton, gbc);
gbc.gridy++;
add(quitButton, gbc);
}
}
}
这里,我使用GridBagConstraints
的ipadx
和ipady
通过布局管理器来增加组件的宽度和高度,以及使用 HORIZONTAL
填充使所有组件的宽度相同。
看看
更多信息
关于Java 按钮宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13136701/