我正在尝试创建一个按钮数组作为seatChart的模拟,但按钮不会出现在屏幕上,只有框架显示出来。我做错了什么?
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();
答案 0 :(得分:2)
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
或JPanel
。 源的其他(未记录的)更改是改进。如果您对更改的任何部分有疑问,请询问。
答案 1 :(得分:1)
您在JPanel
的构建器中创建了一个新的seatingPanel
,但您没有将其添加到seatingPanel
本身,因此它根本不会显示。
尝试将其添加到seatPanel的布局中。
(或完全取消该子面板 - 将网格布局和按钮直接设置到seatingPanel
。)