Reputation: 143
my first time here and total newbie. I have two classes in my program, the first class SwingPaintDemo2 and the second class MyPanel. MyPanel contains my paintComponent(Graphics g) method. I have a boolean variable in my first class called isTrue. I want to make it so that if isTrue = true; then paintComponent executes g.fillRect(l, w, 50, 50). Believe me, I have googled and googled and googled......
import java.awt.*;
import javax.swing.*;
public class SwingPaintDemo2 extends JComponent {
public static boolean isTrue = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Swing Paint Demo");
JPanel MyPanel = new JPanel();
MyPanel.setBorder(BorderFactory.createEmptyBorder(1000, 1000, 1000, 1000));
MyPanel.setPreferredSize(new Dimension(250, 200));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JComponent {
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize() {
return new Dimension(250,200);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int l = 30;
int w = 30;
if (SwingPaintDemo2.isTrue){g.setColor(Color.black);
g.fillRect(l, w, 50, 50);}
}
}
how do I get my isTrue variable to my paintComponent class (getting variable not found error in paintComponent class)? Thanks in advance for any help.
Update: I have just posted my most recent code above after making the changes suggested earlier. Now I am getting "cannot find symbol - variable isTrue", any help would be appreciated, thanks
Upvotes: 2
Views: 1380
Reputation: 6802
Since isTrue
is a static member of SwingPaintDemo2
class, you can access this without instantiating a new object i.e. SwingPaintDemo2.isTrue
So your code will look like:
public void paintComponent(Graphics g) {
super.paintComponent(g);
int l = 30;
int w = 30;
SwingPaintDemo2 PaintDemo = new SwingPaintDemo2();
if (SwingPaintDemo2.isTrue == true){
g.setColor(Color.black);
g.fillRect(l, w, 50, 50);
}
}
Upvotes: 0
Reputation: 47608
If you want to access a public static variable, always refer to it using the name of the enclosing class (and not by recreating a new instance of your SwingPaintDemo2 class):
SwingPaintDemo2.isTrue
You should try to avoid static variables.
Now, maybe you meant to declare a constant, then you need to declare it final
public static final boolean isTrue = true;
Finally, I see also a suspicious line:
if (isTrue=true)
which should rather be
if (isTrue)
NB: variables should start with a lower-case letter.
Upvotes: 1