If in the code below if I leave out the boolean variable bDrawText then the text shows up as soon as the program is launched. So I set that variable to false so as to have the text drawn only when I click the button. But it does not work and the text apperars only if the frame is resized. I assume my use of graphics is wrong...
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);
}
}
}
}
CodePudding user response:
You call repaint for the lowerPanel, but it is necessary to repaint the centralPanel.