Home > Mobile >  How can i change the size of jbutton in jpanel?
How can i change the size of jbutton in jpanel?

Time:04-24

I have tried both b0.setSize(40,40) and b0.setPreferredSize(new Dimension(40,40)), but it does not change. I want to make the button bigger but i don't want to remove the flow layout. Here is the code:

class Calculator extends JFrame {
JFrame f;
JButton b0;
JPanel p;

Calculator() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(null);

    p = new JPanel();
    p.setBounds(20, 80, 295, 360);
    add(p);

    b0 = new JButton("0");
    b0.setSize(100, 40);
    p.add(b0);
}
}

class Test {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        c.setBounds(400, 200, 350, 500);
        c.setVisible(true);
        c.getContentPane().setBackground(Color.gray);
    }
}

CodePudding user response:

Well, that was easier then I though it would be. Just make use of JButton#setMargin, for example...

enter image description here

import java.awt.EventQueue;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            JButton normal = new JButton("Normal");
            JButton large = new JButton("Large");
            large.setMargin(new Insets(32, 32, 32, 32));

            add(normal);
            add(large);
        }

    }
}
  • Related