GridBagLayout对齐和Button样式

时间:2015-02-03 13:09:30

标签: java swing layout-manager gridbaglayout

我正在尝试使用GridBagLayout对齐按钮,但看起来我无法实现这一目标。另外,我想从我的自定义按钮中移除JButton的纹理,但我不能..这就是它的样子:

enter image description here

我希望按钮位于顶部(但使用GridBagLayout),并且绿色按钮的左右边距还有JButton样式的剩余部分,我可以&#39 ; t完全删除它。

另外,这是我的代码:

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);

1 个答案:

答案 0 :(得分:2)

  1. 你可以在底部的虚拟JLabel的帮助下实现它,就像下一个(添加到构造函数的末尾):

    c.gridy++;
    c.fill = GridBagConstraints.VERTICAL;
    c.weighty = 1;
    add(new JLabel(" "), c);
    
  2. 要删除保证金,您可以尝试使用setContentAreaFilled()方法

  3. 而不是ImageIcon im = new ImageIcon("Start.png");使用ImageIcon im = new ImageIcon(Panel1.class.getResource("Start.png"));
  4. 另见answer