Swing render problem - sometimes the buttons don't show up [closed]

4 days ago 7
ARTICLE AD BOX

After several launches of the same program, some of the buttons disappear until the user clicks on one of the displayed buttons. The number of remaining buttons appears random. Also sometimes the program mixes them up.

The problem is that sometimes after launch I get random buttons in a random order, despite the fact that sometimes after startup everything works as it should. The weird thing is that after running the same code I get different results.

Supposed to look like this:

But sometimes looks like this:

public class Window { final String name = "calculator"; final int[] size = {360, 650}; //vars.. //colors.. final String[] buttonValues = {"%" , "CE", "C", "BS", "1/x", "xp2", "SR", "/", "7", "8", "9", "x", "4", "5", "6", "-", "1", "2", "3", "+", "+/-", "0", ",", "EQ"}; final String[] grayButtonValues = {"%" , "CE", "C", "BS", "1/x", "xp2", "SR", "/", "x", "-", "+"}; final String[] blueButtonValues = {"EQ"}; final String[] operatorValues = {"+", "-", "x", "/"}; //Frames, labels, panels JFrame calculator = new JFrame(name); JLabel displayLabel = new JLabel(); JPanel displayPanel = new JPanel(); JLabel displayLabelOperation = new JLabel(); JPanel displayPanelOperation = new JPanel(); JLabel buttonLabel = new JLabel(); JPanel buttonPanel = new JPanel(); //Fonts.. Window() { calculator.setVisible(true); calculator.setSize(size[0], size[1]); calculator.setLocationRelativeTo(null); calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); calculator.setLayout(new BorderLayout()); calculator.setResizable(false); displayLabel.setBackground(color0); displayLabel.setForeground(color1); displayLabel.setFont(new Font("Arial", Font.PLAIN, 80)); displayLabel.setHorizontalAlignment(JLabel.RIGHT); displayLabel.setText("0"); displayLabel.setOpaque(true); displayPanel.setLayout(new BorderLayout()); displayLabel.add(displayPanel); calculator.add(displayLabel, BorderLayout.NORTH); buttonLabel.setBounds(0, 0, 10, 10); buttonPanel.setBounds(0, 0, 10, 10); buttonPanel.setLayout(new GridLayout(6 , 4)); buttonPanel.setBackground(White); calculator.add(buttonPanel); for (int i = 0; i < buttonValues.length; i++) { JButton buttonI = new JButton(); String buttonValue = buttonValues[i]; buttonI.setFont(new Font("Arial", Font.PLAIN, 30)); buttonI.setText(buttonValues[i]); buttonI.setFocusable(false); buttonI.setBorder(new LineBorder(White, 1)); //applying colors.. buttonPanel.add(buttonI); buttonI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton buttonP = (JButton) e.getSource(); String buttonValue = buttonP.getText(); // switch (buttonValue) { // case "0","1","2","3","4","5","6","7","8","9" -> addNum(); // case "+","-","x","/" -> addOperator(); // case "C" -> C(); // case "EQ" -> equals(); // default -> Error(); // } }
Read Entire Article