Reputation: 1
I did a JButton
array in Java, but I don't know to present them in the frame, is it possible?
This is the array, I inserted to each index ImageIcon
:
JButton [] buttons=new JButton[55];
Upvotes: 0
Views: 528
Reputation: 9192
For example this:
javax.swing.JFrame frame = new javax.swing.JFrame("Just a JFrame Window Demo");
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
frame.setLayout(new java.awt.BorderLayout());
javax.swing.JPanel topPanel = new javax.swing.JPanel();
topPanel.setLayout(new java.awt.GridLayout());
javax.swing.JLabel headerLabel = new javax.swing.JLabel(
"50 JButtons in a grid using the GridLayout Layout:");
headerLabel.setHorizontalAlignment(javax.swing.JLabel.CENTER);
headerLabel.setPreferredSize(new java.awt.Dimension(500, 80));
topPanel.add(headerLabel);
javax.swing.JPanel centerPanel = new javax.swing.JPanel();
centerPanel.setLayout(new java.awt.GridLayout(5, 10));
javax.swing.JButton[] buttons = new javax.swing.JButton[50];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new javax.swing.JButton(String.valueOf(i));
buttons[i].setName("button_" + i);
buttons[i].addActionListener(new AllButtonsActionListener());
centerPanel.add(buttons[i]);
}
javax.swing.JPanel bottomPanel = new javax.swing.JPanel();
bottomPanel.setLayout(new java.awt.FlowLayout());
javax.swing.JButton somethingButton = new javax.swing.JButton("Some Button");
somethingButton.addActionListener(new AllButtonsActionListener());
javax.swing.JButton exitButton = new javax.swing.JButton("Exit");
exitButton.addActionListener(new AllButtonsActionListener());
bottomPanel.add(somethingButton);
bottomPanel.add(exitButton);
frame.add(topPanel, BorderLayout.NORTH);
frame.add(centerPanel, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
javax.swing.SwingUtilities.invokeLater(() -> {
frame.setVisible(true);
frame.setLocationRelativeTo(null);
});
And an inner class to catch the button selection:
// Inner Class
class AllButtonsActionListener implements java.awt.event.ActionListener {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String aCmd = e.getActionCommand().toLowerCase();
System.out.println("Action Command is: " + aCmd);
if (aCmd.equals("exit")) {
System.exit(0);
}
}
}
When the above code is run you should see...
When you select any button it's caption will be displayed in the console window.
Upvotes: 2