我正在尝试使用 GridBagLayout 对齐按钮,但看起来我无法实现这一点。另外,我想从自定义按钮中删除 JButton
的纹理,但我不能..这就是它的样子:
我希望按钮位于顶部(但使用 GridBagLayout
),并且在绿色按钮的左右边缘上还有 JButton
的剩余部分风格,我无法完全删除它。
另外,这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestPanel{
public TestPanel(){
JFrame frame = new JFrame();
frame.add(new Panel1());
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestPanel();
}
public class Panel1 extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
public Panel1(){
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
ImageIcon im = new ImageIcon("Start.png");
ImageIcon i = new ImageIcon("Start-Pressed.png");
JButton button = new JButton(im);
JButton but = new JButton("BUT");
button.setRolloverEnabled(true);
Insets margin = new Insets(-15,-10,-10,-10);
button.setBorderPainted(false);
button.setMargin(margin);
button.setRolloverIcon(i);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx=0.5;
c.gridx=0;
c.gridy=0;
add(button, c);
c.gridx=2;
c.gridy=1;
add(but,c);
}
}
}
编辑:
c.gridy++;
c.fill = GridBagConstraints.VERTICAL;
c.weighty = 1;
c.add(new JLabel(" "),c);
c.gridy++;
c.weighty = 1;
c.fill = GridBagConstraints.NONE;
add(eButton, c);
最佳答案
您可以借助底部的虚拟
JLabel
来实现它,例如 next(添加到构造函数的末尾):c.gridy++; c.fill = GridBagConstraints.VERTICAL; c.weighty = 1; add(new JLabel(" "), c);
要删除边距,您可以尝试
setContentAreaFilled()
方法- 不要使用
ImageIcon im = new ImageIcon("Start.png");
使用ImageIcon im = new ImageIcon(Panel1.class.getResource("Start.png"));
另请参阅 answer .
关于java - GridBagLayout对齐和Button样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299759/