package chapter17;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class showRadioButton extends JFrame{
/**
* @param args
*/
showRadioButton(){
creatButtonPanel bp =new creatButtonPanel();
messagePanel mp = new messagePanel();
setLayout(new BorderLayout());
add(bp,BorderLayout.SOUTH);
add(mp,BorderLayout.CENTER);
messagePanel messagepanel = new messagePanel();
setSize(800,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
// TODO 自動生成的方法存根
showRadioButton srb = new showRadioButton();
}
//生成String,並操作String
class messagePanel extends JPanel{
private String s = "Welcome to Java";
private boolean bl = true;
private int x ;
private int y ;
// 第一次繪制圖形
protected void paintComponent(Graphics g){
super.paintComponent(g);
// 設置string的位置
if(bl == true){
FontMetrics fm = g.getFontMetrics();
int sw = fm.stringWidth(s)/2;
int sh = fm.getAscent()/2;
x = getWidth()/2 - sw;
y = getHeight()/2 - sh;
//開始繪制sting並且設置布爾值
g.drawString(s,x,y);
bl = false;
}else{
g.drawString(s,x,y);
}
}
//重繪方法
protected void left(){
x = x - 50;
repaint();
}
public void right() {
x = x + 50;
repaint();
}
}
//繪制button按鈕並出冊事件
class creatButtonPanel extends JPanel{
public creatButtonPanel(){
JButton jbtl = new JButton("left");
JButton jbtr = new JButton("rigtht");
jbtl.setMnemonic('L');
jbtr.setMnemonic('R');
//showRadioButton srb = new showRadioButton();
add(jbtl);
add(jbtr);
jbtl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
messagePanel mp = new messagePanel();
mp.left(); // 重要 外部類調用內部類
}
});
jbtl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
new messagePanel().right();
}
});
//return buttonPanel;
}
}
}
你對象是內部類的,超出這個作用域之後會直接銷毀,那麼你每次重繪的都是不一樣的對象,而不是同一個,每次都新建對象,你將這個對象設置為全局的看一下