日期:2014-05-20 浏览次数:20747 次
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
class MyJPanle extends JPanel
{
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(JPanelTest.flag)
{
//话一个区域
g.setColor(Color.YELLOW);
g.fillRect(20,20,50,80);
//画一行文字
g.setColor(Color.BLACK);
g.setFont(new Font("Times New Roman",Font.BOLD,20));
g.drawString("The National GeoGraphics",40,50);
}
else
{
//话一个区域
g.setColor(Color.YELLOW);
g.fillRect(20,20,50,80);
//画一行文字
g.setColor(Color.BLACK);
g.setFont(new Font("宋体",Font.BOLD,20));
g.drawString("国家地理杂志",40,50);
}
}
}
public class JPanelTest extends JFrame
{
public static boolean flag;
private JPanel big;
private JPanel small;
private JButton btnAction;
static{
flag = true;
}
public JPanelTest()
{
//自由定位
setLayout(null);
setBounds(0,0,800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
big = new JPanel();
big.setBounds(0,0,500,500);
//为了方便看,给Big画一个边框
Border lb = BorderFactory.createLineBorder(Color.ORANGE,7);
big.setBorder(lb);
add(big);
Border lb2 = BorderFactory.createLineBorder(Color.ORANGE,7);
//让小panel 是自己实现的Panel
small = new MyJPanle();
small.setBounds(50,50,300,200);
small.setBorder(lb2);
big.setLayout(null);
big.add(small);
//在samll panel 里面画东西
btnAction = new JButton("Click Me");
btnAction.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JPanelTest.flag = !JPanelTest.flag;
small.repaint();
}
});
btnAction.setBounds(10,10,100,30);
big.add(btnAction);
setVisible(true);
}
public static void main(String[] args)
{
JPanelTest f = new JPanelTest();
System.out.println("Hello World!");
}
}