java - GridBagLayout对齐和Button样式

标签 java swing layout-manager gridbaglayout

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

enter image description here

我希望按钮位于顶部(但使用 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);

最佳答案

  1. 您可以借助底部的虚拟 JLabel 来实现它,例如 next(添加到构造函数的末尾):

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

另请参阅 answer .

关于java - GridBagLayout对齐和Button样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299759/

相关文章:

java - 重新画一个圆

java - 使用 BorderLayout 将 JButton 放在屏幕中央

Java 布局格式化 (GridBagLayout)

java - 用于 GWT 的 Moxieapps 文件 uploader 添加多个上传按钮

Java 转换导致运行时错误而不是编译错误

Java Swing EDT : How to know which threads are waiting the execution of an EventDisplay via SwingUtilities. invokeAndWait?

java - JButton Windows 外观

java - GridLayout 中的组件无法正确显示

java 到 sql server 连接异常

java - 使用 Reactor WebClient 发出非阻塞 HTTP 请求并将响应反序列化到对象的最佳方法是什么?