340 likes | 640 Views
Swing. štandard od Java 2 „nadmnožina awt“ – aj ke ď len voľne chápané komponenty sa volajú Jxxxx vlastný look-and-feel Nemie šajte awt a swing komponenty javax.swing javax.swing.event …. import javax.swing.*;. awt vs. swing. JButton. import java.applet.*; import javax.swing.*;
E N D
Swing • štandard od Java 2 • „nadmnožina awt“ – aj keď len voľne chápané • komponenty sa volajú Jxxxx • vlastný look-and-feel • Nemiešajte awt a swing komponenty • javax.swing • javax.swing.event • ….
JButton import java.applet.*; import javax.swing.*; public class JButtonDemo extends Applet { JButton b1 = new JButton("JButton 1"), b2 = new JButton("JButton 2"); JTextField t = new JTextField(20); public void init() { ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e){ String name = ((JButton)e.getSource()).getText(); t.setText(name + " Pressed"); } }; b1.addActionListener(al); add(b1); b2.addActionListener(al); add(b2); add(t); }
JFrame public static void main(String args[]) { JButtonDemo applet = new JButtonDemo(); JFrame frame = new JFrame("TextAreaNew"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ System.exit(0); } }); frame.getContentPane().add(applet,BorderLayout.CENTER); frame.setSize(300,100); applet.init(); applet.start(); frame.setVisible(true); } }
Buttoniáda public Buttons() { add(jb); add(new JToggleButton("JToggleButton")); add(new JCheckBox("JCheckBox")); add(new JRadioButton("JRadioButton")); JPanel jp = new JPanel(); jp.setBorder(new TitledBorder("Directions")); jp.add(up); jp.add(down); jp.add(left); jp.add(right); add(jp); } } public class Buttons extends JPanel { JButton jb = new JButton("JButton"); BasicArrowButton up = new BasicArrowButton( BasicArrowButton.NORTH), down = new BasicArrowButton( BasicArrowButton.SOUTH), right = new BasicArrowButton( BasicArrowButton.EAST), left = new BasicArrowButton( BasicArrowButton.WEST);
Grupáky public class ButtonGroups extends JPanel { static String[] ids = { "zelen", "gula", "cerven", "zalud" }; static JPanel makeBPanel(Class bClass, String[] ids) { ButtonGroup bg = new ButtonGroup(); JPanel jp = new JPanel(); String title = bClass.getName(); title = title.substring( title.lastIndexOf('.') + 1); jp.setBorder(new TitledBorder(title)); for(int i = 0; i < ids.length; i++) { AbstractButton ab = new JButton("failed"); try { Constructor ctor = bClass.getConstructor(new Class[] { String.class }); ab = (AbstractButton)ctor.newInstance(new Object[]{ids[i]}); } catch(Exception ex) { System.out.println("can't create " + bClass); } bg.add(ab); jp.add(ab); } return jp; } public ButtonGroups() { add(makeBPanel(JButton.class, ids)); add(makeBPanel(JToggleButton.class, ids)); add(makeBPanel(JCheckBox.class, ids)); add(makeBPanel(JRadioButton.class, ids)); } }
public interface Icon { void paintIcon(Component c, Graphics g, int x, int y); int getIconWidth(); int getIconHeight(); } Ikony ImageIcon implements Icon Icon xSign = new ImageIcon("x.gif"); Icon oSign = new ImageIcon("o.gif"); java.net.URL imgURL = ButtonDemo.class.getResource("images/right.gif"); ImageIcon leftButtonIcon = new ImageIcon(imgURL); public class RedOval implements Icon { public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(Color.red); g.drawOval (x, y, getIconWidth(), getIconHeight()); } public int getIconWidth() { return 10; } public int getIconHeight() { return 10; } }
ButtIkony ImageIcon leftButtonIcon = new ImageIcon(....); . . . b1 = new JButton("Disable middle button", leftButtonIcon); b1.setVerticalTextPosition(AbstractButton.CENTER); b1.setHorizontalTextPosition(AbstractButton.LEADING); b1.setMnemonic(KeyEvent.VK_D); b1.setActionCommand("disable"); b1.addActionListener(this); b1.setToolTipText("Click this button to disable the middlebutton."); public void actionPerformed(ActionEvent e) { if ("disable".equals(e.getActionCommand())) { b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } . . . .
Ikony import java.awt.event.*; import javax.swing.*; public class Faces extends JPanel { static Icon[] faces = { new ImageIcon("face0.gif"), new ImageIcon("face1.gif"), new ImageIcon("face2.gif"), new ImageIcon("face3.gif"), new ImageIcon("face4.gif"), }; JButton jb = new JButton("JButton", faces[3]), jb2 = new JButton("Disable"); boolean mad = false; public Faces() { jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ if(mad) { jb.setIcon(faces[3]); mad = false; } else { jb.setIcon(faces[0]); mad = true; } jb.setVerticalAlignment(JButton.TOP); jb.setHorizontalAlignment(JButton.LEFT); } }); jb.setRolloverEnabled(true); jb.setRolloverIcon(faces[1]); jb.setPressedIcon(faces[2]); jb.setDisabledIcon(faces[4]); jb.setToolTipText("Yow!"); add(jb); jb2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ if(jb.isEnabled()) { jb.setEnabled(false); jb2.setText("Enable"); } else { jb.setEnabled(true); jb2.setText("Disable"); } } }); add(jb2); }
JLabel public class LabelPanel extends JPanel { public LabelPanel() { JLabel plainLabel = new JLabel("Plain Small Label"); add(plainLabel); JLabel fancyLabel = new JLabel("Fancy Big Label"); Font fancyFont =new Font("Serif", Font.BOLD | Font.ITALIC, 32); fancyLabel.setFont(fancyFont); Icon tigerIcon = new ImageIcon("SmallTiger.gif"); fancyLabel.setIcon(tigerIcon); fancyLabel.setHorizontalAlignment(JLabel.RIGHT); add(fancyLabel); } } String labelText = "<html><FONT COLOR=RED>Red</FONT> and " + "<FONT COLOR=BLUE>Blue</FONT> Text</html>"; JLabel coloredLabel = new JLabel(labelText, Label.CENTER);
Border public class Borders extends JPanel { static JPanel showBorder(Border b) { JPanel jp = new JPanel(); jp.setLayout(new BorderLayout()); String nm = b.getClass().toString(); nm = nm.substring(nm.lastIndexOf('.') + 1); jp.add(new JLabel(nm, JLabel.CENTER), BorderLayout.CENTER); jp.setBorder(b); return jp; } public Borders() { setLayout(new GridLayout(2,4)); add(showBorder(new TitledBorder("Title"))); add(showBorder(new EtchedBorder())); add(showBorder(new LineBorder(Color.blue))); add(showBorder( new MatteBorder(5,5,30,30,Color.green))); add(showBorder( new BevelBorder(BevelBorder.RAISED))); add(showBorder( new SoftBevelBorder(BevelBorder.LOWERED))); add(showBorder(new CompoundBorder( new EtchedBorder(), new LineBorder(Color.red)))); } }
JList import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class ListCombo extends JPanel { JComboBox combo; JList list; public ListCombo() { setLayout(new GridLayout(2,1)); list = new JList(ButtonGroups.ids); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int[] a = list.getSelectedIndices(); for(int i=0; i < list.getSelectedIndices().length; i++) System.out.println(list.getSelectedIndices()[i]); }}); add(new JScrollPane(list));
JList public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (list.getSelectedIndex() == -1) { … } else { … } } } list = new JList(data); // data::Object[] list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.HORIZONTAL_WRAP); ... JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(250, 80));
JCombo combo = new JComboBox(); for(int i = 0; i < 100; i++) combo.addItem(Integer.toString(i)); add(combo); combo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { System.out.println(combo.getSelectedItem()); }}); }
Slider static final int FPS_MIN = 0; static final int FPS_MAX = 30; static final int FPS_INIT = 15; //init JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL, FPS_MIN, FPS_MAX, FPS_INIT); framesPerSecond.addChangeListener(this); framesPerSecond.setMajorTickSpacing(10); framesPerSecond.setMinorTickSpacing(1); framesPerSecond.setPaintTicks(true); framesPerSecond.setPaintLabels(true); public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int fps = (int)source.getValue(); if (fps == 0) { if (!frozen) stopAnimation(); } else { delay = 1000 / fps; timer.setDelay(delay); timer.setInitialDelay(delay * 10); if (frozen) startAnimation(); } } }
ProgressBar public void actionPerformed(ActionEvent evt) { progressBar.setValue(task.getCurrent()); String s = task.getMessage(); if (s != null) { taskOutput.append(s + newline); taskOutput.setCaretPosition( taskOutput.getDocument().getLength()); } if (task.isDone()) { Toolkit.getDefaultToolkit().beep(); timer.stop(); startButton.setEnabled(true); setCursor(null); //turn off the wait cursor progressBar.setValue(progressBar.getMinimum()); } } JProgressBar progressBar; ... progressBar = new JProgressBar(0, task.getLengthOfTask()); progressBar.setValue(0); progressBar.setStringPainted(true);
Slider & Progress public class Progress extends JPanel { JProgressBar pb = new JProgressBar(); JSlider sb = new JSlider(JSlider.HORIZONTAL, 0, 100, 60); public Progress() { setLayout(new GridLayout(2,1)); add(pb); sb.setValue(0); sb.setPaintTicks(true); sb.setMajorTickSpacing(20); sb.setMinorTickSpacing(5); sb.setBorder(new TitledBorder("Slide Me")); pb.setModel(sb.getModel()); // Share model add(sb); } }
JSplit Pane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane, pictureScrollPane); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(150); Dimension minimumSize = new Dimension(100, 50); listScrollPane.setMinimumSize(minimumSize); pictureScrollPane.setMinimumSize(minimumSize);
JScrollBar public class ScrollbarPanel extends JPanel { public ScrollbarPanel() { setLayout(new BorderLayout()); JScrollBar scrollBar1 = new JScrollBar (JScrollBar.VERTICAL, 0, 5, 0, 100); add(scrollBar1, BorderLayout.EAST); JScrollBar scrollBar2 = new JScrollBar (JScrollBar.HORIZONTAL, 0, 5, 0, 100); add(scrollBar2, BorderLayout.SOUTH); } }
JText copy() cut() paste() getSelectedText() setSelectionStart() setSelectionEnd() selectAll() replaceSelection() getText() setText() setEditable() setCaretPosition()
JTextField, JTextArea, JTextPane JTextField tf = new JTextField(); tf.setText("TextField"); add(tf); JTextArea ta = new JTextArea(); ta.setText("JTextArea\n Allows Multiple Lines"); add(new JScrollPane(ta)); JTextPane tp = new JTextPane(); MutableAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setFontFamily(attr, "Serif"); StyleConstants.setFontSize(attr, 18); StyleConstants.setBold(attr, true); tp.setCharacterAttributes(attr, false); add(new JScrollPane(tp)); PasswordPanel() { JPasswordField pass1 = new JPasswordField(20); JPasswordField pass2 = new JPasswordField(20); pass2.setEchoChar ('?'); add(pass1); add(pass2); }
JEditorPane final JEditorPane jt = new JEditorPane(); jt.setEditable(false); jt.setPage ("file:///C:/borovan/JAVA/index.html"); jt.addHyperlinkListener(new HyperlinkListener () { public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { SwingUtilities.invokeLater(new Runnable() { public void run() { Document doc = jt.getDocument(); try { URL url = e.getURL(); jt.setPage(url); input.setText (url.toString()); } catch (IOException io) { JOptionPane.showMessageDialog ( Browser.this, "Can't follow link", "Invalid Input", JOptionPane.ERROR_MESSAGE); jt.setDocument (doc); } } });
Dialogs //default title and icon JOptionPane.showMessageDialog(frame, “info dialog"); //custom title, warning icon JOptionPane.showMessageDialog(frame, “warning dialog", "warning", JOptionPane.WARNING_MESSAGE); //custom title, error icon JOptionPane.showMessageDialog(frame, “error dialog”, "error", JOptionPane.ERROR_MESSAGE); //custom title, custom icon JOptionPane.showMessageDialog(frame, “icon", "custom", JOptionPane.INFORMATION_MESSAGE, icon); JOptionPane optionPane = new JOptionPane( "The only way to close this dialog is by\n" + "pressing one of the following buttons.\n" + "Do you understand?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
InputDialog Object[] possibilities = {"ham", "spam", "yam"}; String s = (String)JOptionPane.showInputDialog( frame, "Complete the sentence:\n" + "\"Green eggs and...\"", "Customized Dialog", JOptionPane.PLAIN_MESSAGE, icon, possibilities, "ham"); //If a string was returned, say so. if ((s != null) && (s.length() > 0)) { setLabel("Green eggs and... " + s + "!"); return; }
JMenuBar public Object[] menuBar = { fileMenu, editMenu, faceMenu, optionMenu, helpMenu, }; static public JMenuBar createMenuBar(Object[] menuBarData) { JMenuBar menuBar = new JMenuBar(); for(int i = 0; i < menuBarData.length; i++) menuBar.add(createMenu((Object[][])menuBarData[i])); return menuBar; }
JMenu public Object[][] helpMenu = { // Menu name: { "Help", new Character('H') }, // Name type accel listener enabled { "Index", mi, new Character('I'), a1, bT }, { "Using help", mi,new Character('U'),a1,bT}, { null }, // Separator { "About", mi, new Character('t'), a1, bT }, }; static ButtonGroup bgroup; static public JMenu createMenu(Object[][] menuData) { JMenu menu = new JMenu(); menu.setText((String)menuData[0][0]); menu.setMnemonic(((Character)menuData[0][1]).charValue()); // Create redundantly, in case there are any radio buttons: bgroup = new ButtonGroup(); for(int i = 1; i < menuData.length; i++) { if(menuData[i][0] == null) menu.add(new JSeparator()); else menu.add(createMenuItem(menuData[i])); } return menu; }
JMenuItem static public JMenuItem createMenuItem(Object[] data) { JMenuItem m = null; MType type = (MType)data[1]; if(type == mi) m = new JMenuItem(); else if(type == cb) m = new JCheckBoxMenuItem(); else if(type == rb) { m = new JRadioButtonMenuItem(); bgroup.add(m); } m.setText((String)data[0]); m.setMnemonic( ((Character)data[2]).charValue()); m.addActionListener((ActionListener)data[3]); m.setEnabled(((Boolean)data[4]).booleanValue()); if(data.length == 6) m.setIcon((Icon)data[5]); return m; } public Object[][] faceMenu = { { "Faces", new Character('a') }, { "Face 0", rb, new Character('0'), a2, bT, Faces.faces[0] },
Action&ItemListener menuItem = new JMenuItem( "Both text and icon", new ImageIcon("images/middle.gif")); menuItem.setMnemonic(KeyEvent.VK_B); menu.add(menuItem); public class MenuDemo ... implements ActionListener, ItemListener { ... public MenuDemo() { menuItem.addActionListener(this); //...for each JMenuItem instance: ... rbMenuItem.addActionListener(this); //for each JRadioButtonMenuItem: ... cbMenuItem.addItemListener(this); //for each JCheckBoxMenuItem: ... } public void actionPerformed(ActionEvent e) { } public void itemStateChanged(ItemEvent e) { }
Popup import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Popup extends JPanel { JPopupMenu popup = new JPopupMenu(); JTextField t = new JTextField(10); public Popup() { add(t); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e){ t.setText( ((JMenuItem)e.getSource()).getText()); } }; JMenuItem m = new JMenuItem(“CutMe"); m.addActionListener(al); popup.add(m); m = new JMenuItem(“CopyMe"); m.addActionListener(al); popup.add(m); m = new JMenuItem(“PasteMe"); m.addActionListener(al); popup.add(m); popup.addSeparator(); m = new JMenuItem(“Nothing"); m.addActionListener(al); popup.add(m); PopupListener pl = new PopupListener(); addMouseListener(pl); t.addMouseListener(pl); } class PopupListener extends MouseAdapter { public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if(e.isPopupTrigger()) { popup.show( e.getComponent(), e.getX(), e.getY()); } } } }
static int i = 0; DefaultMutableTreeNode root, child, chosen; JTree tree; DefaultTreeModel model; public Trees() { setLayout(new BorderLayout()); root = new DefaultMutableTreeNode("root"); tree = new JTree(root); add(new JScrollPane(tree), BorderLayout.CENTER); model =(DefaultTreeModel)tree.getModel(); JButton test = new JButton("Press me"); test.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ if(i < data.length) { child = new Branch(data[i++]).node(); chosen = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if(chosen == null) chosen = root; model.insertNodeInto(child, chosen, 0); } } }); JPanel p = new JPanel(); p.add(test); add(p, BorderLayout.SOUTH); } Trees class Branch { DefaultMutableTreeNode r; public Branch(String[] data) { r = new DefaultMutableTreeNode(data[0]); for(int i = 1; i < data.length; i++) r.add(new DefaultMutableTreeNode(data[i])); } public DefaultMutableTreeNode node() { return r; } } public class Trees extends JPanel { String[][] data = { { "Colors", "Red", "Blue", "Green" }, { "Flavors", "Tart", "Sweet", "Bland" }, { "Length", "Short", "Medium", "Long" }, { "Volume", "High", "Medium", "Low" }, { "Temperature", "High", "Medium", "Low" }, { "Intensity", "High", "Medium", "Low" }, };
Tabbed public class Tabbed extends JPanel { static Object[][] q = { { "Felix", Borders.class }, { "The Professor", Buttons.class }, { "Rock Bottom", ButtonGroups.class }, { "Theodore", Faces.class }, { "Simon", Menus.class }, { "Alvin", Popup.class }, { "Tom", ListCombo.class }, { "Jerry", Progress.class }, { "Bugs", Trees.class }, { "Daffy", Table.class }, }; static JPanel makePanel(Class c) { String title = c.getName(); title = title.substring(title.lastIndexOf('.') + 1); JPanel sp = null; try { sp = (JPanel)c.newInstance(); } catch(Exception e) { System.out.println(e); } sp.setBorder(new TitledBorder(title)); return sp; } public Tabbed() { setLayout(new BorderLayout()); JTabbedPane tabbed = new JTabbedPane(); for(int i = 0; i < q.length; i++) tabbed.addTab((String)q[i][0], makePanel((Class)q[i][1])); add(tabbed, BorderLayout.CENTER); tabbed.setSelectedIndex(q.length/2); } }
JTable String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian"}; Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)}, {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)}, {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)} }; JTable table = new JTable(data, columnNames);
Table class DataModel extends AbstractTableModel { Object[][] data = { {"one", "two", "three", "four"}, {"five", "six", "seven", "eight"}, {"nine", "ten", "eleven", "twelve"}, }; class TML implements TableModelListener { public void tableChanged(TableModelEvent e) { … } } DataModel() { addTableModelListener(new TML()); } public int getColumnCount() { return data[0].length; } public int getRowCount() { return data.length; } public Object getValueAt(int row, int col) { return data[row][col]; } public void setValueAt(Object val, int row, int col) { data[row][col] = val; // Indicate the change has happened: fireTableDataChanged(); } public boolean isCellEditable(int row, int col) { return true; } }; import java.awt.*; import javax.swing.*; public class Table extends JPanel { public Table() { setLayout(new BorderLayout()); JTable table = new JTable(new DataModel()); JScrollPane scrollpane = JTable.createScrollPaneForTable(table); add(scrollpane, BorderLayout.CENTER); } public static void main(String args[]) { Show.inFrame(new Table(),200,200); } }