I'm trying to create a JButton with an icon and some text in it. My problem is that I want the icon to be left-aligned and the text right-aligned (It isn't necessary to be right-aligned, but I don't want the text to stick to the icon).
Not being able to do this on my own, I tried a slightly different solution. I used the iconTextGap to create some space between the icon and the text, what worked fine in principle, but when I create multiple buttons, which all have the width of the widest, the icon isn't at the very left anymore (except in the button with the longest text).
I included a code to demonstrate that:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.File;
import java.net.MalformedURLException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Main{
private JFrame frame;
private JPanel buttonPanel;
private GridBagConstraints constraints;
public Main() throws MalformedURLException{
frame = new JFrame();
buttonPanel = new JPanel();
frame.add(buttonPanel);
buttonPanel.setLayout(new GridBagLayout());
constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 3, 5);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
String[] text = { "some Text", "this text is longer" };
for (int i = 0; i < text.length; i++) {
JButton button= new JButton(text[i], new ImageIcon(new File("icon.png").toURI().toURL()));
button.setAlignmentX(SwingConstants.WEST);
button.setIconTextGap(30);
button.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 10));
buttonPanel.add(button, constraints);
constraints.gridy++;
}
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
try {
new Main();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Does anyone know of a way to have the icon at the left end and have some space between the icon and the text (or the text right-aligned)?
Have a look at JButton#setHorizontalTextPosition and JButton#setHorizontalAlignment
And just because it might be helpful JButton#setVerticalTextPosition and JButton#setVerticalAlignment
Classic solution to this problem to use additional panel that has a layout that alows to align components such as BorderLayout. Then put the button and label inside it with the corresponding layout alignment. Pack or validate the frame.
Try to set margin to smaller then default values in button properties,
and then set iconTextGap to have it rightmost horizontal position
Related
I'm trying to create something super basic but after getting super frustrated I figured it was time to ask here.
Desired result:
Right now here is my code:
GUI class
package bookingProject;
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class GUI extends javax.swing.JFrame {
JFrame frame = new JFrame();
JPanel silverPanel = new JPanel();
JPanel goldPanel = new JPanel();
Button buttons[] = new Button[30];
public static void main(String args[]) {
new GUI();
}
public GUI() {
setSize(500, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel bronzePanel = new JPanel();
bronzePanel.setLayout(new GridLayout(3, 10));
bronzePanel.setBackground(Color.red);
for (int i = 0; i < 30; i++) {
buttons[i] = new Button();
bronzePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
bronzePanel.add(buttons[i]);
}
add(bronzePanel);
setVisible(true);
silverPanel.setLayout(new GridLayout(3, 10));
silverPanel.setBackground(Color.yellow);
for (int i = 0; i < 30; i++) {
buttons[i] = new Button();
silverPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
silverPanel.add(buttons[i]);
}
add(silverPanel);
setVisible(true);
goldPanel.setLayout(new GridLayout(3, 10));
goldPanel.setBackground(Color.green);
for (int i = 0; i < 30; i++) {
buttons[i] = new Button();
goldPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
goldPanel.add(buttons[i]);
}
add(goldPanel);
setVisible(true);
}
}
And a class for the Buttons I want to use
Button class
package bookingProject;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Button extends JButton implements ActionListener{
public Button (){
this.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source instanceof GUI){
((GUI)source).setBackground(Color.YELLOW);
}
}
}
This is what I'm getting:
I'm brand new to this stuff so forgive my complete ignorance/ability... but what I would like is 3 panels going top to bottom (bronze/silver/gold) each with a GridLayout of buttons... But all I can get is the bronze panel sticking infront of everything else. I think I'm supposed to use BoxLayout to sort the 3 panels into an order but I played around with this for about 4 hours and felt like I was getting nowhere fast.
I also need a way of making the buttons turn yellow when I press them but currently that isn't working; although I barely looked at that.
This is what I'm getting:
By default the content pane of a JFrame uses a BorderLayout. When you add components to the frame the components get added to the BorderLayout.CENTER by default because you didn't specify a constraint. Only one component can be displayed in the CENTER so only the last one added is visible.
I think I'm supposed to use BoxLayout
That is one approach (but probably not the easiest) as you would manually need to specify the space between each row of components.
The section from the Swing tutorial on How to Use Box Layout has a working example to get you started.
Easiest is to use a GridLayout with 3 rows and 2 columns as the layout manager for the frame. Then each individual panel can also use a GridLayout with 3 rows and 5 columns.
If you want spaces between the components in each of your panels then you need to look at the GridLayout API. It allows you to specify a vertical and horizontal gap between components.
Another approach would be to use a GridBagLayout, although this is a little more complicated because you need to specify constraints for each component added.
The tutorial also has sections on How to Use GridBag Layout and How to Use GridLayout.
Note the examples from the tutorial will also show you how to better structure your code so that component are created on the Event Dispatch Thread(EDT).
You can try GridBagLayout instead:
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import java.awt.Insets;
import java.awt.Color;
class Demo{
public static void main(String[]args){
SwingUtilities.invokeLater(()->{
JFrame frame=new JFrame("Grid");
JPanel panel=(JPanel)frame.getContentPane();
GridBagConstraints gbc=new GridBagConstraints();
gbc.insets=new Insets(9,7,5,5);
panel.setLayout(new GridBagLayout());
panel.add(newGrid(Color.YELLOW,gbc, 0, 0),gbc);
panel.add(newGrid(Color.YELLOW,gbc, 1, 0),gbc);
panel.add(newGrid(Color.LIGHT_GRAY,gbc, 0, 1),gbc);
panel.add(newGrid(Color.LIGHT_GRAY,gbc, 1, 1),gbc);
panel.add(newGrid(Color.GREEN,gbc, 0, 2),gbc);
panel.add(newGrid(Color.GREEN,gbc, 1, 2),gbc);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
});
}
private static JPanel newGrid(Color color, GridBagConstraints pGbc, int pX, int pY){
JPanel panel=new JPanel(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
gbc.insets=new Insets(5,5,5,5);
for(int x=0;5>x;x++){
for(int y=0;3>y;y++){
gbc.gridx=x;
gbc.gridy=y;
JButton btn=new JButton("<html> </html>");
btn.setBackground(color);
panel.add(btn,gbc);
}
}
pGbc.gridx=pX;
pGbc.gridy=pY;
return panel;
}
}
I am attempting to make a "sentence randomizer" that, when a button is pressed, makes a grammatically correct sentence, that may not make any sense, by looping different types of words from a separate folder and separate files. It also alternates colors in each panel. I so far am able to get the JButton to show up, but I can't seem to figure out how to get the panels to appear? Here is my code so far for the UI:
package user_interface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import code.sentence;
import user_interface.RandomButtonListener;
public class sentenceUI {
private sentence _s;
private JButton _rando;
public sentenceUI() {
_s = new sentence(this);
JFrame f = new JFrame("Ryan Ellis' Lab 9");
f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
f.add(topPanel);
JPanel lowerPanel = new JPanel();
f.add(lowerPanel);
_rando = new JButton("Random Sentence");
_rando.addActionListener(new RandomButtonListener(_s, this));
lowerPanel.add(_rando);
Color c1 = Color.BLUE;
Color c2 = new Color( 255 - c1.getRed(), 255 - c1.getGreen(), 255 - c1.getBlue());
for(int i = 0; i < 8; i++){
JLabel _l = new JLabel();
_l.setBackground(c1);
_l.setForeground(c2);
Color temp = c1;
c1 = c2;
c2 = temp;
_l.setBorder(BorderFactory.createEmptyBorder(0,0,8,5));
_l.setFont(new Font("Comic Sans", Font.BOLD, 18));
topPanel.add(_l);
}
ArrayList<String> _slst = new ArrayList<String>();
_slst.add("WordLists/adjectives.txt");
_slst.add("WordLists/adverbs.txt");
_slst.add("WordLists/determiners.txt");
_slst.add("WordLists/nouns.txt");
_slst.add("WordLists/verbs.txt");
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
list.add(_slst);
int i = 0;
list.get(i % 5);
f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
}
private void createRButton(String string, JPanel lowerPanel) {
createRButton("Random", lowerPanel);
}
You're adding topPanel twice to the JFrame, here
JPanel topPanel = new JPanel();
f.add(topPanel);
and here:
f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);
and in the 2nd addition, you're adding it as if the JFrame currently used a BorderLayout, but it's not since you've given it a BoxLayout.
Instead, only add the topPanel once, and in a logical way. Also consider giving your JLabel's some dummy text, such as " " so that they have some size when you first pack() your GUI.
Also, your labels are being added but they have no size and are non-opaque and so can't be seen. For example try this within your for loop to see for yourself:
JLabel _l = new JLabel("Label " + i); // to give labels size
_l.setOpaque(true); // so you can see the background color
_l.setBackground(c1);
_l.setForeground(c2);
Using BorderLayout I have put two different JButtons, one on the left (west) and one on the right (east), and a horizontal JSeparator in the center. What I want to do is to y-align the separator to the center, instead of to the top as it is now. I have already tried to use the following method on the separator
setAlignmentY(CENTER_ALIGNMENT);
but it has absolutely no effect. What am I missing? If it is not possible, is there any other way to do that without using external libraries?
This is what I get:
and this is what I want to achieve:
This is the sample code that I am using (JPanels on top and bottom were added just for clarity):
import java.awt.BorderLayout;
import javax.swing.*;
public class SeparatorTest extends JFrame{
JButton btn1 = new JButton("button1");
JSeparator sep = new JSeparator(SwingConstants.HORIZONTAL);
JButton btn2 = new JButton("button2");
public SeparatorTest() {
getContentPane().add(BorderLayout.NORTH, new JPanel());
getContentPane().add(BorderLayout.WEST, btn1);
getContentPane().add(BorderLayout.CENTER, sep);
getContentPane().add(BorderLayout.EAST, btn2);
getContentPane().add(BorderLayout.SOUTH, new JPanel());
setSize(300, 85);
}
public static void main(String[] args){
new SeparatorTest().setVisible(true);
}
}
EDIT 1: I don't mind the layout as long as it looks the same, I used BorderLayout here due to its simpleness.
This will have to do with how the JSeparator UI delegate decides how to paint the component, which, based on your tests, seems to want to always paint the separator starting at a y position of 0.
Instead, you might need to wrap the JSeparator in another panel which can use a different layout manager which meets your needs, like GridBagLayout for example (of course you could just use GridBagLayout to start with, but I'm aiming for the smallest change possible ;))
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SeparatorTest extends JFrame {
JButton btn1 = new JButton("button1");
JSeparator sep = new JSeparator(SwingConstants.HORIZONTAL);
JButton btn2 = new JButton("button2");
public SeparatorTest() {
JPanel pane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
pane.add(sep, gbc);
getContentPane().add(BorderLayout.NORTH, new JPanel());
getContentPane().add(BorderLayout.WEST, btn1);
getContentPane().add(BorderLayout.CENTER, pane);
getContentPane().add(BorderLayout.EAST, btn2);
getContentPane().add(BorderLayout.SOUTH, new JPanel());
setSize(300, 85);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
SeparatorTest frame = new SeparatorTest();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I am using a GridBagLayout to create a JPanel, called 'Preset', that gets replicated several times in a JFrame. Each Preset will have multiple rows (JPanels). My goal is that only one line (the first) will show up, but when the edit button is clicked, they will all show. Right now, the edit button works, but there is a massive space between the lines. I want it to be such that when the extra lines are collapsed, each Preset will be directly above each other (no space). You can see in the following picture what I am talking about.
This is how it looks:
This is how I want it to Look:
I am fairly certain I need to do something with the GridBag, but I don't know what. I have read several tutorials and have written it as I thought it should be, but no luck.
package SSCCE;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class UI extends JFrame{
private final static int HEIGHT = 600;
private final static int WIDTH = 730;
private JPanel pane; //Pane that stores accounts
private JScrollPane scroller;
private Preset[] branches;
public static void main(String[] args) {
JFrame frame = new UI();
}
public UI(){
//Make the UI close when the exit button is clicked
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Sets the size of the UI
this.setSize(WIDTH, HEIGHT);
//Set the layout and add components to it
this.setLayout(new BorderLayout());
//Reads in the settings and sets up the branches
populateBranches();
pane = new JPanel();
pane.setLayout(new GridLayout(branches.length,1));
for (int i = 0; i < branches.length; i++){
pane.add(branches[i]);
}
//Create the center pane of the BorderLayout
scroller = new JScrollPane(pane);
scroller.createVerticalScrollBar();
this.add(scroller,BorderLayout.CENTER);
//Makes the UI visible
this.setVisible(true);
}
private void populateBranches(){
//Populates the branches array based on what is read in, or not read in from the file
branches = new Preset[15];
for (int i = 0; i < branches.length; i++){
branches[i] = new Preset();
branches[i].setEnabled(false);
}
}
public class Preset extends JPanel{
private JTextField eName;
private JButton edit;
private JButton activate;
private JComboBox printer;
private JPanel line1;
private JPanel line2;
private String branchName;
private String ipAddress;
private boolean enableAll;
public Preset(){
eName = new JTextField(20);
edit = new JButton("Edit");
activate = new JButton("Activate");
JPanel nameContainer = new JPanel();
nameContainer.setLayout(new FlowLayout());
nameContainer.add(eName);
printer = new JComboBox();
//
line1 = new JPanel();
line1.setLayout(new FlowLayout());
line1.add(nameContainer);
line1.add(edit);
line1.add(activate);
//
line2 = new JPanel();
line2.setLayout(new BorderLayout());
line2.add(printer, BorderLayout.WEST);
GridBagLayout grid = new GridBagLayout();
GridBagConstraints cons = new GridBagConstraints();
cons.fill = GridBagConstraints.BOTH;
this.setLayout(grid);
cons.ipady = 100;
cons.ipadx = 100;
cons.weighty = 0D;
cons.gridx = 0;
cons.gridy = 0;
cons.gridwidth = 2;
cons.gridheight = 1;
grid.setConstraints(line1, cons);
this.add(line1);
cons.ipady = 100;
cons.ipadx = 100;
cons.weighty = 0D;
cons.gridx = 0;
cons.gridy = 1;
cons.gridwidth = 2;
cons.gridheight = 1;
grid.setConstraints(line2, cons);
this.add(line2);
//Enable all components
enableAll = true;
}
}
}
Remove every statement that assigns padding in the Y AXIS for the GridBagConstraints of the Preset JPanel, i.e.
cons.ipady = 100;
I don't consider this a "real" answer to your question, but something for you to consider: get rid of gridbag. I don't see anything in your desired layout that requires it. Create each panel with two subpanels; the second subpanel contains the stuff that you want to make invisible by default and display later, and use setVisible() to do that.
I've never gotten comfortable with all of the GridBagConstraints, which seem to interact in ways for which I have no clear model. I avoid GridBagLayout for that reason, so I can't help do this with GridBagLayout. But I don't see why you can't do this with simpler (and less wordy) existing Swing containers and layout managers.
This is a real answer to the background question (how to get the effect you want):
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesOneAndTwo implements ActionListener
{
private static final long serialVersionUID = 1L;
JFrame mainWindow = new JFrame("LinesOneandTwo");
JButton showButton = null;
JButton hideButton = null;
JPanel firstb = new JPanel();
public static void main(String[] args)
{
LinesOneAndTwo main = new LinesOneAndTwo();
main.go();
}
private void go()
{
mainWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container contentPane = mainWindow.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JPanel first = new JPanel();
JPanel firsta = new JPanel();
JPanel second = new JPanel();
JPanel seconda = new JPanel();
JPanel secondb = new JPanel();
first.setLayout(new BoxLayout(first, BoxLayout.Y_AXIS));
firsta.setLayout(new BoxLayout(firsta, BoxLayout.X_AXIS));
showButton = new JButton("show");
hideButton = new JButton("hide");
firsta.add(showButton);
firsta.add(hideButton);
firstb.setLayout(new BoxLayout(firstb, BoxLayout.X_AXIS));
firstb.add(new JButton("one"));
firstb.add(new JButton("two"));
first.add(firsta);
first.add(firstb);
second.setLayout(new BoxLayout(second, BoxLayout.Y_AXIS));
seconda.setLayout(new BoxLayout(seconda, BoxLayout.X_AXIS));
secondb.setLayout(new BoxLayout(secondb, BoxLayout.X_AXIS));
seconda.add(new JButton("hiya"));
seconda.add(new JButton("there"));
secondb.add(new JButton("not here"));
second.add(seconda);
second.add(secondb);
secondb.setVisible(false);
firstb.setVisible(false);
showButton.addActionListener(this);
hideButton.addActionListener(this);
mainWindow.add(first);
mainWindow.add(second);
mainWindow.pack();
mainWindow.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == showButton)
{
firstb.setVisible(true);
mainWindow.pack();
}
else if (event.getSource() == hideButton)
{
firstb.setVisible(false);
mainWindow.pack();
}
}
}
Of course, I don't know what's different about the internals of your panels, or how they differ otherwise, but the "show" and "hide" buttons cause the secondary panel within the top panel of the frame to appear and disappear, leaving no gaps.
I still don't like GridBagLayout.
I got the same problem and found a 70% Solution .
If you use rowWeights and set it to 0 for all but your last component (with rowWeights 1.0), nearly all spaces vanish. If your containing Component is larger than all the other components, there remains only the gap before the last component.
GridBagLayout gbl_panelFoo = new GridBagLayout();
gbl_panelFoo.rowWeights = new double[] {0.0, 0.0, 0.0, ... 0.0, 1.0};
Maybe this helps a little
I am wondering about this since we are making a game in Swing and we made our map tiles into jButtons instead of jPanels for whatever reason. Now we want to put units on top of them so the map background is still shown when the unit is on top of them. Anyone know if this is possible?
OK, so I am not sure this is really what you are looking for and how your application is currently set up, but this is an example to have JButtons on top of each other (if this is not what you are looking for, consider posting an SSCCE and give more details). There are other alternatives and better way to handle such thing, but since you asked JButton over a JButton, here is a snippet showing that:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.basic.BasicButtonUI;
public class TestButtonGrid {
protected int x;
protected int y;
protected void initUI() throws MalformedURLException {
final JFrame frame = new JFrame();
frame.setTitle(TestButtonGrid.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridBagLayout());
ImageIcon icon = new ImageIcon(new URL("http://manhack-arcade.net/pivot/isdrawing/tile_bluerock.png"));
ImageIcon unit = new ImageIcon(new URL("http://static.spore.com/static/image/500/642/783/500642783372_lrg.png"));
ButtonUI ui = new BasicButtonUI();
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
gbc.gridx = i;
gbc.gridy = j;
JButton button = new JButton(icon);
button.setBorderPainted(false);
button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
button.setUI(ui);
button.setOpaque(false);
panel.add(button, gbc);
if (i == j) {
// Choose a layout that will center the icon by default
button.setLayout(new BorderLayout());
JButton player = new JButton(unit);
player.setPreferredSize(new Dimension(unit.getIconWidth(), unit.getIconHeight()));
player.setBorderPainted(false);
player.setUI(ui);
player.setOpaque(false);
button.add(player);
}
}
}
frame.add(panel);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestButtonGrid().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}
It might be a better idea to have a panel which contains buttons. Your panel could then use a mouse event listener to perform an action when clicked on.
The advantage of using a jPanel is that you can set a layout within it, which will make positioning your buttons in it much easier.
Well it is possible to put a JButton Over an other JButton you just wont be able to see it.
CardLayout cl = new CardLayout();
JPanel jpnlMain = new JPanel(cl);
jpnlMain.add(new JButton(), "FIRST");
jpnlMain.add(new JButton(), "SECOND");
Then Maybe you could create a Class that Extends Either the Cardlayout or the JPanel to make it show both Items.
EDIT
Made a little Test and HJere is a Button in a Button Buttonception!!
Main class:
import javax.swing.JFrame;
public class Test {
public static void main(String[] arg0){
SpecialButton sp = new SpecialButton();
JFrame jf = new JFrame();
jf.add(sp);
jf.setVisible(true);
jf.pack();
}
}
Special Button Class:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SpecialButton extends JButton{
SpecialButton(){
super();
JButton jbtnMid = new JButton();
JLabel jlblMid = new JLabel(new ImageIcon(this.getClass().getResource("/Images/arrowUpIcon.png")));
jbtnMid .add(jlblMid);
this.add(jbtnMid);
this.setVisible(true);
}
}