AXL
AXL

Reputation: 17

GridBagLayout alignment and Button style

I am trying to align a button using the GridBagLayout but it look I just can't achieve that. Also I want to remove the JButton's texture from my custom button, but I can not.. This is what it looks like:

enter image description here

I want the buttons to be at the top( but using GridBagLayout) and also on the left and right margin of the green button there is the remains of the JButton style and I can't remove it completely.

Also, this is my code:

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

        }       
         }
          }

Edit:

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

Upvotes: 0

Views: 772

Answers (1)

alex2410
alex2410

Reputation: 10994

  1. You can achive it with help of dummy JLabel at bottom, like next(add to the end of constructor):

    c.gridy++;
    c.fill = GridBagConstraints.VERTICAL;
    c.weighty = 1;
    add(new JLabel(" "), c);
    
  2. To remove margin you can try setContentAreaFilled() method

  3. Instead of ImageIcon im = new ImageIcon("Start.png"); use ImageIcon im = new ImageIcon(Panel1.class.getResource("Start.png"));

Also see that answer.

Upvotes: 2

Related Questions