📄 jpaneltest.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPanelTest extends JApplet {
Panel panel1 = new Panel();
BorderLayout borderLayout1 = new BorderLayout();
JButton jButton1 = new JButton();
JButton jButton2 = new JButton();
JTextField jTextField1 = new JTextField();
Font ft1,ft2;
private Component glassPane = new MyGlassPane();
//初始化
public void init() {
try {
myInit();
}
catch(Exception e) { //异常处理
e.printStackTrace();
}
}
//*************初始设定*******************
private void myInit() throws Exception {
this.setGlassPane(glassPane);//将一个JPanel当作一个glassPane
this.getContentPane().setLayout(borderLayout1);//设定ContentPane的Layout
//#设定jButton1的外观
jButton1.setBackground(Color.black);
jButton1.setForeground(Color.orange);
ft1=new Font("宋体",Font.BOLD,18);
jButton1.setFont(ft1);
jButton1.setText("按钮一");
//#设定jButton2的外观
jButton2.setBackground(Color.blue);
jButton2.setForeground(Color.red);
ft2=new Font("宋体",Font.PLAIN,18);
jButton2.setFont(ft2);
jButton2.setText("按钮二");
jTextField1.setText("请压一下按钮");
//*****加入组件*****
this.getContentPane().add(panel1, BorderLayout.SOUTH);
//加panel1到ContentPane的南边
panel1.add(jButton1, null);//Panel加入JButton1
panel1.add(jButton2, null);//Panel加入JButton2
this.getContentPane().add(jTextField1, BorderLayout.NORTH);
//加TextField1到ContentPane的北边?
//#Button1的事件倾听#
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
//#Button2的事件倾听#
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
}
//#jButton1的按钮事件#
void jButton1_actionPerformed(ActionEvent e) {
glassPane.setVisible(true);
}
//#jButton2的按钮事件#
void jButton2_actionPerformed(ActionEvent e) {
glassPane.setVisible(false);
}
//*************初始设定*******************
}
//此类继承JPanel当作glassPane
class MyGlassPane extends JPanel {
private JButton button;
private Point point= new Point(100,100),//绘图起始点
previous,now;//
private String demoString ="JPanel作GlassPane,可设定DoubleBuffered()";
public MyGlassPane() {
this.setDoubleBuffered(true);
this.setOpaque(false);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
previous= e.getPoint();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
now= e.getPoint();
point.x += now.x - previous.x;
point.y += now.y - previous.y;
repaint();
previous.x = now.x;
previous.y = now.y;
}
});
}
public void paintComponent(Graphics g) {
FontMetrics fm = g.getFontMetrics();
int dsw = fm.stringWidth(demoString);//取得字符串长度
int dsh = fm.getHeight( );
int fmAscent = fm.getAscent();
g.drawRect(point.x, point.y, dsw + 15, dsh + 15);
g.drawString(demoString,point.x + 5, point.y + fmAscent + 5);
for(int i=50;i<=150;i+=10){
g.fillOval(point.x+i, point.y+i,30,30);}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -