Reputation: 419
I am trying to create an array of buttons as a simulation of a seatingChart, but the buttons wont show up on the screen only the frame shows up. what am I doing wrong?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class guiCreator extends JFrame
{
public guiCreator()
{
setTitle("Seats");
setSize(500, 600);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
Container contentPane = getContentPane();
contentPane.add(new seatingPanel());
setVisible(true);
}
}
class seatingPanel extends JPanel implements ActionListener
{
public seatingPanel()
{
setLayout(new BorderLayout());
JPanel panel4seating = new JPanel();//creating a grid panel
panel4seating.setLayout(new GridLayout(4, 10));//setting the layout of the grid panel
JButton [] seats = new JButton [40]; //creating a pointer to the buttonsArray
for (int i = 0; i < 40; i++)
{
seats[i] = new JButton();//creating the buttons
seats[i].addActionListener(this);
panel4seating.add(seats[i]);
}
}
@Override
public void actionPerformed(ActionEvent evt)
{
}
//main
guiCreator flightSeats = new guiCreator();
Upvotes: 1
Views: 5310
Reputation: 168815
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GuiCreator extends JFrame
{
public GuiCreator()
{
super("Seats");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.add(new SeatingPanel());
pack();
setVisible(true);
}
public static void main(String[] args) {
new GuiCreator();
}
}
class SeatingPanel extends JPanel
{
public SeatingPanel()
{
super(new BorderLayout());
JPanel panel4seating = new JPanel();//creating a grid panel
panel4seating.setLayout(new GridLayout(4, 10));//setting the layout of the grid panel
JButton [] seats = new JButton [40]; //creating a pointer to the buttonsArray
for (int i = 0; i < 40; i++)
{
seats[i] = new JButton();//creating the buttons
//better to set the preferred size of the button
seats[i].setPreferredSize(new Dimension(50,25));
panel4seating.add(seats[i]);
}
add(panel4seating, BorderLayout.CENTER);
}
}
JFrame
or JPanel
in this instance. The other (undocumented) changes to the source are improvements. If you have questions on any part of the changes, ask.
Upvotes: 3
Reputation: 206669
You're creating a new JPanel
in seatingPanel
's constructor, but you're not adding it to the seatingPanel
itself, so it won't show up at all.
Try adding it to the seatingPanel's layout.
(Or do away with that sub-panel entirely - set the grid layout and and the buttons directly to your seatingPanel
.)
Upvotes: 1