SetBounds not working properly

2019-08-26 18:20发布

问题:

I want to make 3 panels, where one is to the west side, one to the east, and one to the south. When I complie this, it gives me frame with colors all one above another and it doesn't give me buttons.

frame = new JFrame();
frame.setBounds(600, 200, 500, 350);
frame.setTitle("Dr. Idrizovic");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panelWest = new JPanel();
panelWest.setBounds(0, 0, 175, 310);
panelWest.setLayout(null);
panelWest.setBackground(Color.green);   

regUslugaButt = new JButton("Registar usluga");
regUslugaButt.setBounds(12, 35, 150, 25);

regMaterijalaButt = new JButton("Registar materijala");
regMaterijalaButt.setBounds(12, 95, 150, 25);

regIntervencijaButt = new JButton("Registar intervencija");
regIntervencijaButt.setBounds(12, 155, 150, 25);

regDijagnozaButt = new JButton("Registar dijagnoza");
regDijagnozaButt.setBounds(12, 215, 150, 25);


panelEast = new JPanel();
panelEast.setBounds(325, 0, 175, 310);
panelEast.setLayout(null);
panelEast.setBackground(Color.red);

evidencijaPacButt = new JButton("Evidencija pacijenata");
evidencijaPacButt.setBounds(324, 35, 150, 25);

zakazivanjePacButt = new JButton("Zakazivanje pacijenata");
zakazivanjePacButt.setBounds(12, 95, 150, 25);

evidencijaStomatologaButt = new JButton("Evidencija stomatologa");
evidencijaStomatologaButt.setBounds(12, 155, 150, 25);

izvrseneUslugeButt = new JButton("Izvrsene usluge");
izvrseneUslugeButt.setBounds(12, 215, 150, 25);






panelSouth = new JPanel();
panelSouth.setBounds(175, 310, 150, 40);
panelSouth.setLayout(null);
panelSouth.setBackground(Color.black);

exitButt = new JButton("Kraj rada");
exitButt.setBounds(174, 260, 150, 25);






panelWest.add(regUslugaButt);
panelWest.add(regMaterijalaButt);
panelWest.add(regIntervencijaButt);
panelWest.add(regDijagnozaButt);

panelEast.add(evidencijaPacButt);
panelEast.add(zakazivanjePacButt);
panelEast.add(evidencijaStomatologaButt);
panelEast.add(izvrseneUslugeButt);

panelSouth.add(exitButt);

frame.add(panelWest);
frame.add(panelSouth);
frame.add(panelEast);

回答1:

I want to make 3 panels where one is to the west side,one to the east and one to the south.

Don't use a null layout. Don't use setBounds().

Instead you should be using a BorderLayout for you main panel. Your child panels should also use an appropriate layout manager.



回答2:

you have a JFrame you need to set a layout to the frame you have like this:

          frame.setLayout(new BorderLayout());

and later you need to add each panel in the position you like, like this:

    frame.add(panelWest, BorderLayout.WEST);

remember to this at the end, when you alredy set all the properties of all the panels.