Swing JPanel類及實例
JPanel類是一個通用的輕量級容器。
類聲明
以下是javax.swing.JPanel 類的聲明:
public class JPanel extends JComponent implements Accessible
類構造函數
S.N. | 構造函數 & 描述 |
---|---|
1 |
JPanel() Creates a new JPanel with a double buffer and a flow layout. |
2 |
JPanel(boolean isDoubleBuffered) Creates a new JPanel with FlowLayout and the specified buffering strategy. |
3 |
JPanel(LayoutManager layout) Create a new buffered JPanel with the specified layout manager. |
4 |
JPanel(LayoutManager layout, boolean isDoubleBuffered) Creates a new JPanel with the specified layout manager and buffering strategy. |
類方法
S.N. | 方法 & 描述 |
---|---|
1 |
AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JPanel. |
2 |
PanelUI getUI() Returns the look and feel (L&F) object that renders this component. |
3 |
String getUIClassID() Returns a string that specifies the name of the L&F class that renders this component. |
4 |
protected String paramString() Returns a string representation of this JPanel. |
5 |
void setUI(PanelUI ui) Sets the look and feel (L&F) object that renders this component. |
6 |
void updateUI() Resets the UI property with a value from the current look and feel. |
方法繼承
這個類從以下類繼承的方法:
-
javax.swing.JComponent
-
java.awt.Container
-
java.awt.Component
-
java.lang.Object
JPanel 例子
選擇使用任何編輯器創建以下java程序在 D:/ > SWING > com > yiibai > gui >
SwingContainerDemo.javapackage com.yiibai.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingContainerDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; private JLabel msglabel; public SwingContainerDemo(){ prepareGUI(); } public static void main(String[] args){ SwingContainerDemo swingContainerDemo = new SwingContainerDemo(); swingContainerDemo.showJPanelDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java Swing Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial." , JLabel.CENTER); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showJPanelDemo(){ headerLabel.setText("Container in action: JPanel"); JPanel panel = new JPanel(); panel.setBackground(Color.magenta); panel.setLayout(new FlowLayout()); panel.add(msglabel); controlPanel.add(panel); mainFrame.setVisible(true); } }
編譯程序,使用命令提示符。到 D:/ > SWING 然後輸出以下命令。
D:SWING>javac comyiibaiguiSwingContainerDemo.java
如果冇有錯誤出現,這意味著編譯成功。使用下麵的命令來運行程序。
D:SWING>java com.yiibai.gui.SwingContainerDemo
驗證下麵的輸出