import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;public class Test extends JFrame {
private Message ms=new Message();
private static String str;
public Test(){
this.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
JButton jb1=new JButton("OK");
JButton jb2=new JButton("Cancel");
jb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
str="The "+e.getActionCommand()+" have been clicked";
System.out.println(str);
}
});
jb2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
str="The "+e.getActionCommand()+" have been clicked";
System.out.println(str);
}
});
ms.add(jb1);
ms.add(jb2);
add(ms);
}
public static void main(String[] args){
Test frame=new Test();
frame.setTitle("MessagePanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setSize(500,400);
}
static class Message extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString(str, 10, 10);
}
}
}
图形界面

解决方案 »

  1.   

    给str一个初值就可以了
    private static String str = "";
      

  2.   

    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.event.*;
    import javax.swing.*;public class Test extends JFrame {
    private JButton jb1=new JButton("OK");
    private JButton jb2=new JButton("Cancel");
    private Message jpMessage=new Message();
    public Test(){
    this.setLayout(new BorderLayout());
    JPanel jpButton=new JPanel();
    jpButton.add(jb1);
    jpButton.add(jb2);
    add(jpButton,BorderLayout.NORTH);
    add(jpMessage,BorderLayout.CENTER);
    }
    public static void main(String[] args){
    Test frame=new Test();
    frame.setTitle("MessagePanel");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    frame.setSize(500,400);
    }
    class Message extends JPanel{
    private String str=" ";
    public Message(){
    jb1.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    str="The "+e.getActionCommand()+" have been clicked";
    repaint();
    }
    });
    jb2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    str="The "+e.getActionCommand()+" have been clicked";
    repaint();
    }
    });
    }
    protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawString(str, 180, 60);
    }
    }
    }
    两个面板的布局方式BorderLayout