简体   繁体   中英

Java Swing elements change every runtime

So I made a program using java's swing library. I made a program that graphs equations and here is the main method if it's relevant:

public static void main(String[] args) throws Exception {

    JFrame frame= new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    frame.setLayout(new GridLayout(1,2));

    GraphPanel gp = new GraphPanel();
    GraphPanel gp2 = new GraphPanel();

    //gp.functs.add(new Function(Phrase.createPhrase("2(25-x^2)^(1/2)")));
    //gp.functs.add(new Function(Phrase.createPhrase("-1.1((25-x^2)^(1/2))")));
    gp.functs.add(new Function(Phrase.createPhrase("x^2")));
    //gp.functs.add(new Function(Phrase.createPhrase("-4/x^2+6")));
    gp2.functs.add(new Function(Phrase.createPhrase("sinx")));

    frame.add(gp);
    frame.add(gp2);
    frame.pack();
    frame.setSize(800, 800);


    //gp.setBorder(BorderFactory.createLineBorder(Color.RED));
    gp.setBounds(100, 100, 700, 700);//I WANT THIS TO ALWAYS RUN

}

I ran two trial runs of the program WITHOUT CHANGING ANY PART OF IT and this is what it looked like:

在此处输入图片说明

Then the next time i ran it:

第二次

If it's relevant, GraphPanel is of type JLabel. I know that if i use a null absolute LayoutManager, it will always work. But I'm just wondering why swing has such inconsistencies in it. I've noticed stuff like this before but I though it was just some error in the program. Why is this? Thanks in advance!

  • Start by moving frame.setVisible(true); to the end of the main method
  • This gp.setBounds(100, 100, 700, 700); is pointless, as gp is under the control of a layout manager ( GridLayout )
  • There's no point in using both path and setSize , pack is generally a safer option, but that will depend on your components correctly overriding getPreferredSize

But I'm just wondering why swing has such inconsistencies in it. I've noticed stuff like this before but I though it was just some error in the program. Why is this?

Mostly because you're not using the API properly. It's possible, because of the way a JFrame is physically attached to a native peer, that the frame may or may not actually be visible on the screen when you reach gp.setBounds .

Also, because you're doing all your work from within the "main" thread and not the Event Dispatching Thread, you're running the risk of a race condition between them, see Initial Threads for more details.

Swing is VERY flexible, it's also unforgiving when you do the wrong things (or things the wrong way)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM