有两个按钮
left = new JButton("prev");
right = new JButton("next");
我像这样将它们添加到 jframe
mainframe.add(left,BorderLayout.WEST);
mainframe.add(right,BorderLayout.EAST);
但高度与主机的高度相同。如何设置自己的宽度和高度?
以及如何设置它们的位置(不仅在北、西、东、南)?
最佳答案
How to set my own width and height
不要这样做,只需使用 NORTH
限制大小即可或SOUTH
的JPanel
其本身被添加到 EAST
或WEST
外部(父)布局。
很像这样:
import java.awt.*;
import javax.swing.*;
class BorderGUI {
BorderGUI() {
JPanel gui = new JPanel(new BorderLayout(2,2));
JPanel westConstrain = new JPanel(new BorderLayout(2,2));
// LINE_START will be WEST for l-r languages, otherwise EAST
gui.add(westConstrain, BorderLayout.LINE_START);
JPanel westControls = new JPanel(new GridLayout(0,1,2,2));
for (int ii=1; ii<3; ii++) {
westControls.add( new JButton("" + ii) );
}
westConstrain.add(westControls, BorderLayout.PAGE_START);
JPanel eastConstrain = new JPanel(new BorderLayout(2,2));
gui.add(eastConstrain, BorderLayout.LINE_END);
JPanel eastControls = new JPanel(new GridLayout(0,1,2,2));
for (int ii=1; ii<4; ii++) {
eastControls.add( new JButton("" + ii) );
}
// show at the bottom
eastConstrain.add(eastControls, BorderLayout.PAGE_END);
gui.add( new JScrollPane(new JTextArea(6,10)), BorderLayout.CENTER );
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new BorderGUI();
}
});
}
}
关于java - 设置按钮的大小和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10065046/