EncoreLaw 2016-07-04 02:36 采纳率: 46.2%
浏览 1202
已结题

GUI太神奇,一个简单的程序,大神来帮帮手

package frame;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
public class frame implements ActionListener {
JFrame f=new JFrame();
JButton button=new JButton("Change colors");
JButton button2=new JButton("Change label");
JLabel label=new JLabel("I'm just a label");
public static void main(String[] args) {
frame gg=new frame();
gg.go();
}
public void go(){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new colorListener());
button2.addActionListener(new textListener());
DrawPanel d=new DrawPanel();
f.getContentPane().add(BorderLayout.CENTER,d);
f.getContentPane().add(BorderLayout.SOUTH,button);
f.getContentPane().add(BorderLayout.WEST,label);
f.setSize(500,400);
f.setVisible(true);
f.getContentPane().add(BorderLayout.EAST,button2);
}
class colorListener implements ActionListener{
public void actionPerformed(ActionEvent event2){
f.repaint();
}
}
class textListener implements ActionListener{
public void actionPerformed(ActionEvent event){
label.setText("I've changed!");
}
}
public void actionPerformed(ActionEvent event3){}
}
为什么我按button2的时候,repaint也会执行?

  • 写回答

2条回答 默认 最新

  • _1_1_7_ 2016-07-04 03:54
    关注

    label 是JFrame f的子组件,当它更新时,会调用父组件的更新方法,看源码:
    public void setText(String text) {
    。。。。。。。。。
    revalidate();
    repaint();//调用自己的repaint
    。。。。。。。。。。。。。
    }

                        repaint 方法是这样定义的:
                            public void repaint() {
        repaint(0, 0, 0, width, height);
    }
    
         public void repaint(long tm, int x, int y, int width, int height) {
        。。。。。。。
         parent.repaint(tm, px, py, pwidth, pheight);//调用父组件的repaint
        ...........
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line