2017-03-09 16 views
0

這是我當前的代碼,試圖在公共Pos上添加JLabel,但它不會顯示,並且當我這樣做時沒有任何錯誤。如何在我的項目中添加JLabel?我是一名初學者,我不知道是否必須放置其他東西,這樣我的JLabel纔會出現。如何把JLabel放在我當前的代碼上?我正在研究POS類型的學校項目

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class Pos extends JFrame implements ActionListener { 

    private JMenuBar mainBar = new JMenuBar(); 
    private JMenu menu1 = new JMenu("File"); 
    private JMenuItem exit = new JMenuItem("Exit"); 
    private JLabel itemLabel = new JLabel("Item Name:"); 


    public Pos() { 

     setTitle("Point of Sale System"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLayout(new FlowLayout()); 
     setJMenuBar(mainBar); 
     mainBar.add(menu1); 
     menu1.add(exit); 
     exit.addActionListener(this); 

    } 

    public void actionPerformed(ActionEvent e) { 

     Object source = e.getSource(); 
     Container con = getContentPane(); 
     if(source == exit) 
     System.exit(0); 
    } 

    public static void main(String[] args) { 

     Pos mFrame = new Pos(); 
     final int WIDTH = 500; 
     final int HEIGHT = 700; 
     mFrame.setSize(WIDTH, HEIGHT); 
     mFrame.setVisible(true); 
     mFrame.setLocationRelativeTo(null); 

    } 
} 
+0

你有沒有嘗試使用'添加(itemLabel);'作爲最後一行你的構造? – MadProgrammer

+0

MadProgrammer感謝它現在的作品,現在我剩下的問題是放置。再次感謝 –

+0

看看[放置容器中的組件](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html) – MadProgrammer

回答

0

您不是將標籤添加到框架,它只是聲明爲成員變量。在Pos構造函數中,添加:

this.add(itemLabel); 
0

在Frame上需要使用getContentPane()。你這樣做的方式可以用於JPanel,但不適用於JDialog或JFrame(並且你必須實際添加)。就像這樣:

public Pos() { 

    setTitle("Point of Sale System"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    getContentPane().setLayout(new FlowLayout()); // <-- 
    getContentPane().add(itemLabel); // <-- 
    setJMenuBar(mainBar); 
    mainBar.add(menu1); 
    menu1.add(exit); 
    exit.addActionListener(this); 

} 
0

請添加如下:

public Pos() { 

     setTitle("Point of Sale System"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLayout(new FlowLayout()); 
     setJMenuBar(mainBar); 
     mainBar.add(menu1); 
     menu1.add(exit); 
     exit.addActionListener(this); 
     add(itemLabel); 

    } 
相關問題