Java Swing Первые программы

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
(Наш первый примерчик)
(нарушало авторские права)
 
(9 промежуточных версий не показаны.)
Строка 1: Строка 1:
-
В этой главе мы напишем нашу первую программу исползуя Swing. Пример будет весьма простеньким. Будет охвачена лишь некоторая часть основных функциональных возможностей.
 
-
 
-
== Наш первый примерчик ==
 
-
В нашем первом примере мы покажем основное окно.
 
-
<source lang="cpp">
 
-
import javax.swing.JFrame;
 
-
 
-
 
-
public class Simple extends JFrame {
 
-
 
-
    public Simple() {
 
-
 
-
        setSize(300, 200);
 
-
        setTitle("Simple");
 
-
        setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
  }
 
-
 
-
    public static void main(String[] args) {
 
-
 
-
        Simple simple = new Simple();
 
-
        simple.setVisible(true);
 
-
 
-
    }
 
-
}
 
-
</source>
 
-
Несмотря на то, что приведенный фрагмент кода достаточно мал, окно приложения может делать достаточно много. Оно может изменять размер, максимизироваться, минимизироваться. При этом все сложности реализации сокрыты от прикладного разработчика.
 
-
<source lang="cpp">
 
-
import javax.swing.JFrame;
 
-
</source>
 
-
Эта строчка кода осуществляет импорт класса JFrame из пакета javax.swing.JFrame. ''Этого можно было бы и не делать, но тогда приходилось бы каждый раз писать javax.swing.JFrame вместо JFrame - прим. переводчика.''
 
-
В данном случае, JFrame - это контейнер, который используется для размещения на нем других виджетов.
 
-
<source lang="cpp">
 
-
setSize(300, 200);
 
-
setTitle("Simple");
 
-
</source>
 
-
Этот фрагмент коде изменяет размер экрана, устанавливая его равным 300 пикселям по ширине и 200 пикселям по высоте. Также в качестве заголовка окна устанавливается "Simple".
 
-
<source lang="cpp">
 
-
setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
</source>
 
-
Этот метод будет закрывать окно, если мы нажмем на кнопку закрытия окна ("крестик"). По умолчанию ничего не происходит.
 
-
''Примечание переводчика: Это не совсем так. По умолчанию приложение может и не завершить работу по нажатию на "крестик", но само окно может исчезнуть с экрана''
 
-
 
-
[[image: java_swing_simple.jpg | center]]
 
-
 
-
== Centering window on the screen==
 
-
По умолчанию, окно, отображаемое на экране, расположено не по центру. В большинстве случаев оно будет расположенов левом верхнем углу. Следующий фрагмент кода реализует окно, расположенное строго по центру экрана, вне зависимости от разрешения последнего.
 
-
<source lang="cpp">
 
-
import java.awt.Dimension;
 
-
import java.awt.Toolkit;
 
-
 
-
import javax.swing.JFrame;
 
-
 
-
public class CenterOnScreen extends JFrame {
 
-
 
-
    public CenterOnScreen() {
 
-
 
-
        setSize(300, 200);
 
-
        setTitle("CenterOnScreen");
 
-
        setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
 
-
        Toolkit toolkit = getToolkit();
 
-
        Dimension size = toolkit.getScreenSize();
 
-
        setLocation(size.width/2 - getWidth()/2,
 
-
size.height/2 - getHeight()/2);
 
-
    }
 
-
 
-
    public static void main(String[] args) {
 
-
 
-
        CenterOnScreen cos = new CenterOnScreen();
 
-
        cos.setVisible(true);
 
-
 
-
    }
 
-
}
 
-
</source>
 
-
Для центрирования окна на экране мы сначала должны узнать разрешение монитора. Для этого мы используем класс <i>Toolkit</i>.
 
-
<source lang="cpp">
 
-
Toolkit toolkit = getToolkit();
 
-
Dimension size = toolkit.getScreenSize();
 
-
</source>
 
-
We get the toolkit and figure out the screen size.
 
-
<source lang="cpp">
 
-
setLocation(size.width/2 - getWidth()/2, size.height/2 - getHeight()/2);
 
-
</source>
 
-
Для непосредственно центрирования окна, вызовем метод <i>setLocation()</i>.
 
-
 
-
== Два Button'а (Кнопки) ==
 
-
В нашем следующем примере мы создадим и покажем два объекта типа Button. Первая кнопка будет отвечать за воспроиздедение звукового сигнала, а вторая -  за закрытие окна.
 
-
<source lang="cpp">
 
-
import java.awt.Dimension;
 
-
import java.awt.Toolkit;
 
-
import java.awt.event.ActionEvent;
 
-
import java.awt.event.ActionListener;
 
-
 
-
import javax.swing.JButton;
 
-
import javax.swing.JFrame;
 
-
import javax.swing.JPanel;
 
-
 
-
 
