Code
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.net.URL;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JButtonDemo extends JPanel implements ActionListener {
protected static JButton jbnLeft, jbnMiddle, jbnRight;
public JButtonDemo() {
// Create Icons that can be used with the jButtons
ImageIcon leftButtonIcon = createImageIcon("rightarrow.JPG");
ImageIcon middleButtonIcon = createImageIcon("java-swing-tutorial.JPG");
ImageIcon rightButtonIcon = createImageIcon("leftarrow.JPG");
jbnLeft = new JButton("Disable centre button", leftButtonIcon);
jbnLeft.setVerticalTextPosition(AbstractButton.CENTER);
jbnLeft.setHorizontalTextPosition(AbstractButton.LEADING);
jbnLeft.setMnemonic(KeyEvent.VK_D);
// Alt-D clicks the button
jbnLeft.setActionCommand("disable");
jbnLeft.setToolTipText("disable the Centre button."); // Adding Tool
// tips
jbnMiddle = new JButton("Centre button", middleButtonIcon);
jbnMiddle.setVerticalTextPosition(AbstractButton.BOTTOM);
jbnMiddle.setHorizontalTextPosition(AbstractButton.CENTER);
jbnMiddle.setMnemonic(KeyEvent.VK_M);
// Alt-M clicks the button
jbnMiddle.setToolTipText("Centre button");
jbnRight = new JButton("Enable centre button", rightButtonIcon);
// Use the default text position of CENTER, TRAILING (RIGHT).
jbnRight.setMnemonic(KeyEvent.VK_E);
// Alt-E clicks the button
jbnRight.setActionCommand("enable");
jbnRight.setEnabled(false);
// Disable the Button at creation time
// Listen for actions on Left and Roght Buttons
jbnLeft.addActionListener(this);
jbnRight.addActionListener(this);
jbnRight.setToolTipText("Enable the Centre button.");
// Add Components to the frame, using the default FlowLayout.
add(jbnLeft);
add(jbnMiddle);
add(jbnRight);
}
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
jbnMiddle.setEnabled(false);
jbnLeft.setEnabled(false);
jbnRight.setEnabled(true);
} else {
jbnMiddle.setEnabled(true);
jbnLeft.setEnabled(true);
jbnRight.setEnabled(false);
}
}
// Returns an ImageIcon, or null if the path was invalid.
protected static ImageIcon createImageIcon(String path) {
URL imgURL = JButtonDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find image in system: " + path);
return null;
}
}
// Create the GUI and show it.
private static void createGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the frame.
JFrame frame = new JFrame("jButton usage demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JButtonDemo buttonContentPane = new JButtonDemo();
buttonContentPane.setOpaque(true); // content panes must be opaque
frame.getRootPane().setDefaultButton(jbnLeft);
frame.setContentPane(buttonContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
}
Добавлено (2011-10-19, 20:04:37)
---------------------------------------------
Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
import java.text.*;
public class DateComboBoxDemo extends JPanel {
static JFrame frame;
JLabel jlbResult;
String datePattern_Current;
public DateComboBoxDemo() {
String[] datePatterns = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy",
"yyyy.MM.dd G 'at' hh:mm:ss z", "EEE, MMM d, ''yy",
"h:mm a", "H:mm:ss:SSS", "K:mm a,z",
"yyyy.MMMMM.dd GGG hh:mm aaa" };
datePattern_Current = datePatterns[0];
// Set up the UI for selecting a pattern.
JLabel jlbHeading = new JLabel(
"Enter Date pattern /Select from list:");
JComboBox patternList = new JComboBox(datePatterns);
patternList.setEditable(true);
patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
patternList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcmbDates = (JComboBox) e.getSource();
String seletedDate = (String) jcmbDates.getSelectedItem();
datePattern_Current = seletedDate;
showDateinLabel();
}
});
// Create the UI for displaying result
JLabel jlbResultHeading = new JLabel("Current Date/Time",
JLabel.LEFT);
jlbResult = new JLabel(" ");
jlbResult.setForeground(Color.black);
jlbResult.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.black), BorderFactory
.createEmptyBorder(5, 5, 5, 5)));
// Lay out everything
JPanel jpnDate = new JPanel();
jpnDate.setLayout(new BoxLayout(jpnDate, BoxLayout.Y_AXIS));
jpnDate.add(jlbHeading);
jpnDate.add(patternList);
JPanel jpnResults = new JPanel();
jpnResults.setLayout(new GridLayout(0, 1));
jpnResults.add(jlbResultHeading);
jpnResults.add(jlbResult);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
jpnDate.setAlignmentX(Component.LEFT_ALIGNMENT);
jpnResults.setAlignmentX(Component.LEFT_ALIGNMENT);
add(jpnDate);
add(Box.createRigidArea(new Dimension(0, 10)));
add(jpnResults);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
showDateinLabel();
} // constructor
/** Formats and displays today's date. */
public void showDateinLabel() {
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(
datePattern_Current);
try {
String dateString = formatter.format(today);
jlbResult.setForeground(Color.black);
jlbResult.setText(dateString);
} catch (IllegalArgumentException e) {
jlbResult.setForeground(Color.red);
jlbResult.setText("Error: " + e.getMessage());
}
}
public static void main(String s[]) {
frame = new JFrame("JComboBox Usage Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new DateComboBoxDemo());
frame.pack();
frame.setVisible(true);
}
}
Добавлено (2011-10-19, 20:21:30)
---------------------------------------------
Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
//Used Action Listner for JMenuItem & JRadioButtonMenuItem
//Used Item Listner for JCheckBoxMenuItem
public class JMenuDemo implements ActionListener, ItemListener {
JTextArea jtAreaOutput;
JScrollPane jspPane;
public JMenuBar createJMenuBar() {
JMenuBar mainMenuBar;
JMenu menu1, menu2, submenu;
JMenuItem plainTextMenuItem, textIconMenuItem, iconMenuItem, subMenuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
ImageIcon icon = createImageIcon("jmenu.jpg");
mainMenuBar = new JMenuBar();
menu1 = new JMenu("Menu 1");
menu1.setMnemonic(KeyEvent.VK_M);
mainMenuBar.add(menu1);
// Creating the MenuItems
plainTextMenuItem = new JMenuItem("Menu item with Plain Text",
KeyEvent.VK_T);
// can be done either way for assigning shortcuts
// menuItem.setMnemonic(KeyEvent.VK_T);
// Accelerators, offer keyboard shortcuts to bypass navigating the menu
// hierarchy.
plainTextMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
plainTextMenuItem.addActionListener(this);
menu1.add(plainTextMenuItem);
textIconMenuItem = new JMenuItem("Menu Item with Text & Image",
icon);
textIconMenuItem.setMnemonic(KeyEvent.VK_B);
textIconMenuItem.addActionListener(this);
menu1.add(textIconMenuItem);
// Menu Item with just an Image
iconMenuItem = new JMenuItem(icon);
iconMenuItem.setMnemonic(KeyEvent.VK_D);
iconMenuItem.addActionListener(this);
menu1.add(iconMenuItem);
menu1.addSeparator();
// Radio Button Menu items follow a seperator
ButtonGroup itemGroup = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem(
"Menu Item with Radio Button");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
itemGroup.add(rbMenuItem);
rbMenuItem.addActionListener(this);
menu1.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem(
"Menu Item 2 with Radio Button");
itemGroup.add(rbMenuItem);
rbMenuItem.addActionListener(this);
menu1.add(rbMenuItem);
menu1.addSeparator();
// Radio Button Menu items follow a seperator
cbMenuItem = new JCheckBoxMenuItem("Menu Item with check box");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
cbMenuItem.addItemListener(this);
menu1.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Menu Item 2 with check box");
cbMenuItem.addItemListener(this);
menu1.add(cbMenuItem);
menu1.addSeparator();
// Sub Menu follows a seperator
submenu = new JMenu("Sub Menu");
submenu.setMnemonic(KeyEvent.VK_S);
subMenuItem = new JMenuItem("Sub MenuItem 1");
subMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
ActionEvent.CTRL_MASK));
subMenuItem.addActionListener(this);
submenu.add(subMenuItem);
subMenuItem = new JMenuItem("Sub MenuItem 2");
submenu.add(subMenuItem);
subMenuItem.addActionListener(this);
menu1.add(submenu);
// Build second menu in the menu bar.
menu2 = new JMenu("Menu 2");
menu2.setMnemonic(KeyEvent.VK_N);
mainMenuBar.add(menu2);
return mainMenuBar;
}
public Container createContentPane() {
// Create the content-pane-to-be.
JPanel jplContentPane = new JPanel(new BorderLayout());
jplContentPane.setLayout(new BorderLayout());// Can do it either way
// to set layout
jplContentPane.setOpaque(true);
// Create a scrolled text area.
jtAreaOutput = new JTextArea(5, 30);
jtAreaOutput.setEditable(false);
jspPane = new JScrollPane(jtAreaOutput);
// Add the text area to the content pane.
jplContentPane.add(jspPane, BorderLayout.CENTER);
return jplContentPane;
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = JMenuDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find image file: " + path);
return null;
}
}
private static void createGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
JFrame frame = new JFrame("JMenu Usage Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuDemo app = new JMenuDemo();
frame.setJMenuBar(app.createJMenuBar());
frame.setContentPane(app.createContentPane());
frame.setSize(500, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem) (e.getSource());
String s = "Menu Item source: " + source.getText()
+ " (an instance of " + getClassName(source) + ")";
jtAreaOutput.append(s + "\n");
jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()
.getLength());
}
public void itemStateChanged(ItemEvent e) {
JMenuItem source = (JMenuItem) (e.getSource());
String s = "Menu Item source: "
+ source.getText()
+ " (an instance of "
+ getClassName(source)
+ ")"
+ "\n"
+ " State of check Box: "
+ ((e.getStateChange() == ItemEvent.SELECTED) ? "selected"
: "unselected");
jtAreaOutput.append(s + "\n");
jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()
.getLength());
}
// Returns the class name, no package info
protected String getClassName(Object o) {
String classString = o.getClass().getName();
int dotIndex = classString.lastIndexOf(".");
return classString.substring(dotIndex + 1); // Returns only Class name
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
}
Добавлено (2011-10-19, 20:34:42)
---------------------------------------------
Code
import javax.swing.JInternalFrame;
import javax.swing.JDesktopPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JFrame;
import java.awt.event.*;
import java.awt.*;
public class JInternalFrameDemo extends JFrame {
JDesktopPane jdpDesktop;
static int openFrameCount = 0;
public JInternalFrameDemo() {
super("JInternalFrame Usage Demo");
// Make the main window positioned as 50 pixels from each edge of the
// screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2,
screenSize.height - inset * 2);
// Add a Window Exit Listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Create and Set up the GUI.
jdpDesktop = new JDesktopPane();
// A specialized layered pane to be used with JInternalFrames
createFrame(); // Create first window
setContentPane(jdpDesktop);
setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Frame");
menu.setMnemonic(KeyEvent.VK_N);
JMenuItem menuItem = new JMenuItem("New IFrame");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createFrame();
}
});
menu.add(menuItem);
menuBar.add(menu);
return menuBar;
}
protected void createFrame() {
MyInternalFrame frame = new MyInternalFrame();
frame.setVisible(true);
// Every JInternalFrame must be added to content pane using JDesktopPane
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String[] args) {
JInternalFrameDemo frame = new JInternalFrameDemo();
frame.setVisible(true);
}
class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame() {
super("IFrame #" + (++openFrameCount), true, // resizable
true, // closable
true, // maximizable
true);// iconifiable
setSize(300, 300);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition
* openFrameCount);
}
}
}
Добавлено (2011-10-19, 20:36:23)
---------------------------------------------
Code
import javax.swing.JInternalFrame;
import javax.swing.JDesktopPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JFrame;
import java.awt.event.*;
import java.awt.*;
public class JInternalFrameDemo extends JFrame {
JDesktopPane jdpDesktop;
static int openFrameCount = 0;
public JInternalFrameDemo() {
super("JInternalFrame Usage Demo");
// Make the main window positioned as 50 pixels from each edge of the
// screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2,
screenSize.height - inset * 2);
// Add a Window Exit Listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Create and Set up the GUI.
jdpDesktop = new JDesktopPane();
// A specialized layered pane to be used with JInternalFrames
createFrame(); // Create first window
setContentPane(jdpDesktop);
setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Frame");
menu.setMnemonic(KeyEvent.VK_N);
JMenuItem menuItem = new JMenuItem("New IFrame");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createFrame();
}
});
menu.add(menuItem);
menuBar.add(menu);
return menuBar;
}
protected void createFrame() {
MyInternalFrame frame = new MyInternalFrame();
frame.setVisible(true);
// Every JInternalFrame must be added to content pane using JDesktopPane
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String[] args) {
JInternalFrameDemo frame = new JInternalFrameDemo();
frame.setVisible(true);
}
class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame() {
super("IFrame #" + (++openFrameCount), true, // resizable
true, // closable
true, // maximizable
true);// iconifiable
setSize(300, 300);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition
* openFrameCount);
}
}
}
Добавлено (2011-10-19, 20:37:06)
---------------------------------------------
Code
import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class JTabbedPaneDemo extends JPanel {
public JTabbedPaneDemo() {
ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG");
JTabbedPane jtbExample = new JTabbedPane();
JPanel jplInnerPanel1 = createInnerPanel("Tab 1 Contains Tooltip and Icon");
jtbExample.addTab("One", icon, jplInnerPanel1, "Tab 1");
jtbExample.setSelectedIndex(0);
JPanel jplInnerPanel2 = createInnerPanel("Tab 2 Contains Icon only");
jtbExample.addTab("Two", icon, jplInnerPanel2);
JPanel jplInnerPanel3 = createInnerPanel("Tab 3 Contains Tooltip and Icon");
jtbExample.addTab("Three", icon, jplInnerPanel3, "Tab 3");
JPanel jplInnerPanel4 = createInnerPanel("Tab 4 Contains Text only");
jtbExample.addTab("Four", jplInnerPanel4);
// Add the tabbed pane to this panel.
setLayout(new GridLayout(1, 1));
add(jtbExample);
}
protected JPanel createInnerPanel(String text) {
JPanel jplPanel = new JPanel();
JLabel jlbDisplay = new JLabel(text);
jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
jplPanel.setLayout(new GridLayout(1, 1));
jplPanel.add(jlbDisplay);
return jplPanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("TabbedPane Source Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.getContentPane().add(new JTabbedPaneDemo(),
BorderLayout.CENTER);
frame.setSize(400, 125);
frame.setVisible(true);
}
}
Добавлено (2011-10-19, 20:39:42)
---------------------------------------------
Code
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
public class JListDemo extends JFrame {
JList list;
String[] listColorNames = { "black", "blue", "green", "yellow",
"white" };
Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN,
Color.YELLOW, Color.WHITE };
Container contentpane;
public JListDemo() {
super("List Source Demo");
contentpane = getContentPane();
contentpane.setLayout(new FlowLayout());
list = new JList(listColorNames);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
contentpane.add(new JScrollPane(list));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
contentpane.setBackground(listColorValues[list
.getSelectedIndex()]);
}
});
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
JListDemo test = new JListDemo();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Добавлено (2011-10-19, 20:47:36)
---------------------------------------------
Code
import javax.swing.*;
import java.awt.event.*;
public class JWindowDemo extends JWindow {
private int X = 0;
private int Y = 0;
public JWindowDemo() {
setBounds(60, 60, 100, 100);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); // An Exit Listener
}
});
// Print (X,Y) coordinates on Mouse Click
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
X = e.getX();
Y = e.getY();
System.out.println("The (X,Y) coordinate of window is ("
+ X + "," + Y + ")");
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
setLocation(getLocation().x + (e.getX() - X),
getLocation().y + (e.getY() - Y));
}
});
setVisible(true);
}
public static void main(String[] args) {
new JWindowDemo();
}
}