Re: need help or explanation
Dave wrote:
The bad part is, when I run this program at work, it works like
it's supposed to. When I run it at home, I get the double menu.
I haven't tried the program on any other PC's yet.
I see the double menus too. I have Vista Ultimate, and Java 1.6 update
17 also. Good job on the sample code btw, you're light-years ahead of
most of the new posters we get around here.
I see two big problems which may be affecting this. First, you
absolutely have to use proper synchronization when dealing with Swing
components. Otherwise, all bets are off. You call methods which are
not thread safe directly from your "main" method, which could be causing
all sorts of errors.
<http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html>
The second thing that I notice that if Thread.sleep() is called on the
EDT, well, you're going to be really unhappy about that. So I
substituted a Swing Timer instead.
What actually fixed the funny display is calling repaint() on the whole
frame instead of just the component. Swing likes to layout whole
components, just trying to update part of one may not work I suppose.
Finally, pay attention to coding standards. Class names should begin
with a capital letter. If this code is from work, I'd think you'd want
to be a bit more rigorous about adhering to standards.
My version follows:
package test;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
graph1.main( args );
}
}
class graph1
{
int x = 70;
int y = 70;
public static void main(String[] args)
{
SwingUtilities.invokeLater( new Runnable() {
public void run() {
graph1 gui = new graph1();
gui.go();
}
} );
}
public void go()
{
JMenuBar mBar = new JMenuBar();
JMenu mMenu1 = new JMenu("Menu1");
JMenuItem mItem = new JMenuItem("first entry");
mBar.add(mMenu1);
mMenu1.add(mItem);
final JFrame frame = new JFrame("Graph1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(mBar);
final MyPaint mp = new MyPaint();
frame.getContentPane().add(mp);
frame.setSize(600,600);
frame.setVisible(true);
ActionListener sprite = new ActionListener() {
public void actionPerformed(ActionEvent e) {
++x;
++y;
frame.repaint();
}
};
Timer spriteTimer = new Timer(200, sprite);
spriteTimer.setInitialDelay( 400 );
spriteTimer.start();
}
class MyPaint extends JPanel
{
public void paintComponent(Graphics g)
{
g.setColor(Color.green);
g.fillOval(x,y,40,40);
}
}
}