我试图制作一个可以添加姓名和地址的程序。 我试图使用GridLayout,但没有按钮显示。 我在这做错了什么? 感谢
您好。我正在尝试制作一个可以添加姓名和地址的程序。 我试图使用GridLayout,但没有按钮显示。 我在这做错了什么? 感谢
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AddressBookProgram extends JFrame {
public AddressBookProgram() {
super("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new GridPanel());
setSize(300, 300);
setVisible(true);
}
private final class GridPanel extends JPanel {
private JPanel bookPanel;
private JPanel buttonPanel;
private JButton add;
private JButton delete;
private JButton search;
private JButton displayAll;
private JButton exit;
private ActionListener buttons = new ButtonListener();
private GridPanel() {
setLayout(new GridLayout(2, 3));
setBackground(Color.green);
bookPanel = new JPanel();
bookPanel.setBackground(Color.white);
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
add = new JButton("Add");
delete = new JButton("Delete");
search = new JButton("Search");
displayAll = new JButton("Display All");
exit = new JButton("Exit");
add.addActionListener(buttons);
delete.addActionListener(buttons);
search.addActionListener(buttons);
displayAll.addActionListener(buttons);
exit.addActionListener(buttons);
buttonPanel.add(add);
buttonPanel.add(delete);
buttonPanel.add(search);
buttonPanel.add(displayAll);
buttonPanel.add(exit);
}
private class ButtonListener implements ActionListener {
/**
* <p>Updates the watchLabel label when button is pushed.</p>
* @param event a button is pushed
*/
public void actionPerformed(ActionEvent event) {
if (event.getSource() == add) {
}
if (event.getSource() == delete) {
}
if (event.getSource() == search) {
}
if (event.getSource() == displayAll) {
}
if (event.getSource() == exit) {
}
}
}
}
public static void main(String[] args) {
new AddressBookProgram();
}
}
答案 0 :(得分:1)
这是因为您创建 buttonPanel
,但不添加。只需写下这一行:
add(buttonPanel);
这将使您的代码成为:
buttonPanel.add(add);
buttonPanel.add(delete);
buttonPanel.add(search);
buttonPanel.add(displayAll);
buttonPanel.add(exit);
add(buttonPanel);