2014-10-03 4 views
0

По какой-то причине я не могу получить BorderLayout, чтобы установить способ, которым он должен. Просто хотел бы знать, где я ошибаюсь.BorderLayout не работает JFrame

import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 

public class ColorFactory extends JFrame 
{ 

    final int width = 500; 
    final int height = 300; 

    private JPanel buttonPanel; 
    private JPanel radioButtonPanel; 
    private JLabel msgChangeColor; 

    public ColorFactory() 
    { 
     setTitle("Color Factory"); 
     setSize(width, height); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     setLayout(new BorderLayout()); 

     createTopPanel(); 
     add(buttonPanel, BorderLayout.NORTH); 

     createBottomPanel(); 
     add(radioButtonPanel, BorderLayout.SOUTH); 

     msgChangeColor = new JLabel("Top buttons change the panel color and bottom radio buttons change the text color."); 
     add(msgChangeColor, BorderLayout.CENTER); 

     pack(); 
    } 

    private void createTopPanel() 
    { 
     buttonPanel = new JPanel(); 
     setLayout(new FlowLayout()); 

     JButton redButton = new JButton("Red"); 
     redButton.setBackground(Color.RED); 
     redButton.addActionListener(new ButtonListener()); 
     redButton.setActionCommand("R"); 

     JButton orangeButton = new JButton("Orange"); 
     orangeButton.setBackground(Color.ORANGE); 
     orangeButton.addActionListener(new ButtonListener()); 
     orangeButton.setActionCommand("O"); 

     JButton yellowButton = new JButton("Yellow"); 
     yellowButton.setBackground(Color.YELLOW); 
     yellowButton.addActionListener(new ButtonListener()); 
     yellowButton.setActionCommand("Y"); 

     buttonPanel.add(redButton); 
     buttonPanel.add(orangeButton); 
     buttonPanel.add(yellowButton); 

    } 

    private void createBottomPanel() 
    { 
     radioButtonPanel = new JPanel(); 
     setLayout(new FlowLayout()); 

     JRadioButton greenRadioButton = new JRadioButton("Green"); 
     greenRadioButton.setBackground(Color.GREEN); 
     greenRadioButton.addActionListener(new RadioButtonListener()); 
     greenRadioButton.setActionCommand("G"); 

     JButton blueRadioButton = new JButton("Blue"); 
     blueRadioButton.setBackground(Color.BLUE); 
     blueRadioButton.addActionListener(new RadioButtonListener()); 
     blueRadioButton.setActionCommand("B"); 

     JButton cyanRadioButton = new JButton("Cyan"); 
     cyanRadioButton.setBackground(Color.CYAN); 
     cyanRadioButton.addActionListener(new RadioButtonListener()); 
     cyanRadioButton.setActionCommand("C"); 

     radioButtonPanel.add(greenRadioButton); 
     radioButtonPanel.add(blueRadioButton); 
     radioButtonPanel.add(cyanRadioButton); 
    } 

    private class ButtonListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      String actionColor = e.getActionCommand(); 
      if(actionColor.equals("R")) 
      { 
       buttonPanel.setBackground(Color.RED); 
       radioButtonPanel.setBackground(Color.RED); 
      } 

      if(actionColor.equals("O")) 
      { 
       buttonPanel.setBackground(Color.ORANGE); 
       radioButtonPanel.setBackground(Color.ORANGE); 
      } 

      if(actionColor.equals("Y")) 
      { 
       buttonPanel.setBackground(Color.YELLOW); 
       radioButtonPanel.setBackground(Color.YELLOW); 
      } 
     } 
    } 
     private class RadioButtonListener implements ActionListener 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       String actionTextColor = e.getActionCommand(); 
       if(actionTextColor.equals("G")) 
       { 
        msgChangeColor.setForeground(Color.GREEN); 
       } 

       if(actionTextColor.equals("B")) 
       { 
        msgChangeColor.setForeground(Color.BLUE); 
       } 

       if(actionTextColor.equals("C")) 
       { 
        msgChangeColor.setForeground(Color.CYAN); 
       } 
      } 
    } 

     public static void main(String[] args) 
     { 
      ColorFactory run = new ColorFactory(); 
      run.setVisible(true); 
     } 

} 

ответ

1

Проблема вы меняете менеджер компоновки для кадра при создании вашей верхней и нижней панели ...

private void createTopPanel() { 
    buttonPanel = new JPanel(); 
    setLayout(new FlowLayout()); // <--- This is call setLayout on the frame 

Вот почему это опасно ...

  • Продлить от чего-то вроде JFrame ...
  • Компоненты динамической сборки

Это все легко потерять контекст и начать осуществление компонентов, которые вы на самом деле не хотят ...

+0

поэтому я изменил его на buttonPanel.setLayout (новый lowLayout()); и это работает. пришлось удалить pack(); чтобы выровнять панели. спасибо за помощь – user3752231

+1

* «.. и он работает. пришлось удалить pack() ..» * «он работает» и «удален пакет» в * том же * описании. Как странно. Если что-то работает * без * пакета, это признак, что графический интерфейс очень сломан. –

+0

@ user3752231 Проблемы не с 'пакетом'. Попробуйте использовать «EmptyBorder» для создания большего количества пространства вокруг компонента. – MadProgrammer

1

Еще одна проблема (кроме один отправленный MadProgrammer) является то, что вы добавляете компоненты к самой JFrame.

Вы должны добавить контент в область содержимого кадра, которую вы можете получить, позвонив по телефону JFrame.getContentPane().

Пример:

JFrame f = new JFrame("Test"); 
Container c = f.getContentPane(); 
c.add(new JButton("In Center"), BorderLayout.CENTER); 
c.add(new JButton("At the Bottom"), BorderLayout.SOUTH); 
c.add(new JButton("At the Top"), BorderLayout.NORTH); 
c.add(new JButton("On the Left"), BorderLayout.WEST); 
c.add(new JButton("On the Right"), BorderLayout.EAST); 

Вы можете установить/изменить панель содержимого с помощью вызова JFrame.setContentPane(). Панель содержимого по умолчанию уже имеет BorderLayout, поэтому вам даже не нужно ее менять или не устанавливать новую панель.

+0

. Что касается Java 5 (я думаю), 'JFrame # add' автоматически перенаправляется на панель контента, поэтому нет реальной причины, по которой вам нужно использовать' getContentPane', другое чем эстетика ... – MadProgrammer

+0

@MadProgrammer Вы правы, я не осознавал этого. И да, связанные методы были переопределены, начиная с 5.0, чтобы перейти к области содержимого. – icza

Смежные вопросы