-
public class Buttons extends JFrame {
 
-
 
-
    private Toolkit toolkit;
 
-
 
-
    public Buttons() {
 
-
 
-
        setTitle("Buttons");
 
-
        setSize(300, 200);
 
-
 
-
        toolkit = getToolkit();
 
-
        Dimension size = toolkit.getScreenSize();
 
-
        setLocation((size.width - getWidth())/2, (size.height - getHeight())/2);
 
-
        setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
 
-
        JPanel panel = new JPanel();
 
-
        getContentPane().add(panel);
 
-
 
-
panel.setLayout(null);
 
-
 
-
        JButton beep = new JButton("Beep");
 
-
        beep.setBounds(150, 60, 80, 30);
 
-
        beep.addActionListener(new ActionListener() {
 
-
            public void actionPerformed(ActionEvent event) {
 
-
                toolkit.beep();
 
-
            }
 
-
        });
 
-
 
-
      JButton close = new JButton("Close");
 
-
      close.setBounds(50, 60, 80, 30);
 
-
      close.addActionListener(new ActionListener() {
 
-
          public void actionPerformed(ActionEvent event) {
 
-
              System.exit(0);
 
-
          }
 
-
      });
 
-
 
-
        panel.add(beep);
 
-
        panel.add(close);
 
-
 
-
    }
 
-
 
-
    public static void main(String[] args) {
 
-
 
-
        Buttons buttons = new Buttons();
 
-
        buttons.setVisible(true);
 
-
 
-
    }
 
-
}
 
-
</source>
 
-
In this example, we will see two new topics. Layout management and event handling. They will be touched only briefly. Both of the topics will have their own chapter.
 
-
<source lang="cpp">
 
-
JPanel panel = new JPanel();
 
-
getContentPane().add(panel);
 
-
</source>
 
-
We create a <i>JPanel</i> component. It is a generic lightweight container. We add the JPanel to the JFrame.
 
-
<source lang="cpp">
 
-
panel.setLayout(null);
 
-
</source>
 
-
 
-
By default, the JPanel has a <i>FlowLayout</i> manager. The layout manager is used to place widgets onto the containers. If we call <i>setLayout(null)</i> we can position our components absolutely. For this, we use the  <i>setBounds()</i> method.
 
-
<source lang="cpp">
 
-
JButton beep = new JButton("Beep");
 
-
beep.setBounds(150, 60, 80, 30);
 
-
beep.addActionListener(new ActionListener() {
 
-
    public void actionPerformed(ActionEvent event) {
 
-
        toolkit.beep();
 
-
    }
 
-
});
 
-
</source>
 
-
Here we create a button. We position it by calling the <i>setBounds()</i> method. Then we add an action listener. The action listener will be called, when we perform an action on the button. In our case, if we click on the button. The beep button will play a simple beep sound.
 
-
<source lang="cpp">
 
-
System.exit(0);
 
-
</source>
 
-
The close button will exit the application. For this, we call the <i>System.exit()</i> method.
 
-
<source lang="cpp">
 
-
panel.add(beep);
 
-
panel.add(close);
 
-
</source>
 
-
In order to show the buttons, we must add them to the panel.
 
-
 
-
[[image: java_swing_buttons.jpg  | center]]
 
-
 
-
== A tooltip ==
 
-
Tooltips are part of the internal application's help system. The Swing shows a small rectangular window, if we hover a mouse pointer over an object.
 
-
<source lang="cpp">
 
-
import java.awt.Dimension;
 
-
import java.awt.Toolkit;
 
-
 
-
import javax.swing.JButton;
 
-
import javax.swing.JFrame;
 
-
import javax.swing.JPanel;
 
-
 
-
 
-
public class Tooltip extends JFrame {
 
-
 
-
    private Toolkit toolkit;
 
-
 
-
    public Tooltip() {
 
-
 
-
        setTitle("Tooltip");
 
-
        setSize(300, 200);
 
-
 
-
        toolkit = getToolkit();
 
-
        Dimension size = toolkit.getScreenSize();
 
-
        setLocation((size.width - getWidth())/2, (size.height - getHeight())/2);
 
-
        setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
 
-
        JPanel panel = new JPanel();
 
-
        getContentPane().add(panel);
 
-
 
-
        panel.setLayout(null);
 
-
        panel.setToolTipText("A Panel container");
 
-
 
-
        JButton button = new JButton("Button");
 
-
        button.setBounds(100, 60, 80, 30);
 
-
        button.setToolTipText("A button component");
 
-
 
-
        panel.add(button);
 
-
 
-
    }
 
-
 
-
    public static void main(String[] args) {
 
-
 
-
        Tooltip tooltip = new Tooltip();
 
-
        tooltip.setVisible(true);
 
-
 
-
    }
 
-
}
 
-
</source>
 
-
In the example, we set the tooltip for the frame and the button.
 
-
<source lang="cpp">
 
-
panel.setToolTipText("A Panel container");
 
-
</source>
 
-
To enable a tooltip, we call the <i>setTooltipText()</i> method.
 
-
 
-
[[image: java_swing_tooltip.jpg | center]]
 
-
 
-
[[Категория:Java]]
 

Текущая версия на 11:26, 7 апреля 2009