如果在下面的代碼中我省略了布爾變數 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);
}
}
}
}
uj5u.com熱心網友回復:
你為lowerPanel呼叫repaint,但是需要重繪centralPanel。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/323070.html
