Java Swing JPanel

2018-01-09 19:23 更新

Java Swing教程 - Java Swing JPanel


JPanel是用于其他組件的容器。我們可以設(shè)置其布局管理器,邊框和背景顏色。JPanel組相關(guān)組件。

Java Swing教程 - Java Swing JPanel...

下表列出了JPanel類(lèi)的構(gòu)造函數(shù)。

ID 構(gòu)造函數(shù)/說(shuō)明
1 JPanel()創(chuàng)建一個(gè)具有FlowLayout和雙緩沖的JPanel。
2 JPanel(boolean is DoubleBuffered)使用FlowLayout和指定的雙緩沖標(biāo)志創(chuàng)建JPanel。
3 JPanel(LayoutManager布局)使用指定的布局管理器和雙緩沖創(chuàng)建JPanel。
4 JPanel(LayoutManager布局,布爾isDoubleBuffered)使用指定的布局管理器和雙緩沖標(biāo)志創(chuàng)建JPanel。

以下代碼顯示如何使用BorderLayout創(chuàng)建JPanel并向其添加按鈕。

import java.awt.BorderLayout;
/* w w  w  .j  a va  2  s  .c o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel buttonPanel = new JPanel(new BorderLayout()); 
    JButton northButton = new JButton("North");
    JButton southButton = new JButton("South"); 
    JButton eastButton  = new JButton("East"); 
    JButton  westButton = new JButton("west");

    buttonPanel.add(northButton, BorderLayout.NORTH); 
    buttonPanel.add(southButton, BorderLayout.SOUTH); 
    buttonPanel.add(eastButton,  BorderLayout.EAST); 
    buttonPanel.add(westButton,  BorderLayout.WEST);

    frame.add(buttonPanel,  BorderLayout.CENTER);
     

    frame.pack();
    frame.setVisible(true);
  }
}


使用JPanel作為畫(huà)布

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
  public Main() {
  }/*from w  ww .  j  av a 2 s  .  c  o  m*/
  public void paintComponent(Graphics g) {
    int width = getWidth();
    int height = getHeight();
    g.setColor(Color.black);
    g.drawOval(0, 0, width, height);
  }
  public static void main(String args[]) {
    JFrame frame = new JFrame("Oval Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Main());
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)