[英]Changing width of GridLayout elements
Panel = new JPanel();
gl = new GridLayout(2, 1);
Panel.setLayout(gl);
add(Panel, BorderLayout.EAST);
Up= new JButton("Btn1");
Up.addActionListener(this);
Up.setPreferredSize(new Dimension(200,150));
Panel.add(Up);
Down = new JButton("Btn2");
Down.addActionListener(this);
Down.setPreferredSize(new Dimension(200,300));
Panel.add(Down);
對於這種情況,我將使用GridBagLayout 。 這可以很好地適應GridBagConstraints 。
在您的情況下, weighty
參數將負責控制面板中按鈕的高度。 這是以百分比形式給出的。
代碼如下所示:
panel = new JPanel(new GridBagLayout());
add(panel, BorderLayout.EAST);
up = new JButton("Btn1");
up.addActionListener(this);
up.setPreferredSize(new Dimension(200, 150));
panel.add(up, new GridBagConstraints(0, 0, 1, 1, 100, 33, GridBagConstraints.NORTH, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0,0));
down = new JButton("Btn2");
down.addActionListener(this);
down.setPreferredSize(new Dimension(200, 300));
panel.add(down, new GridBagConstraints(0, 1, 1, 1, 100, 66, GridBagConstraints.NORTH, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0,0));
結果如下所示:
這個問題已經有一個公認的答案,但只是想在答案中進行一些“調整”。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BigWideButtons {
private JComponent ui = null;
static int upCodepoint = 9206; // upward triangle
static int downCodepoint = 9207; // downward triangle
Insets insets = new Insets(0, 75, 0, 75); // wide insets
Font font = getCompatibleFont().deriveFont(120f); // big font
BigWideButtons() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridLayout(0, 1, 10, 10));
ui.setBorder(new EmptyBorder(4,4,4,4));
addButton(upCodepoint);
addButton(downCodepoint);
}
private void addButton(int codepoint) {
JButton b = new JButton(new String(Character.toChars(codepoint)));
b.setFont(font);
b.setMargin(insets);
ui.add(b);
}
private static Font getCompatibleFont() {
Font[] fonts = GraphicsEnvironment.
getLocalGraphicsEnvironment().getAllFonts();
for (Font font : fonts) {
if (font.canDisplay(upCodepoint) &&
font.canDisplay(downCodepoint)) {
System.out.println("Font: " + font.getFamily());
return font;
}
}
return null; // No installed font supports these characters!
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
BigWideButtons o = new BigWideButtons();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
這個答案:
GridLayout
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.