我的代码在JFrame中显示一个菜单和4个JButton。我昨晚测试了代码,一切正常。现在JButton今天早上没有出现在JFrame中。我尝试在Eclipse中做,但我得到了相同的结果。
我得到的输出:
alt text http://i30.tinypic.com/34rirub.jpg
我的代码:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
public class Control {
//JFrame
JFrame main = new JFrame();
//MenuBar
JMenuBar menuBar = new JMenuBar();
//Adding the menu
JMenu fileMenu = new JMenu("File");
JMenu functionMenu = new JMenu("Function");
JMenu helpMenu = new JMenu("Help");
//Adding the Menu Item
JMenuItem addFlight = new JMenuItem("Add Flight");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem landFlight = new JMenuItem("Land Flight");
JMenuItem virtualPath = new JMenuItem("Virtual Path");
JMenuItem flightDetails = new JMenuItem("Flight Details");
JMenuItem about = new JMenuItem("About ...");
//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");
JButton btnLandFlight = new JButton("Land Flight");
JButton btnVirtualPath = new JButton("Virtual Path");
JButton btnFlightDetails = new JButton("Flight Details");
public Control() {
//Adding to the file menu
fileMenu.add(addFlight);
fileMenu.add(exit);
//Adding to the function menu
functionMenu.add(landFlight);
functionMenu.add(virtualPath);
functionMenu.add(flightDetails);
//Adding to the help menu
helpMenu.add(about);
exit.add(new JSeparator());
flightDetails.add(new JSeparator());
//Adding the Menus to the Menu Bar
menuBar.add(fileMenu);
menuBar.add(functionMenu);
menuBar.add(helpMenu);
//FlightInfo setbounds
btnAddFlight.setBounds(30, 30, 120, 30);
btnLandFlight.setBounds(30, 80, 120, 30);
btnVirtualPath.setBounds(30, 130, 120, 30);
btnFlightDetails.setBounds(30, 180, 120, 30);
//JPanel bounds
pnlButton.setLayout(null);
//Adding to JFrame
pnlButton.add(btnAddFlight);
pnlButton.add(btnLandFlight);
pnlButton.add(btnVirtualPath);
pnlButton.add(btnFlightDetails);
main.add(pnlButton);
// JFrame properties
main.setJMenuBar(menuBar);
main.setLayout(null);
main.setBackground(Color.red);
main.setSize(800, 300);
main.setTitle("Air Traffic Control");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
//Adding the actionlistener
//btnAddFlight.addActionListener(new AddFlight());
//btnLandFlight.addActionListener(new LandFlight());
}
public static void main(String[] args) {
new Control();
}
}
我想让JButtons出现在JFrame上。
非常感谢
答案 0 :(得分:3)
您不应将小部件(pnlButton)直接添加到JFrame,您需要将它们添加到为您自动创建的子面板(称为内容窗格)。要获取内容窗格
Container cp = main.getContentPane();
然后做
cp.add(pnlButton);
使用具有绝对定位的空布局通常是个坏主意,顺便说一句。
答案 1 :(得分:1)