Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Заочники 2020-2021 / Лекция 6.ppt
Скачиваний:
65
Добавлен:
15.06.2021
Размер:
746.5 Кб
Скачать

GUI в Java. Классы фреймов. DrawFrame. Обработка событий

Лекция 6

public void actionPerformed(ActionEvent ae) {

 

if( ae.getActionCommand().toString() == "closeGraf" ) {

 

JOptionPane JOP = new JOptionPane();

 

int selection = JOP.showConfirmDialog(getParent(), "Вы действительно хотите скрыть график?", "Prop", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);

if( selection == JOptionPane.OK_OPTION ){ this.Status.setText("График - скрыт"); //Скрываем график, открываем кнопку OpenGraf this.DG.setVisible(false); this.openGraf.setVisible(true); this.closeGraf.setVisible(false); this.setJFT("График - скрыт");

}

}

else if( ae.getActionCommand().toString() == "openGraf" ) { this.Status.setText("График - отображается"); //Открываем график, открываем кнопку closeGraf this.DG.setVisible(true); this.openGraf.setVisible(false); this.closeGraf.setVisible(true);

this.setJFT("График - отображается");

}

}

/*

//Метод добавляет текст в поле JFT фрейма DrawProperties

private void setJFT(String text) {

JInternalFrame JIF = (JInternalFrame) App.get("PropFrame"); for(Component temp: JIF.getContentPane().getComponents()) {

if( temp.getName() == "panel" ) { JPanel tempPanel = (JPanel) temp;

for(Component panelComponent: tempPanel.getComponents()) { System.out.println(panelComponent.getClass().getName()+" "+panelComponent.getName()); if( panelComponent.getName() == "JTF" ) {

JTextField tempComponent = (JTextField) panelComponent; tempComponent.setText(text);

}

}

}

}

}

*/

GUI в Java. Классы фреймов. DrawFrame. Обработка событий

Лекция 6

//делаем запись в окно статусов

 

private void setJFT(String text) {

 

JTextField JTF = (JTextField) App.Frames.get(App.PPrefix+"/DrawProperties/panel/JTF");

 

JTF.setText(text);

 

}

 

//Отправляем управление в контроллер в стиле клиент-сервер

 

public String ControllerRequest(String ObjKey, String Action) {

 

Map <String, Object> Request = new HashMap<String, Object>();

 

Request.put("FROM", this);

 

Request.put("TO", ObjKey);

 

Request.put("ACTION", Action);

 

return App.getResponse(Request);

 

}

 

public Component[] getComponents () {

 

return panel.getComponents();

 

}

 

GUI в Java. Классы фреймов. DrawFrame. Обработка событий

Лекция 6

GUI в Java.

Лекция 6

График скрыт по нажатию кнопки «Скрыть график»

Во фрейм «DrawProperties» добавляется текст «График - скрыт»

GUI в Java.

Лекция 6

График отображается по нажатию кнопки «Показать график»

Во фрейм «DrawProperties» добавляется текст «График - отображается»

GUI в Java. Классы фреймов. DrawProperties.

Лекция 6

