Java Swing — различия между версиями
Материал из SEWiki
Antonk (обсуждение | вклад) |
Antonk (обсуждение | вклад) (→Что почитать) |
||
| (не показаны 2 промежуточные версии этого же участника) | |||
| Строка 1: | Строка 1: | ||
== Что почитать == | == Что почитать == | ||
| + | |||
| + | [[Медиа:Java_Swing.pdf | Слайды с лекции]] | ||
[http://mexmat.sgu.ru/sites/chairs/prinf/materials/java/lesson8.htm Ссылка 1] | [http://mexmat.sgu.ru/sites/chairs/prinf/materials/java/lesson8.htm Ссылка 1] | ||
| Строка 63: | Строка 65: | ||
JFrame myWindow = new SimpleWindowButton(); | JFrame myWindow = new SimpleWindowButton(); | ||
myWindow.setVisible(true); | myWindow.setVisible(true); | ||
| + | } | ||
| + | } | ||
| + | </source> | ||
| + | |||
| + | == 4. Layouts == | ||
| + | |||
| + | <source lang="java"> | ||
| + | import java.awt.BorderLayout; | ||
| + | import java.awt.FlowLayout; | ||
| + | import java.awt.GridLayout; | ||
| + | |||
| + | import javax.swing.Box; | ||
| + | import javax.swing.JButton; | ||
| + | import javax.swing.JComponent; | ||
| + | import javax.swing.JFrame; | ||
| + | import javax.swing.JPanel; | ||
| + | |||
| + | class SimpleWindowFlow extends JFrame { | ||
| + | SimpleWindowFlow() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | setSize(400, 300); | ||
| + | JPanel panel = new JPanel(); | ||
| + | panel.setLayout(new FlowLayout()); | ||
| + | panel.add(new JButton("Кнопка")); | ||
| + | panel.add(new JButton("+")); | ||
| + | panel.add(new JButton("-")); | ||
| + | panel.add(new JButton("Кнопка с длинной надписью")); | ||
| + | setContentPane(panel); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | class SimpleWindowBorder extends JFrame { | ||
| + | SimpleWindowBorder() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | setSize(400, 300); | ||
| + | getContentPane().add(new JButton("NORTH"), BorderLayout.NORTH); | ||
| + | getContentPane().add(new JButton("EAST"), BorderLayout.EAST); | ||
| + | getContentPane().add(new JButton("SOUTH"), BorderLayout.SOUTH); | ||
| + | getContentPane().add(new JButton("WEST"), BorderLayout.WEST); | ||
| + | getContentPane().add(new JButton("В ЦЕНТР!")); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | class SimpleWindowGrid extends JFrame { | ||
| + | SimpleWindowGrid() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | setSize(400, 300); | ||
| + | JPanel panel = new JPanel(); | ||
| + | panel.setLayout(new GridLayout(2, 3, 5, 10)); | ||
| + | panel.add(new JButton("Кнопка")); | ||
| + | panel.add(new JButton("+")); | ||
| + | panel.add(new JButton("-")); | ||
| + | panel.add(new JButton("Кнопка с длинной надписью")); | ||
| + | panel.add(new JButton("еще кнопка")); | ||
| + | setContentPane(panel); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | |||
| + | class SimpleWindowBox extends JFrame { | ||
| + | SimpleWindowBox() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | // setSize(400, 300); | ||
| + | Box box = Box.createVerticalBox(); | ||
| + | box.add(new JButton("Кнопка")); | ||
| + | box.add(Box.createVerticalStrut(10)); | ||
| + | box.add(new JButton("+")); | ||
| + | box.add(Box.createVerticalGlue()); | ||
| + | |||
| + | JButton rightButton = new JButton("-"); | ||
| + | rightButton.setAlignmentX(JComponent.RIGHT_ALIGNMENT); | ||
| + | box.add(rightButton); | ||
| + | |||
| + | box.add(Box.createVerticalStrut(10)); | ||
| + | box.add(new JButton("Кнопка с длинной надписью")); | ||
| + | setContentPane(box); | ||
| + | pack(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | class SimpleWindowManual extends JFrame { | ||
| + | SimpleWindowManual() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | setSize(400, 300); | ||
| + | JPanel panel = new JPanel(); | ||
| + | panel.setLayout(null); | ||
| + | JButton button = new JButton("Кнопка"); | ||
| + | button.setSize(80, 30); | ||
| + | button.setLocation(20,20); | ||
| + | panel.add(button); | ||
| + | button = new JButton("Кнопка с длинной надписью"); | ||
| + | button.setSize(120, 40); | ||
| + | button.setLocation(70,50); | ||
| + | panel.add(button); | ||
| + | setContentPane(panel); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public class testFramePanel { | ||
| + | public static void main (String [] args) { | ||
| + | JFrame myWindow = new SimpleWindowBorder(); | ||
| + | myWindow.setVisible(true); | ||
| + | } | ||
| + | } | ||
| + | </source> | ||
| + | |||
| + | == 5. Обрамление == | ||
| + | |||
| + | <source lang="java"> | ||
| + | import java.awt.BorderLayout; | ||
| + | import java.awt.Color; | ||
| + | import java.awt.GridLayout; | ||
| + | |||
| + | import javax.swing.ImageIcon; | ||
| + | import javax.swing.JButton; | ||
| + | import javax.swing.JFrame; | ||
| + | import javax.swing.JPanel; | ||
| + | import javax.swing.border.*; | ||
| + | |||
| + | class SimpleWindowPanelBorder extends JFrame { | ||
| + | SimpleWindowPanelBorder() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(EXIT_ON_CLOSE); | ||
| + | JPanel panel = new JPanel(); | ||
| + | panel.setLayout(new GridLayout(2,3,5,10)); | ||
| + | panel.add(createPanel(new TitledBorder("Рамка с заголовком"), "TitledBorder")); | ||
| + | panel.add(createPanel(new EtchedBorder(), "EtchedBorder")); | ||
| + | panel.add(createPanel(new BevelBorder(BevelBorder.LOWERED), "BevelBorder")); | ||
| + | panel.add(createPanel(new SoftBevelBorder(BevelBorder.RAISED), "SoftBevelBorder")); | ||
| + | panel.add(createPanel(new LineBorder(Color.ORANGE, 4), "LineBorder")); | ||
| + | panel.add(createPanel(new MatteBorder(new ImageIcon("1.gif")), "MatteBorder")); | ||
| + | setContentPane(panel); | ||
| + | pack(); | ||
| + | } | ||
| + | |||
| + | private JPanel createPanel(Border border, String text) { | ||
| + | JPanel panel = new JPanel(); | ||
| + | panel.setLayout(new BorderLayout()); | ||
| + | panel.add(new JButton(text)); | ||
| + | panel.setBorder(new CompoundBorder(new EmptyBorder(12,12,12,12), border)); | ||
| + | return panel; | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public class testBorder { | ||
| + | public static void main (String [] args) { | ||
| + | JFrame myWindow = new SimpleWindowPanelBorder(); | ||
| + | myWindow.setVisible(true); | ||
| + | } | ||
| + | } | ||
| + | </source> | ||
| + | |||
| + | == 6. Компоненты == | ||
| + | |||
| + | <source lang="java"> | ||
| + | import java.awt.BorderLayout; | ||
| + | import java.awt.Color; | ||
| + | import java.awt.GridLayout; | ||
| + | import java.awt.Insets; | ||
| + | |||
| + | import javax.swing.*; | ||
| + | import javax.swing.border.TitledBorder; | ||
| + | |||
| + | class SimpleWindowLabel extends JFrame { | ||
| + | SimpleWindowLabel() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | JLabel label = new JLabel("<html>Метка со значком и с <font size=+5>большой</font> <i>надписью</i></html>", new ImageIcon("1.gif"), SwingConstants.RIGHT); | ||
| + | getContentPane().add(label); | ||
| + | pack(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | class SimpleWindowButton2 extends JFrame { | ||
| + | SimpleWindowButton2() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | JButton button = new JButton("Кнопка", new ImageIcon("1.gif")); | ||
| + | button.setMargin(new Insets(0, 10, 20, 30)); | ||
| + | button.setVerticalTextPosition(SwingConstants.TOP); | ||
| + | button.setHorizontalTextPosition(SwingConstants.LEFT); | ||
| + | getContentPane().add(button); | ||
| + | pack(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | class SimpleWindowToggles extends JFrame { | ||
| + | SimpleWindowToggles() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | ImageIcon icon = new ImageIcon("1.gif"); | ||
| + | // будем использовать один значок на все случаи | ||
| + | |||
| + | Box mainBox = Box.createVerticalBox(); | ||
| + | |||
| + | Box box1 = Box.createVerticalBox(); | ||
| + | JToggleButton tButton1 = new JToggleButton("Кнопка выбора 1"); | ||
| + | JToggleButton tButton2 = new JToggleButton("Кнопка выбора 2", icon); | ||
| + | ButtonGroup bg = new ButtonGroup(); | ||
| + | // создаем группу взаимного исключения | ||
| + | bg.add(tButton1); | ||
| + | bg.add(tButton2); | ||
| + | // сделали кнопки tButton1 и tButton2 взаимоисключающими | ||
| + | box1.add(tButton1); | ||
| + | box1.add(tButton2); | ||
| + | // добавили кнопки tButton1 и tButton2 на панель box1 | ||
| + | box1.setBorder(new TitledBorder("Кнопки выбора")); | ||
| + | Box box2 = Box.createVerticalBox(); | ||
| + | JCheckBox check1 = new JCheckBox("Флажок 1"); | ||
| + | JCheckBox check2 = new JCheckBox("Флажок 2", icon); | ||
| + | box2.add(check1); | ||
| + | box2.add(check2); | ||
| + | // добавили флажки на панель box2 | ||
| + | box2.setBorder(new TitledBorder("Флажки")); | ||
| + | Box box3 = Box.createVerticalBox(); | ||
| + | JRadioButton rButton1 = new JRadioButton("Переключатель 1"); | ||
| + | JRadioButton rButton2 = new JRadioButton("Переключатель 2", icon); | ||
| + | rButton2.setSelectedIcon(new ImageIcon("2.gif")); | ||
| + | bg = new ButtonGroup(); // создаем группу взаимного исключения | ||
| + | bg.add(rButton1); | ||
| + | bg.add(rButton2); | ||
| + | // сделали радиокнопки взаимоисключающими | ||
| + | box3.add(rButton1); | ||
| + | box3.add(rButton2); | ||
| + | // добавили радиокнопки на панель box3 | ||
| + | box3.setBorder(new TitledBorder("Переключатели")); | ||
| + | mainBox.add(box1); | ||
| + | mainBox.add(box2); | ||
| + | mainBox.add(box3); | ||
| + | setContentPane(mainBox); | ||
| + | pack(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | class SimpleWindowText extends JFrame { | ||
| + | SimpleWindowText() { | ||
| + | super("Пробное окно"); | ||
| + | JTextField textField = new JTextField("Текстовое поле", 20); | ||
| + | textField.setCaretColor(Color.RED); | ||
| + | textField.setHorizontalAlignment(JTextField.RIGHT); | ||
| + | |||
| + | JPasswordField passwordField = new JPasswordField(20); | ||
| + | passwordField.setEchoChar('$'); | ||
| + | passwordField.setText("пароль"); | ||
| + | |||
| + | JTextArea textArea = new JTextArea(5, 20); | ||
| + | textArea.setLineWrap(true); | ||
| + | textArea.setWrapStyleWord(true); | ||
| + | for (int i = 0; i <= 20; i++) | ||
| + | textArea.append("Область для ввода текстового содержимого "); | ||
| + | |||
| + | getContentPane().add(textField, BorderLayout.NORTH); | ||
| + | // getContentPane().add(textArea); | ||
| + | getContentPane().add(new JScrollPane(textArea)); | ||
| + | getContentPane().add(passwordField, BorderLayout.SOUTH); | ||
| + | pack(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public class testFrameComponents { | ||
| + | public static void main (String [] args) { | ||
| + | JFrame myWindow = new SimpleWindowText(); | ||
| + | myWindow.setVisible(true); | ||
| + | |||
| + | myWindow = new SimpleWindowToggles(); | ||
| + | myWindow.setVisible(true); | ||
| + | } | ||
| + | } | ||
| + | </source> | ||
| + | |||
| + | == 7. MouseListener == | ||
| + | |||
| + | <source lang="java"> | ||
| + | import java.awt.BorderLayout; | ||
| + | import java.awt.event.ActionEvent; | ||
| + | import java.awt.event.ActionListener; | ||
| + | import java.awt.event.MouseAdapter; | ||
| + | import java.awt.event.MouseEvent; | ||
| + | import java.awt.event.MouseListener; | ||
| + | |||
| + | import javax.swing.JButton; | ||
| + | import javax.swing.JFrame; | ||
| + | import javax.swing.JOptionPane; | ||
| + | import javax.swing.JTextField; | ||
| + | |||
| + | class SimpleWindowButtonListener extends JFrame { | ||
| + | JTextField tField; | ||
| + | class MouseL implements MouseListener { | ||
| + | public void mouseClicked(MouseEvent event) { | ||
| + | if (tField.getText().equals("Иван")) | ||
| + | JOptionPane.showMessageDialog(null, "Привет"); | ||
| + | else JOptionPane.showMessageDialog(null, "Пока!"); | ||
| + | } | ||
| + | public void mouseEntered(MouseEvent event) {} | ||
| + | public void mouseExited(MouseEvent event) {} | ||
| + | public void mousePressed(MouseEvent event) {} | ||
| + | public void mouseReleased(MouseEvent event) {} | ||
| + | } | ||
| + | |||
| + | SimpleWindowButtonListener() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | setSize(400, 300); | ||
| + | JButton newButton = new JButton("Жмакни меня"); | ||
| + | newButton.addMouseListener(new MouseL()); | ||
| + | |||
| + | newButton.addMouseListener(new MouseAdapter() { | ||
| + | public void mouseClicked(MouseEvent event) { | ||
| + | if (tField.getText().equals("Иван")) | ||
| + | JOptionPane.showMessageDialog(null, "Вход выполнен1"); | ||
| + | else JOptionPane.showMessageDialog(null, "Вход НЕ выполнен1"); | ||
| + | } | ||
| + | }); | ||
| + | |||
| + | tField = new JTextField("Привет"); | ||
| + | getContentPane().add(tField, BorderLayout.NORTH); | ||
| + | getContentPane().add(newButton, BorderLayout.SOUTH); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public class testMouseListener { | ||
| + | public static void main (String [] args) { | ||
| + | JFrame myWindow = new SimpleWindowButtonListener(); | ||
| + | myWindow.setVisible(true); | ||
| + | } | ||
| + | } | ||
| + | </source> | ||
| + | |||
| + | == 8. ActionListener == | ||
| + | |||
| + | <source lang="java"> | ||
| + | import java.awt.BorderLayout; | ||
| + | import java.awt.event.ActionEvent; | ||
| + | import java.awt.event.ActionListener; | ||
| + | import java.awt.event.MouseAdapter; | ||
| + | import java.awt.event.MouseEvent; | ||
| + | import java.awt.event.MouseListener; | ||
| + | |||
| + | import javax.swing.JButton; | ||
| + | import javax.swing.JFrame; | ||
| + | import javax.swing.JOptionPane; | ||
| + | import javax.swing.JTextField; | ||
| + | |||
| + | class SimpleWindowButtonListener2 extends JFrame { | ||
| + | JTextField tField; | ||
| + | SimpleWindowButtonListener2() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | setSize(400, 300); | ||
| + | JButton newButton = new JButton("Жмакни меня"); | ||
| + | |||
| + | newButton.addActionListener(new ActionListener() { | ||
| + | public void actionPerformed(ActionEvent event) { | ||
| + | if (tField.getText().equals("Иван")) | ||
| + | JOptionPane.showMessageDialog(null, "Вход выполнен2"); | ||
| + | else JOptionPane.showMessageDialog(null, "Вход НЕ выполнен2"); | ||
| + | } | ||
| + | }); | ||
| + | |||
| + | tField = new JTextField("Привет"); | ||
| + | getContentPane().add(tField, BorderLayout.NORTH); | ||
| + | getContentPane().add(newButton, BorderLayout.SOUTH); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public class testActionListener { | ||
| + | public static void main (String [] args) { | ||
| + | JFrame myWindow = new SimpleWindowButtonListener2(); | ||
| + | myWindow.setVisible(true); | ||
| + | } | ||
| + | } | ||
| + | </source> | ||
| + | |||
| + | == 9. Action == | ||
| + | |||
| + | <source lang="java"> | ||
| + | import java.awt.BorderLayout; | ||
| + | import java.awt.event.ActionEvent; | ||
| + | |||
| + | import javax.swing.*; | ||
| + | |||
| + | class SimpleWindowAction extends JFrame { | ||
| + | private ExitAction exitAction; | ||
| + | SimpleWindowAction(){ | ||
| + | super("Окно с меню"); | ||
| + | setDefaultCloseOperation(EXIT_ON_CLOSE); | ||
| + | exitAction = new ExitAction(); | ||
| + | DeactivateAction deactivateAction = new DeactivateAction(); | ||
| + | JMenuBar menuBar = new JMenuBar(); | ||
| + | JMenu fileMenu = new JMenu("Файл"); | ||
| + | fileMenu.add(new JMenuItem("Новый")); | ||
| + | fileMenu.addSeparator(); | ||
| + | fileMenu.add(deactivateAction); | ||
| + | fileMenu.add(exitAction); | ||
| + | menuBar.add(fileMenu); | ||
| + | setJMenuBar(menuBar); | ||
| + | JToolBar toolBar = new JToolBar("Панель инструментов"); | ||
| + | toolBar.add(exitAction); | ||
| + | toolBar.add(deactivateAction); | ||
| + | getContentPane().add(toolBar, BorderLayout.NORTH); | ||
| + | JPanel panel = new JPanel(); | ||
| + | panel.add(new JButton(exitAction)); | ||
| + | panel.add(new JButton(deactivateAction)); | ||
| + | getContentPane().add(panel); setSize(250,250); | ||
| + | } | ||
| + | |||
| + | class ExitAction extends AbstractAction { | ||
| + | ExitAction(){ | ||
| + | putValue(Action.NAME, "Выйти"); | ||
| + | putValue(Action.SHORT_DESCRIPTION, "Программа перестанет работать, а окно исчезнет с экрана."); | ||
| + | putValue(Action.SMALL_ICON, new ImageIcon("2.gif")); | ||
| + | } | ||
| + | public void actionPerformed(ActionEvent event) { | ||
| + | System.exit(0); | ||
| + | } | ||
| + | } | ||
| + | class DeactivateAction extends AbstractAction { | ||
| + | DeactivateAction(){ | ||
| + | putValue(Action.NAME, "Запретить выход"); | ||
| + | putValue(Action.SMALL_ICON, new ImageIcon("1.gif")); | ||
| + | } | ||
| + | public void actionPerformed(ActionEvent event) { | ||
| + | if (exitAction.isEnabled()) { | ||
| + | exitAction.setEnabled(false); | ||
| + | putValue(Action.NAME, "Разрешить выход"); | ||
| + | } else { | ||
| + | exitAction.setEnabled(true); | ||
| + | putValue(Action.NAME, "Запретить выход"); | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public class testAction { | ||
| + | public static void main (String [] args) { | ||
| + | JFrame myWindow = new SimpleWindowAction(); | ||
| + | myWindow.setVisible(true); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | </source> | ||
| + | |||
| + | == 10. Swing and Threads == | ||
| + | |||
| + | <source lang="java"> | ||
| + | import java.awt.BorderLayout; | ||
| + | import java.awt.event.MouseAdapter; | ||
| + | import java.awt.event.MouseEvent; | ||
| + | import java.awt.event.MouseListener; | ||
| + | |||
| + | import javax.swing.JButton; | ||
| + | import javax.swing.JFrame; | ||
| + | import javax.swing.JOptionPane; | ||
| + | import javax.swing.JProgressBar; | ||
| + | import javax.swing.JTextField; | ||
| + | import javax.swing.SwingUtilities; | ||
| + | |||
| + | class SimpleWindowProgress extends JFrame { | ||
| + | JTextField tField; | ||
| + | static JProgressBar pBar; | ||
| + | |||
| + | SimpleWindowProgress() { | ||
| + | super("Пробное окно"); | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | setSize(400, 300); | ||
| + | JButton newButton = new JButton("Жмакни меня"); | ||
| + | |||
| + | newButton.addMouseListener(new MouseAdapter() { | ||
| + | public void mouseClicked(MouseEvent event) { | ||
| + | if (tField.getText().equals("Иван")) | ||
| + | JOptionPane.showMessageDialog(null, "Вход выполнен"); | ||
| + | else JOptionPane.showMessageDialog(null, "Вход НЕ выполнен"); | ||
| + | } | ||
| + | }); | ||
| + | |||
| + | tField = new JTextField("Привет"); | ||
| + | pBar = new JProgressBar(); | ||
| + | getContentPane().add(tField, BorderLayout.NORTH); | ||
| + | getContentPane().add(newButton, BorderLayout.SOUTH); | ||
| + | getContentPane().add(pBar); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | class Task extends Thread { | ||
| + | public void run() { | ||
| + | for (int i = 0; i <= 100; i++) { | ||
| + | final int percent = i; | ||
| + | try { | ||
| + | SwingUtilities.invokeLater(new Runnable() { | ||
| + | public void run() { | ||
| + | SimpleWindowProgress.pBar.setValue(percent); | ||
| + | } | ||
| + | }); | ||
| + | |||
| + | // НЕ ДЕЛАЙТЕ ТАК!!! | ||
| + | // SimpleWindowProgress.pBar.setValue(percent); | ||
| + | |||
| + | Thread.sleep(100); | ||
| + | } catch (InterruptedException e) { | ||
| + | e.printStackTrace(); | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public class testThreads { | ||
| + | public static void main (String [] args) { | ||
| + | JFrame myWindow = new SimpleWindowProgress(); | ||
| + | myWindow.setVisible(true); | ||
| + | Thread t = new Task(); | ||
| + | t.start(); | ||
} | } | ||
} | } | ||
</source> | </source> | ||
Текущая версия на 10:54, 25 апреля 2012
Содержание
Что почитать
1. TestFrame
import javax.swing.*;
public class testFrame {
public static void main (String [] args) {
JFrame myWindow = new JFrame("Пробное окно");
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setSize(400, 300);
myWindow.setVisible(true);
}
}
2. TestFrame2
import javax.swing.JFrame;
class SimpleWindow extends JFrame {
SimpleWindow() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
}
}
public class testFrame2 {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindow();
myWindow.setVisible(true);
}
}
3. Button
import javax.swing.JButton;
import javax.swing.JFrame;
class SimpleWindowButton extends JFrame {
SimpleWindowButton() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JButton newButton = new JButton("Жмакни меня");
getContentPane().add(newButton);
}
}
public class testFrameButton {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindowButton();
myWindow.setVisible(true);
}
}
4. Layouts
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
class SimpleWindowFlow extends JFrame {
SimpleWindowFlow() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JButton("Кнопка"));
panel.add(new JButton("+"));
panel.add(new JButton("-"));
panel.add(new JButton("Кнопка с длинной надписью"));
setContentPane(panel);
}
}
class SimpleWindowBorder extends JFrame {
SimpleWindowBorder() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
getContentPane().add(new JButton("NORTH"), BorderLayout.NORTH);
getContentPane().add(new JButton("EAST"), BorderLayout.EAST);
getContentPane().add(new JButton("SOUTH"), BorderLayout.SOUTH);
getContentPane().add(new JButton("WEST"), BorderLayout.WEST);
getContentPane().add(new JButton("В ЦЕНТР!"));
}
}
class SimpleWindowGrid extends JFrame {
SimpleWindowGrid() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 3, 5, 10));
panel.add(new JButton("Кнопка"));
panel.add(new JButton("+"));
panel.add(new JButton("-"));
panel.add(new JButton("Кнопка с длинной надписью"));
panel.add(new JButton("еще кнопка"));
setContentPane(panel);
}
}
class SimpleWindowBox extends JFrame {
SimpleWindowBox() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// setSize(400, 300);
Box box = Box.createVerticalBox();
box.add(new JButton("Кнопка"));
box.add(Box.createVerticalStrut(10));
box.add(new JButton("+"));
box.add(Box.createVerticalGlue());
JButton rightButton = new JButton("-");
rightButton.setAlignmentX(JComponent.RIGHT_ALIGNMENT);
box.add(rightButton);
box.add(Box.createVerticalStrut(10));
box.add(new JButton("Кнопка с длинной надписью"));
setContentPane(box);
pack();
}
}
class SimpleWindowManual extends JFrame {
SimpleWindowManual() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JPanel panel = new JPanel();
panel.setLayout(null);
JButton button = new JButton("Кнопка");
button.setSize(80, 30);
button.setLocation(20,20);
panel.add(button);
button = new JButton("Кнопка с длинной надписью");
button.setSize(120, 40);
button.setLocation(70,50);
panel.add(button);
setContentPane(panel);
}
}
public class testFramePanel {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindowBorder();
myWindow.setVisible(true);
}
}
5. Обрамление
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.*;
class SimpleWindowPanelBorder extends JFrame {
SimpleWindowPanelBorder() {
super("Пробное окно");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,3,5,10));
panel.add(createPanel(new TitledBorder("Рамка с заголовком"), "TitledBorder"));
panel.add(createPanel(new EtchedBorder(), "EtchedBorder"));
panel.add(createPanel(new BevelBorder(BevelBorder.LOWERED), "BevelBorder"));
panel.add(createPanel(new SoftBevelBorder(BevelBorder.RAISED), "SoftBevelBorder"));
panel.add(createPanel(new LineBorder(Color.ORANGE, 4), "LineBorder"));
panel.add(createPanel(new MatteBorder(new ImageIcon("1.gif")), "MatteBorder"));
setContentPane(panel);
pack();
}
private JPanel createPanel(Border border, String text) {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JButton(text));
panel.setBorder(new CompoundBorder(new EmptyBorder(12,12,12,12), border));
return panel;
}
}
public class testBorder {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindowPanelBorder();
myWindow.setVisible(true);
}
}
6. Компоненты
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.*;
import javax.swing.border.TitledBorder;
class SimpleWindowLabel extends JFrame {
SimpleWindowLabel() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("<html>Метка со значком и с <font size=+5>большой</font> <i>надписью</i></html>", new ImageIcon("1.gif"), SwingConstants.RIGHT);
getContentPane().add(label);
pack();
}
}
class SimpleWindowButton2 extends JFrame {
SimpleWindowButton2() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Кнопка", new ImageIcon("1.gif"));
button.setMargin(new Insets(0, 10, 20, 30));
button.setVerticalTextPosition(SwingConstants.TOP);
button.setHorizontalTextPosition(SwingConstants.LEFT);
getContentPane().add(button);
pack();
}
}
class SimpleWindowToggles extends JFrame {
SimpleWindowToggles() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon("1.gif");
// будем использовать один значок на все случаи
Box mainBox = Box.createVerticalBox();
Box box1 = Box.createVerticalBox();
JToggleButton tButton1 = new JToggleButton("Кнопка выбора 1");
JToggleButton tButton2 = new JToggleButton("Кнопка выбора 2", icon);
ButtonGroup bg = new ButtonGroup();
// создаем группу взаимного исключения
bg.add(tButton1);
bg.add(tButton2);
// сделали кнопки tButton1 и tButton2 взаимоисключающими
box1.add(tButton1);
box1.add(tButton2);
// добавили кнопки tButton1 и tButton2 на панель box1
box1.setBorder(new TitledBorder("Кнопки выбора"));
Box box2 = Box.createVerticalBox();
JCheckBox check1 = new JCheckBox("Флажок 1");
JCheckBox check2 = new JCheckBox("Флажок 2", icon);
box2.add(check1);
box2.add(check2);
// добавили флажки на панель box2
box2.setBorder(new TitledBorder("Флажки"));
Box box3 = Box.createVerticalBox();
JRadioButton rButton1 = new JRadioButton("Переключатель 1");
JRadioButton rButton2 = new JRadioButton("Переключатель 2", icon);
rButton2.setSelectedIcon(new ImageIcon("2.gif"));
bg = new ButtonGroup(); // создаем группу взаимного исключения
bg.add(rButton1);
bg.add(rButton2);
// сделали радиокнопки взаимоисключающими
box3.add(rButton1);
box3.add(rButton2);
// добавили радиокнопки на панель box3
box3.setBorder(new TitledBorder("Переключатели"));
mainBox.add(box1);
mainBox.add(box2);
mainBox.add(box3);
setContentPane(mainBox);
pack();
}
}
class SimpleWindowText extends JFrame {
SimpleWindowText() {
super("Пробное окно");
JTextField textField = new JTextField("Текстовое поле", 20);
textField.setCaretColor(Color.RED);
textField.setHorizontalAlignment(JTextField.RIGHT);
JPasswordField passwordField = new JPasswordField(20);
passwordField.setEchoChar('$');
passwordField.setText("пароль");
JTextArea textArea = new JTextArea(5, 20);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
for (int i = 0; i <= 20; i++)
textArea.append("Область для ввода текстового содержимого ");
getContentPane().add(textField, BorderLayout.NORTH);
// getContentPane().add(textArea);
getContentPane().add(new JScrollPane(textArea));
getContentPane().add(passwordField, BorderLayout.SOUTH);
pack();
}
}
public class testFrameComponents {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindowText();
myWindow.setVisible(true);
myWindow = new SimpleWindowToggles();
myWindow.setVisible(true);
}
}
7. MouseListener
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
class SimpleWindowButtonListener extends JFrame {
JTextField tField;
class MouseL implements MouseListener {
public void mouseClicked(MouseEvent event) {
if (tField.getText().equals("Иван"))
JOptionPane.showMessageDialog(null, "Привет");
else JOptionPane.showMessageDialog(null, "Пока!");
}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mousePressed(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
}
SimpleWindowButtonListener() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JButton newButton = new JButton("Жмакни меня");
newButton.addMouseListener(new MouseL());
newButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
if (tField.getText().equals("Иван"))
JOptionPane.showMessageDialog(null, "Вход выполнен1");
else JOptionPane.showMessageDialog(null, "Вход НЕ выполнен1");
}
});
tField = new JTextField("Привет");
getContentPane().add(tField, BorderLayout.NORTH);
getContentPane().add(newButton, BorderLayout.SOUTH);
}
}
public class testMouseListener {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindowButtonListener();
myWindow.setVisible(true);
}
}
8. ActionListener
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
class SimpleWindowButtonListener2 extends JFrame {
JTextField tField;
SimpleWindowButtonListener2() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JButton newButton = new JButton("Жмакни меня");
newButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (tField.getText().equals("Иван"))
JOptionPane.showMessageDialog(null, "Вход выполнен2");
else JOptionPane.showMessageDialog(null, "Вход НЕ выполнен2");
}
});
tField = new JTextField("Привет");
getContentPane().add(tField, BorderLayout.NORTH);
getContentPane().add(newButton, BorderLayout.SOUTH);
}
}
public class testActionListener {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindowButtonListener2();
myWindow.setVisible(true);
}
}
9. Action
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
class SimpleWindowAction extends JFrame {
private ExitAction exitAction;
SimpleWindowAction(){
super("Окно с меню");
setDefaultCloseOperation(EXIT_ON_CLOSE);
exitAction = new ExitAction();
DeactivateAction deactivateAction = new DeactivateAction();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Файл");
fileMenu.add(new JMenuItem("Новый"));
fileMenu.addSeparator();
fileMenu.add(deactivateAction);
fileMenu.add(exitAction);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar("Панель инструментов");
toolBar.add(exitAction);
toolBar.add(deactivateAction);
getContentPane().add(toolBar, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.add(new JButton(exitAction));
panel.add(new JButton(deactivateAction));
getContentPane().add(panel); setSize(250,250);
}
class ExitAction extends AbstractAction {
ExitAction(){
putValue(Action.NAME, "Выйти");
putValue(Action.SHORT_DESCRIPTION, "Программа перестанет работать, а окно исчезнет с экрана.");
putValue(Action.SMALL_ICON, new ImageIcon("2.gif"));
}
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
}
class DeactivateAction extends AbstractAction {
DeactivateAction(){
putValue(Action.NAME, "Запретить выход");
putValue(Action.SMALL_ICON, new ImageIcon("1.gif"));
}
public void actionPerformed(ActionEvent event) {
if (exitAction.isEnabled()) {
exitAction.setEnabled(false);
putValue(Action.NAME, "Разрешить выход");
} else {
exitAction.setEnabled(true);
putValue(Action.NAME, "Запретить выход");
}
}
}
}
public class testAction {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindowAction();
myWindow.setVisible(true);
}
}
10. Swing and Threads
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
class SimpleWindowProgress extends JFrame {
JTextField tField;
static JProgressBar pBar;
SimpleWindowProgress() {
super("Пробное окно");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JButton newButton = new JButton("Жмакни меня");
newButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
if (tField.getText().equals("Иван"))
JOptionPane.showMessageDialog(null, "Вход выполнен");
else JOptionPane.showMessageDialog(null, "Вход НЕ выполнен");
}
});
tField = new JTextField("Привет");
pBar = new JProgressBar();
getContentPane().add(tField, BorderLayout.NORTH);
getContentPane().add(newButton, BorderLayout.SOUTH);
getContentPane().add(pBar);
}
}
class Task extends Thread {
public void run() {
for (int i = 0; i <= 100; i++) {
final int percent = i;
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleWindowProgress.pBar.setValue(percent);
}
});
// НЕ ДЕЛАЙТЕ ТАК!!!
// SimpleWindowProgress.pBar.setValue(percent);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class testThreads {
public static void main (String [] args) {
JFrame myWindow = new SimpleWindowProgress();
myWindow.setVisible(true);
Thread t = new Task();
t.start();
}
}