如果在下面的代码中,如果我省略了布尔变量bDrawText,那么程序一启动,文本就会显示出来。因此,我将该变量设置为false,以便只在单击按钮时绘制文本。但它不起作用,只有调整了框架的大小,文本才会出现。我认为我对图形的使用是错误的。。。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Demo1 {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
justAnyFrame f = new justAnyFrame("Draw text",200,100,600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
});
}
}
////////////////////////////////////////////////////////////////
class justAnyFrame extends JFrame {
private JButton bDrawText;
private boolean drawNow=false;
public justAnyFrame(String title,int left,int top,int width,int height) {
setTitle(title);
setLocation(left,top);
setSize(width,height);
centralPanel cp=new centralPanel();
cp.setBackground(Color.LIGHT_GRAY);
add(cp,BorderLayout.CENTER);
lowerPanel lp=new lowerPanel();
add (lp, BorderLayout.SOUTH);
}
//////////////////////////////////////////////////////////////////
class lowerPanel extends JPanel implements ActionListener {
public lowerPanel() {
setLayout(new FlowLayout(FlowLayout.LEFT));
bDrawText=new JButton("Draw Text");
bDrawText.addActionListener(this);
add(bDrawText);
}
public void actionPerformed(ActionEvent e) {
Object clicked=e.getSource();
if(clicked==bDrawText) {
drawNow=true;
repaint();
}
}
}
////////////////////////////////////////////////////////////////
class centralPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(drawNow) {
g2.setColor(Color.BLUE);
Font myFont=new Font("Helvetica",Font.BOLD,40);
g2.setFont(myFont);
g2.drawString("QWERTY",50,100);
}
}
}
}
您为lowerPanel调用了重新绘制,但有必要重新绘制centralPanel。