P
P
PlagueStarScream2017-05-06 13:05:45
Java
PlagueStarScream, 2017-05-06 13:05:45

Mysticism and Java swing, what's the problem?

When you try to learn swing, strange things happen. The essence of the problem is that some elements are not visible after compilation, they become visible only after minimizing, expanding or slightly stretching the window. and always different in one case, the button is not visible, in this code the panel is not visible (it is not visible until the specified methods are performed). But the sample is elementary and therefore stalled

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



public class GUI implements ActionListener {
    JFrame frame;

    public static void main(String args[]){
        GUI gui = new GUI();
        gui.go();

    }

    public void go() {
        frame = new JFrame("GUI");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
        frame.setBackground(Color.BLACK);

       JButton b = new JButton("click");
       b.addActionListener(this);
       frame.getContentPane().add(BorderLayout.NORTH,b);
       JLabel l = new JLabel("label");
       frame.getContentPane().add(BorderLayout.SOUTH,l);
        JTextField f = new JTextField(10);
        f.setText(" blooo");
        draw draw = new draw();
        draw.add(f);
        frame.getContentPane().add(draw);
        
    }
    public void actionPerformed(ActionEvent ev){

        frame.repaint();
    }
    class draw extends JPanel{
        public void paint(Graphics g){

            g.fillRect(0,100,300,50);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Shockoway, 2017-05-06
@PlagueStarScream

frame.setVisible(true);
It is desirable to call this method at the very end. In your case, you first render the window, and only then add elements to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question