public class DrawProperties extends JInternalFrame implements ActionListener, KeyListener, MouseListener {

/**

*@author Aam

*DrawProperties - окно, демонстрирующее работу различных контролов

*/

private JComboBox<String> JCB; private JPanel panel;

private JCheckBox JCB_MIET; private JCheckBox JCB_BEST; private JTextField JTF; private JRadioButton JRBLarge; private JRadioButton JRBSmall;

private ButtonGroup ButtonGroup;

public static final String Name = "DrawProperties";

public static final String localPrefix = App.PPrefix+"/"+Name;

public DrawProperties() { super();

//Задаем параметры фрейма this.setTitle(localPrefix); this.setName(localPrefix); this.setSize(200, 200); this.setMinimumSize(new Dimension(200,200)); this.setResizable(true); this.setClosable(true); this.setLocation(680, 0);

this.setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE ); this.setVisible(true);

this.addKeyListener(this); this.getActionMap();

this.getInputMap().put(KeyStroke.getKeyStroke((char) KeyEvent.KEY_PRESSED), ""); this.addMouseListener(this);

App.Frames.put(localPrefix, this);

//Создаем панель и назначаем менеджера компоновки для размещения компонентов в панели содержимого panel = new JPanel();

panel.setName("panel");

GridBagLayout layout = new GridBagLayout(); panel.setLayout(layout); App.Frames.put(localPrefix+"/panel", panel);

GUI в Java. Классы фреймов. DrawProperties. Лекция 6

//------------------- Создаем компоненты и разещаем их в ячейках GridBagLayout -----------------------//

//Создаем выпадающий список this.JCB = new JComboBox<String>(); JCB.setName("JCB"); JCB.addItem("First"); JCB.addItem("Second");

JCB.addActionListener(this); //Добавляем слушателя события

GridBagConstraints contrJCB = new GBC(2,1,2,2,100,100,GridBagConstraints.NORTHWEST); //Создаем ячейку для

списка

panel.add(JCB, contrJCB); //Добавляем список в панель в нужное место в сетке App.Frames.put(localPrefix+"/panel/JCB", JCB);

//Создаем первый флажок

this.JCB_MIET = new JCheckBox("МИЭТ"); JCB_MIET.setName("JCB_MIET");

JCB_MIET.addActionListener(this); //Добавляем слушателя событий для флажка

GridBagConstraints contrJCB_MIET = new GBC(1,1,1,1,100,30,GridBagConstraints.NORTHWEST); //Создаем ячейку

для флажка

panel.add(JCB_MIET, contrJCB_MIET); //Добавляем флажок в панель в нужное место в сетке App.Frames.put(localPrefix+"/panel/JCB_MIET", JCB_MIET);

//Создаем второй флажок

this.JCB_BEST = new JCheckBox("Лучший"); JCB_BEST.setName("JCB_BEST"); JCB_BEST.addActionListener(this);

GridBagConstraints contrJCB_BEST = new GBC(1,2,1,1,100,30,GridBagConstraints.NORTHWEST); panel.add(JCB_BEST, contrJCB_BEST);

App.Frames.put(localPrefix+"/panel/JCB_BEST", JCB_BEST);

//Создаем список радиокнопок ButtonGroup = new ButtonGroup();

JRBLarge = new JRadioButton("Large", true); ButtonGroup.add(JRBLarge); JRBLarge.addActionListener(this);

JRBSmall = new JRadioButton("Small", false); JRBSmall.addActionListener(this); ButtonGroup.add(JRBSmall);

GUI в Java. Классы фреймов. DrawProperties.

Лекция 6

//Создаем контейнер, который сам будет содержать свой менеджер компоновки и компоненты Container container = new Container();

container.setName("JRB"); container.setLayout(new GridLayout(1,2));

container.add(JRBLarge, new GBC(1,1,1,1,10,10,GridBagConstraints.NORTHWEST)); container.add(JRBSmall, new GBC(2,1,1,1,10,10,GridBagConstraints.NORTHWEST)); GridBagConstraints contrBG = new GBC(1,3,3,1,100,30,GridBagConstraints.NORTHWEST); panel.add(container, contrBG);

App.Frames.put(localPrefix+"/panel/JRB/Large", JRBLarge);

App.Frames.put(localPrefix+"/panel/JRB/Small", JRBSmall);

//Создаем текстовое поле this.JTF = new JTextField(); JTF.setName("JTF");

JTF.setText("Текст по умолчанию"); JTF.setColumns(15); JTF.addActionListener(this);

GridBagConstraints contrJTF = new GBC(1,4,3,1,100,30,GridBagConstraints.NORTHWEST); panel.add(JTF, contrJTF);

App.Frames.put(localPrefix+"/panel/JTF", JTF);

//Добавляем панель с компонентами в панель контента фрейма getContentPane().add(panel);

GUI в Java. DrawProperties. Обработка событий

Лекция 6

@Override

public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub

if( arg0.getSource().equals(JCB_BEST) ) { this.JTF.setText(JCB_BEST.getText());

}

else if ( arg0.getSource().equals(JCB_MIET) ) { this.JTF.setText(JCB_MIET.getText());

}

else if ( arg0.getSource().equals(JCB) ) { this.JTF.setText(JCB.getSelectedItem().toString());

}

else if ( arg0.getSource().equals(JRBLarge)

|| arg0.getSource().equals(JRBSmall) ) {

JRadioButton temp = (JRadioButton) arg0.getSource(); this.JTF.setText(temp.getText());

}

System.out.println(

arg0.getSource().getClass().getName()

+"\n"

+arg0.getActionCommand()

);

}

GUI в Java. Способы определения компонента в событии

Лекция 6

Пусть задан обработчик:

public void actionPerformed(ActionEvent arg0)

Спомощью проверки на эквивалентность arg0.getSource().equals(JCB_BEST)

Спомощью проверки содержимого ActionCommand arg0.getActionCommand().toString() == "openGraf"

Спомощью проверки имени компонента

arg0.getSource().getClass().getName()

Соседние файлы в папке Заочники 2020-2021