Вопрос

My JFrame is not displaying the button or background color that is set in the constructor. I am only getting a blank box when I start the program. Not sure what is wrong with the code.

//imports
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;;

public class StartingTheCode{

    JButton CalculateButton;
    JTextField Ans;
    JPanel p;
    JFrame f;

    public static void main (String[] args){
        new StartingTheCode();
    }

    //constructor
    StartingTheCode(){
        f = new JFrame("test");
        f.setVisible(true);
        f.setSize(600,600);
        f.setLocationRelativeTo(null);
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        p = new JPanel();
        p.setBackground(Color.BLUE); // not displaying blue background

        CalculateButton = new JButton("+"); // should display button
        CalculateButton.setSize(30,30);
        CalculateButton.setLocation(5,5);
    }
}
Это было полезно?

Решение

You're not adding your button or your JPanel to anything, and so no JFrame is magically going to display them.

You should add your JButton to your JPanel via its add(...) method, and then add the JPanel to the JFrame via its add(...) method, and do so before setting the JFrame visible.

Most importantly, you should read the Swing tutorials, since I speak from experience when saying you'll get no-where just guessing at this stuff. This is all well explained there.

As an aside, avoid setting the sizes of any components and instead read the tutorial section on use of the layout managers as it will allow you to simplify and empower your code greatly.

Другие советы

You need to add your calculateButton to the JPanel with p.add(calculateButton) and add the panel to the frame with f.add(p)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top