Colben Kharrl Colben Kharrl - 5 days ago 5
Java Question

JButton showing ellipses

I am trying to set up a GUI in Java using the Swing library. I have created a custom button class that has a custom initializer to make things easier. It is below:

public class JTButton extends JButton {

char type;

public JTButton(String title, ActionListener listener, char type) {
super(title);
this.type = type;
addActionListener(listener);
setForeground(Color.BLACK);
setBackground(Color.WHITE);
setFont(new Font("Monospaced", 1, 10));
setBorderPainted(false);
if (type == 'h') {
setFont(new Font("Monospaced", 1, 24));
}
setOpaque(true);
}

public void setColor(Color t, Color b) {
setBackground(b);
setForeground(t);
}
}


However, when I run the program it is showing elipses in my grid of buttons, like below.

16x16 grid

16x16 grid

It should look like this (this is the smaller grid):

9x9 grid
9x9 grid

I saw some stuff on
GetPreferredSize()
but haven't been able to make anything work. Let me know what I can do!

Extra info: Running in macOS, the grid is set up in a GridLayout

Answer

When I run my program, it shows ellipses in my grid of buttons.

The ellipses are appearing because the buttons are too small for the text to appear.

Potential Solutions:

1. Modify the JButton Margins.

The margins on JButtons are notoriously small. You can resize them to provide extra room for your text to appear.

You can do this in your JTButton constructor by calling...

setMargin(new Insets(0, 0, 0, 0));

Don't forget to import java.awt.Insets;

You can see the documentation for this function here

2. Make each JButton larger.

Since you are using a GridLayout, you can make each button larger by making your "Grid container" larger. The buttons will stretch out to fill the available space evenly.

Depending on what Layout Manager you're using for the parent of the Grid container, there will be different ways to resize it. It's out of the scope of this answer to go into depth on those.

Comments