public JList5() { JFrame f = new JFrame("JList"); Container contentPane = f.getContentPane(); contentPane.setLayout(new GridLayout(1, 2)); ListModel<String> mode = new DateModel2(1); JList<String> list1 = new JList<String>(mode); list1.setVisibleRowCount(5); list1.setBorder(BorderFactory.createTitledBorder("您玩过哪些软件?")); mode = new DateModel2(2); JList<String> list2 = new JList<String>(mode); list2.setBorder(BorderFactory.createTitledBorder("您玩过哪些数据库?")); contentPane.add(new JScrollPane(list1)); contentPane.add(new JScrollPane(list2)); f.pack(); f.setVisible(true); f.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); }
public static void main(String[] args) { JFrame f = new JFrame("JList"); Container contentPane = f.getContentPane(); contentPane.setLayout(new GridLayout(1, 2)); String[] s = {"美国", "日本", "中国", "英国", "德国"}; Vector<String> v = new Vector<>(); v.addElement("Nokia 8850"); v.addElement("Nokia 8520"); v.addElement("Motorola v8088"); v.addElement("Motorola v3688x"); v.addElement("Panasonic GD92"); v.addElement("其他"); JList<String> list1 = new JList<String>(s); list1.setBorder(BorderFactory.createTitledBorder("你最喜欢到那个国家玩呢?")); JList<String> list2 = new JList<String>(v); list2.setBorder(BorderFactory.createTitledBorder("你最喜欢哪一种手机呢?")); // contentPane.add(list1); // contentPane.add(list2); //////////////////////////// contentPane.add(new JScrollPane(list1)); contentPane.add(new JScrollPane(list2)); f.pack(); f.setVisible(true); f.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); }
public JComponent getJComponent() { if (jp == null) { jp = new JPanel(); jp.setLayout(new BorderLayout()); jp.add(new JLabel(getDescription()), BorderLayout.WEST); jlist = new JList(descnames); if (numrows > 0) { try { jlist.setLayoutOrientation(JList.VERTICAL_WRAP); } catch (NoSuchMethodError e) { } jlist.setVisibleRowCount(numrows); } jlist.setBorder(new LineBorder(Color.black, 2)); updateGUI(); jlist.addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int flags = 0; for (int curindex = 0; curindex < size; curindex++) { JList list = (JList) e.getSource(); if (list.isSelectedIndex(curindex)) { flags |= (1 << curindex); } } enabled = flags; if (J2DBench.verbose.isEnabled()) { System.out.println(getOptionString()); } } }); jp.add(jlist, BorderLayout.EAST); } return jp; }
public void initFenster() { // SplitPane JSplitPane splitPane = new JSplitPane(); getContentPane().add(splitPane, BorderLayout.CENTER); JScrollPane scrollPane = new JScrollPane(); splitPane.setLeftComponent(scrollPane); // Weinpanel weinpanel = new Weinpanel(this, betrieb); splitPane.setRightComponent(weinpanel); // Weinliste weinlist = new JList<Weine>(weinModel); weinlist.setFont(new Font("Tahoma", Font.PLAIN, 15)); weinlist.setBorder(new EmptyBorder(0, 0, 0, 100)); scrollPane.setViewportView(weinlist); weinlist.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { doWeineValueChanged(arg0); } }); // Label Header JLabel lblHeader = new JLabel("alle Weine"); lblHeader.setFont(new Font("Tahoma", Font.BOLD, 15)); scrollPane.setColumnHeaderView(lblHeader); }
@Override protected JComponent createCenterPanel() { final JPanel panel = new JPanel(new BorderLayout()); JTextArea area = new JTextArea( "The imported language extends other languages.\n" + "It might be useful to import all or some of them."); area.setEditable(false); area.setBackground(this.getContentPane().getBackground()); area.setBorder(BorderFactory.createEmptyBorder(5, 5, 3, 5)); panel.add(area, BorderLayout.NORTH); JPanel center = new JPanel(new GridBagLayout()); JTextArea label = new JTextArea("Select additional languages to import:"); label.setEditable(false); label.setBackground(getContentPane().getBackground()); label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); center.add( label, new GridBagConstraints( 0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); myList = new JBList(myCandidates.toArray()); myList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); myList.setSelectionInterval(0, myList.getModel().getSize() - 1); myList.setCellRenderer(new MyDefaultListCellRenderer()); myList.setBorder(BorderFactory.createEtchedBorder()); center.add( ScrollPaneFactory.createScrollPane(myList), new GridBagConstraints( 0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); panel.add(center, BorderLayout.CENTER); panel.setPreferredSize(new Dimension(400, 250)); return panel; }
/** The constructor. */ public TargetManagerPanel() { setLayout(new BorderLayout()); lst = new JList(lm); setTarget(TargetManager.getInstance().getTargets()); add(new JScrollPane(lst), BorderLayout.CENTER); lst.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); TargetManager.getInstance().addTargetListener(this); add(new JButton(new ClearAction("Clear")), BorderLayout.SOUTH); }
public ListReportLinksPanel(SocioProject sp) { list = new JList(new DefaultListModel()); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.VERTICAL); list.setVisibleRowCount(-1); list.setSelectedIndex(0); list.setCellRenderer(new ListReportLinksElementRenderer()); Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5); list.setBorder(border); list.setBackground(new Color(50, 50, 50)); list.setForeground(new Color(210, 210, 220)); list.setEnabled(true); list.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { DefaultListModel mdl = (DefaultListModel) list.getModel(); ListReportLinksElementData elem = (ListReportLinksElementData) mdl.getElementAt(list.getSelectedIndex()); String link = elem.getName(); // String ask = JOptionPane.showInputDialog("Link opened!"); String browserPath = "C:/Program Files (x86)/Mozilla Firefox/firefox.exe"; // Use your browser path try { String[] b = {browserPath, link}; Runtime.getRuntime().exec(b); } catch (IOException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } } }); JScrollPane scroller = new JScrollPane(list); IAppWidgetFactory.makeIAppScrollPane(scroller); scroller.setFocusable(true); scroller.setPreferredSize(new Dimension(170, 220)); toolbar = new ListReportLinksToolbar(sp, list); toolbar.setGroupID(idRoot); toolbar.setPreferredSize(new Dimension(170, 40)); JLabel text = new JLabel("Список ccылок на отчеты:"); Font f = new Font(Font.SANS_SERIF, Font.BOLD, 15); text.setFont(f); text.setText("Список груп:"); text.setBackground(new Color(55, 95, 95)); text.setForeground(new Color(80, 80, 80)); this.setLayout(new BorderLayout()); this.add(text, BorderLayout.NORTH); this.add(scroller, BorderLayout.CENTER); this.add(toolbar, BorderLayout.SOUTH); }
private JList<String> getPmListaCodigosSud() { if (pmListaCodigosSud == null) { pmListaCodigosSud = new JList<String>(); pmListaCodigosSud.setName("List_Sudokus_Modificar"); pmListaCodigosSud.addListSelectionListener(getControlador()); pmListaCodigosSud.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); pmListaCodigosSud.setModel(getPmListModelCodigosSud()); pmListaCodigosSud.setBorder(new LineBorder(new Color(0, 0, 0))); } return pmListaCodigosSud; }
/** Constructor */ public ServiceFilterPanel(String text, Vector list) { empty_border = new EmptyBorder(5, 5, 0, 5); indent_border = new EmptyBorder(5, 25, 5, 5); service_box = new JCheckBox(text); service_box.addActionListener(this); service_data = new Vector(); if (list != null) { service_box.setSelected(true); service_data = (Vector) list.clone(); } service_list = new JList(service_data); service_list.setBorder(new EtchedBorder()); service_list.setVisibleRowCount(5); service_list.addListSelectionListener(this); service_list.setEnabled(service_box.isSelected()); service_scroll = new JScrollPane(service_list); service_scroll.setBorder(new EtchedBorder()); remove_service_button = new JButton("Remove"); remove_service_button.addActionListener(this); remove_service_button.setEnabled(false); remove_service_panel = new JPanel(); remove_service_panel.setLayout(new FlowLayout()); remove_service_panel.add(remove_service_button); service_area = new JPanel(); service_area.setLayout(new BorderLayout()); service_area.add(service_scroll, BorderLayout.CENTER); service_area.add(remove_service_panel, BorderLayout.EAST); service_area.setBorder(indent_border); add_service_field = new JTextField(); add_service_field.addActionListener(this); add_service_field.getDocument().addDocumentListener(this); add_service_field.setEnabled(service_box.isSelected()); add_service_button = new JButton("Add"); add_service_button.addActionListener(this); add_service_button.setEnabled(false); add_service_panel = new JPanel(); add_service_panel.setLayout(new BorderLayout()); JPanel dummy = new JPanel(); dummy.setBorder(empty_border); add_service_panel.add(dummy, BorderLayout.WEST); add_service_panel.add(add_service_button, BorderLayout.EAST); add_service_area = new JPanel(); add_service_area.setLayout(new BorderLayout()); add_service_area.add(add_service_field, BorderLayout.CENTER); add_service_area.add(add_service_panel, BorderLayout.EAST); add_service_area.setBorder(indent_border); setLayout(new BorderLayout()); add(service_box, BorderLayout.NORTH); add(service_area, BorderLayout.CENTER); add(add_service_area, BorderLayout.SOUTH); setBorder(empty_border); }
/** * Sets up the JTree. * * @return */ JList getContent() { model = new DefaultListModel(); list = new JList(model); // Only select one song in playlist at a time list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setDragEnabled(true); list.setDropMode(DropMode.INSERT); // Add drag and drop support list.setTransferHandler(new ListTransferHandler(list, callback, gui)); list.setCellRenderer(new PlayListCellRenderer()); list.setBorder(null); list.addMouseListener( new MouseAdapter() { private PlayListPopUpMenu popup = new PlayListPopUpMenu(); /** Display pop up menu for songs */ @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { JList source = (JList) e.getSource(); source.setSelectedIndex(source.locationToIndex(e.getPoint())); popup.show(source, e.getX(), e.getY()); } } /** Play songs that are double clicked */ @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = list.locationToIndex(e.getPoint()); Song selectedSong = (Song) list.getModel().getElementAt(index); model.remove(index); model.add(model.size(), selectedSong); callback.notify( Command.NEW_QUEUE, Arrays.asList(model.toArray()), gui.getCurrentZone()); } } }); return list; }
private JList getValueList() { if (enumList == null) { enumList = new JList(enumListModel); enumList.setCellRenderer(new AlternatingRowColorListCellRenderer()); enumList.setFixedCellHeight(20); enumList.setVisibleRowCount(10); enumList.setPreferredSize(new Dimension(200, 100)); enumList.getSelectionModel().setSelectionMode(selectionMode); enumList.setBorder(null); for (E possibleValue : enumeration.getEnumConstants()) { enumListModel.addElement(possibleValue); } } return enumList; }
public PanelJugadores(ControladorServidor control) { setLayout(new BorderLayout()); controlador = control; jPanel1 = new JPanel(); jPanel2 = new JPanel(); jLabelJugadores = new JLabel(" Jugadores en mesa:"); jJugadores = new JList(controlador.getListaJugadores()); jJugadores.setFont(new Font("Serif", Font.ITALIC, 12)); jJugadores.setBorder(BorderFactory.createEtchedBorder()); jJugadores.setToolTipText("Jugadores"); add(jLabelJugadores, BorderLayout.NORTH); add(jJugadores, BorderLayout.CENTER); add(jPanel1, BorderLayout.EAST); add(jPanel2, BorderLayout.WEST); }
protected Component buildPage() { JList listBox = SwingComponentFactory.buildList(this.buildSelectedNodesListModel()); listBox.setBorder(BorderFactory.createEmptyBorder()); listBox.setCellRenderer(new DisplayableListCellRenderer()); listBox.setBackground(UIManager.getColor("Panel.background")); listBox.setForeground(UIManager.getColor("List.foreground")); listBox.setSelectionBackground(UIManager.getColor("ScrollPane.background")); listBox.setSelectionForeground(listBox.getForeground()); JScrollPane scrollPane = new JScrollPane(listBox); scrollPane.setBorder(new EmptyBorder(5, 0, 0, 0)); scrollPane.getVerticalScrollBar().setUnitIncrement(10); scrollPane.setViewportBorder(BorderFactory.createEmptyBorder()); return scrollPane; }
public SettingsDialog(final MainWindow window, final Scene scene, final SceneRenderer renderer) { super(window); setResizable(false); setAlwaysOnTop(true); setSize(550, 420); setTitle("Settings"); setLocationRelativeTo(window); getContentPane().setLayout(new BorderLayout()); optionsPanel = new JPanel(); optionsPanel.setLayout(optionsLayout = new CardLayout()); optionsPanel.add(new RendererSettings(scene, renderer), menus[0]); optionsPanel.add(new SubSettings(scene, renderer), menus[1]); optionsPanel.add(new RobotSettings(scene, renderer), menus[2]); optionsPanel.add(new ObstacleSettings(scene, renderer), menus[3]); optionsPanel.add(new PathSettings(scene, renderer), menus[4]); optionsPanel.add(new SumSettings(scene, renderer), menus[5]); optionsPanel.add(new ContactSettings(scene, renderer), menus[6]); getContentPane().add(optionsPanel, BorderLayout.CENTER); JPanel bottomPanel = new JPanel(); FlowLayout fl_bottomPanel = (FlowLayout) bottomPanel.getLayout(); fl_bottomPanel.setAlignment(FlowLayout.RIGHT); bottomPanel.setBorder(new MatteBorder(1, 0, 0, 0, (Color) Color.GRAY)); getContentPane().add(bottomPanel, BorderLayout.SOUTH); menuList = new JList(new MenuModel()); menuList.setCellRenderer(new MenuRenderer()); menuList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); menuList.setPreferredSize(new Dimension(100, 0)); menuList.setBorder(new MatteBorder(0, 0, 0, 1, (Color) Color.GRAY)); menuList.setBounds(17, 20, 99, 241); menuList.addListSelectionListener(new MenuListener()); menuList.setSelectedIndex(0); getContentPane().add(menuList, BorderLayout.WEST); JButton btnOk = new JButton("OK"); btnOk.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { SettingsDialog.this.setVisible(false); } }); bottomPanel.add(btnOk); }
private JList createSuggestionList(final int position, final String subWord) { Object[] data = new Object[10]; for (int i = 0; i < data.length; i++) { data[i] = subWord + i + "test"; } JList list = new JList(data); list.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1)); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectedIndex(0); list.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { insertSelection(); } } }); return list; }
private void init() { Container con = this.getContentPane(); con.setLayout(new BorderLayout()); hostInfo = new JTextField(); try { hostInfo.setText("Server Address: " + InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } hostInfo.setEditable(false); topP.add(hostInfo); topP.add(btnSvrStart); con.add(topP, "North"); middleP.setLayout(new GridLayout(2, 1)); txtChat.setEditable(false); middleP.add(txtChat); roomList = RoomListPanel.getInstance(); sp = new JScrollPane(txtChat); // Adding Scroll Bar middleP.add(roomList); middleP.add(sp); con.add(middleP, "Center"); pnlBroadcast.setLayout(new BoxLayout(pnlBroadcast, BoxLayout.X_AXIS)); pnlBroadcast.add(fldChat); pnlBroadcast.add(btnPersonalMsg); pnlBroadcast.add(btnBroadcast); con.add(pnlBroadcast, "South"); listModel.addElement("To All"); lstConnector = new JList<String>(listModel); con.add(lstConnector, "East"); lstConnector.setBorder(BorderFactory.createLineBorder(Color.BLACK)); fileMenu.add(photoMenuItem); fileMenu.add(fileMenuItem); menuBar.add(fileMenu); this.setJMenuBar(menuBar); }
public InvList() { setLayout(new BorderLayout()); setPreferredSize(new Dimension(150, 400)); pop = new JPopupMenu(); pop.setFont(new Font("Helvetica", Font.ITALIC, 11)); JMenuItem mi; mi = (JMenuItem) pop.add(new JMenuItem("Detail")); mi.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // currently do nothing } }); listTitle = new JLabel("Invitation List"); listView = new JList(); listView.setListData(testing); listView.setBorder(new BevelBorder(BevelBorder.LOWERED)); listView.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { selectedRow = listView.getSelectedIndex(); listView.grabFocus(); } public void mouseReleased(MouseEvent e) { // pop up a list if that is a right click if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0) pop.show(e.getComponent(), e.getX(), e.getY()); } }); scrollList = new JScrollPane(listView); scrollList.setBorder(new BevelBorder(BevelBorder.LOWERED)); add(listView, BorderLayout.CENTER); add(listTitle, BorderLayout.NORTH); }
<T> JList createJList(String title, List<T> data) { JList list = new JList(); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setDragEnabled(false); // HACK find a way to modify napkin's color, not the component's int c = 200; list.setSelectionBackground(new Color(c, c, c)); list.setBorder(BorderFactory.createTitledBorder(title)); if (data != null) { List<T> objects = new ArrayList<T>(data); Collections.sort( objects, new Comparator<T>() { @Override public int compare(T arg0, T arg1) { return arg0.toString().compareTo(arg1.toString()); } }); list.setListData(objects.toArray()); } return list; }
public JList7() { JFrame f = new JFrame("JList"); Container contentPane = f.getContentPane(); contentPane.setLayout(new BorderLayout()); label = new JLabel(); list = new JList(s); list.setVisibleRowCount(5); list.setBorder(BorderFactory.createTitledBorder("您最喜欢到哪个国家玩呢?")); list.addListSelectionListener(this); contentPane.add(label, BorderLayout.NORTH); contentPane.add(new JScrollPane(list), BorderLayout.CENTER); f.pack(); f.show(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); }
public LicenseWindow() { super("Licenses"); setIconImage(Amidst.icon); licenseText.setEditable(false); licenses.add(new License("AMIDST", "licenses/amidst.txt")); licenses.add(new License("Args4j", "licenses/args4j.txt")); licenses.add(new License("Gson", "licenses/gson.txt")); licenses.add(new License("JGoogleAnalytics", "licenses/jgoogleanalytics.txt")); licenses.add(new License("JNBT", "licenses/jnbt.txt")); licenses.add(new License("MiG Layout", "licenses/miglayout.txt")); licenses.add(new License("Rhino", "licenses/rhino.txt")); licenseList = new JList(licenses.toArray()); licenseList.setBorder(new LineBorder(Color.darkGray, 1)); Container contentPane = this.getContentPane(); MigLayout layout = new MigLayout(); contentPane.setLayout(layout); contentPane.add(licenseList, "w 100!, h 0:2400:2400"); JScrollPane scrollPane = new JScrollPane(licenseText); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); contentPane.add(scrollPane, "w 0:4800:4800, h 0:2400:2400"); setSize(870, 550); setVisible(true); licenseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); licenseList.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { License license = (License) licenseList.getSelectedValue(); license.load(); if (license.isLoaded()) { licenseText.setText(license.getContents()); licenseText.setCaretPosition(0); } } }); licenseList.setSelectedIndex(0); }
private void placeComponents() { this.getContentPane().add(hoved = new JPanel(new BorderLayout())); hoved.add(new JPanel().add(messages = new JTextArea()), BorderLayout.CENTER); hoved.add(new JPanel().add(loggedOn = new JList()), BorderLayout.EAST); hoved.add(new JPanel().add(inputFelt = new JTextField()), BorderLayout.SOUTH); loggedOn.setPreferredSize(new Dimension(100, 400)); loggedOn.setBorder(BorderFactory.createLineBorder(Color.BLACK)); messages.setBorder(BorderFactory.createLineBorder(Color.BLACK)); inputFelt.setBorder(BorderFactory.createLineBorder(Color.BLACK)); loggedOn.setListData(new Vector()); inputFelt.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ENTER) { sendMessage(inputFelt.getText()); inputFelt.setText(""); } } }); MenuBar menubar = new MenuBar(); Menu menu = new Menu("Settings"); MenuItem item = new MenuItem("Change nick"); item.addActionListener( new AbstractAction() { public void actionPerformed(ActionEvent e) { String newName = JOptionPane.showInputDialog( Gui.this, "Enter new nick:", "Change nick", JOptionPane.PLAIN_MESSAGE); Gui.this.target.send("/newName: " + newName); Gui.this.target.setUsername(newName); } }); menu.add(item); menubar.add(menu); this.setMenuBar(menubar); }
public PreferencesDialog(JabRefFrame parent) { super(parent, Localization.lang("JabRef preferences"), false); JabRefPreferences prefs = JabRefPreferences.getInstance(); frame = parent; main = new JPanel(); JPanel mainPanel = new JPanel(); JPanel lower = new JPanel(); getContentPane().setLayout(new BorderLayout()); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().add(lower, BorderLayout.SOUTH); final CardLayout cardLayout = new CardLayout(); main.setLayout(cardLayout); List<PrefsTab> tabs = new ArrayList<>(); tabs.add(new GeneralTab(prefs)); tabs.add(new NetworkTab(prefs)); tabs.add(new FileTab(frame, prefs)); tabs.add(new FileSortTab(prefs)); tabs.add(new EntryEditorPrefsTab(frame, prefs)); tabs.add(new GroupsPrefsTab(prefs)); tabs.add(new AppearancePrefsTab(prefs)); tabs.add(new ExternalTab(frame, this, prefs)); tabs.add(new TablePrefsTab(prefs)); tabs.add(new TableColumnsTab(prefs, parent)); tabs.add(new BibtexKeyPatternPrefTab(prefs, parent.getCurrentBasePanel())); tabs.add(new PreviewPrefsTab(prefs)); tabs.add(new NameFormatterTab(prefs)); tabs.add(new ImportSettingsTab(prefs)); tabs.add(new XmpPrefsTab(prefs)); tabs.add(new AdvancedTab(prefs)); // add all tabs tabs.forEach(tab -> main.add((Component) tab, tab.getTabName())); mainPanel.setBorder(BorderFactory.createEtchedBorder()); String[] tabNames = tabs.stream().map(PrefsTab::getTabName).toArray(String[]::new); JList<String> chooser = new JList<>(tabNames); chooser.setBorder(BorderFactory.createEtchedBorder()); // Set a prototype value to control the width of the list: chooser.setPrototypeCellValue("This should be wide enough"); chooser.setSelectedIndex(0); chooser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Add the selection listener that will show the correct panel when // selection changes: chooser.addListSelectionListener( e -> { if (e.getValueIsAdjusting()) { return; } String o = chooser.getSelectedValue(); cardLayout.show(main, o); }); JPanel buttons = new JPanel(); buttons.setLayout(new GridLayout(4, 1)); buttons.add(importPreferences, 0); buttons.add(exportPreferences, 1); buttons.add(showPreferences, 2); buttons.add(resetPreferences, 3); JPanel westPanel = new JPanel(); westPanel.setLayout(new BorderLayout()); westPanel.add(chooser, BorderLayout.CENTER); westPanel.add(buttons, BorderLayout.SOUTH); mainPanel.setLayout(new BorderLayout()); mainPanel.add(main, BorderLayout.CENTER); mainPanel.add(westPanel, BorderLayout.WEST); JButton ok = new JButton(Localization.lang("OK")); JButton cancel = new JButton(Localization.lang("Cancel")); ok.addActionListener(new OkAction()); CancelAction cancelAction = new CancelAction(); cancel.addActionListener(cancelAction); lower.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); ButtonBarBuilder buttonBarBuilder = new ButtonBarBuilder(lower); buttonBarBuilder.addGlue(); buttonBarBuilder.addButton(ok); buttonBarBuilder.addButton(cancel); buttonBarBuilder.addGlue(); // Key bindings: KeyBinder.bindCloseDialogKeyToCancelAction(this.getRootPane(), cancelAction); // Import and export actions: exportPreferences.setToolTipText(Localization.lang("Export preferences to file")); exportPreferences.addActionListener( e -> { Optional<Path> path = new NewFileDialogs(frame, System.getProperty("user.home")) .withExtension(FileExtensions.XML) .saveNewFile(); path.ifPresent( exportFile -> { try { prefs.exportPreferences(exportFile.toString()); } catch (JabRefException ex) { LOGGER.warn(ex.getMessage(), ex); JOptionPane.showMessageDialog( PreferencesDialog.this, ex.getLocalizedMessage(), Localization.lang("Export preferences"), JOptionPane.ERROR_MESSAGE); } }); }); importPreferences.setToolTipText(Localization.lang("Import preferences from file")); importPreferences.addActionListener( e -> { Optional<Path> fileName = new NewFileDialogs(frame, System.getProperty("user.home")) .withExtension(FileExtensions.XML) .openDlgAndGetSelectedFile(); if (fileName.isPresent()) { try { prefs.importPreferences(fileName.get().toString()); updateAfterPreferenceChanges(); JOptionPane.showMessageDialog( PreferencesDialog.this, Localization.lang("You must restart JabRef for this to come into effect."), Localization.lang("Import preferences"), JOptionPane.WARNING_MESSAGE); } catch (JabRefException ex) { LOGGER.warn(ex.getMessage(), ex); JOptionPane.showMessageDialog( PreferencesDialog.this, ex.getLocalizedMessage(), Localization.lang("Import preferences"), JOptionPane.ERROR_MESSAGE); } } }); showPreferences.addActionListener( e -> new PreferencesFilterDialog(new JabRefPreferencesFilter(Globals.prefs), frame) .setVisible(true)); resetPreferences.addActionListener( e -> { if (JOptionPane.showConfirmDialog( PreferencesDialog.this, Localization.lang( "Are you sure you want to reset all settings to default values?"), Localization.lang("Reset preferences"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { try { prefs.clear(); JOptionPane.showMessageDialog( PreferencesDialog.this, Localization.lang("You must restart JabRef for this to come into effect."), Localization.lang("Reset preferences"), JOptionPane.WARNING_MESSAGE); } catch (BackingStoreException ex) { LOGGER.warn(ex.getMessage(), ex); JOptionPane.showMessageDialog( PreferencesDialog.this, ex.getLocalizedMessage(), Localization.lang("Reset preferences"), JOptionPane.ERROR_MESSAGE); } updateAfterPreferenceChanges(); } }); setValues(); pack(); }
/** Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); frame.getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(null); JList list = new JList(); list.setBorder(new LineBorder(new Color(0, 0, 0))); list.setModel( new AbstractListModel() { String[] values = new String[] {"Ejemplo1", "Ejemplo2", "Ejemplo3"}; public int getSize() { return values.length; } public Object getElementAt(int index) { return values[index]; } }); list.setBounds(10, 49, 200, 173); panel.add(list); JLabel lblProductos = new JLabel("Productos"); lblProductos.setBounds(10, 11, 200, 50); panel.add(lblProductos); JLabel lblFechaCaducidad = new JLabel("Fecha caducidad: "); lblFechaCaducidad.setBounds(220, 49, 105, 30); panel.add(lblFechaCaducidad); JLabel Fecha = new JLabel("04/06/14"); Fecha.setBounds(335, 39, 200, 50); panel.add(Fecha); JLabel lblvalido = new JLabel("¿Valido?"); lblvalido.setBounds(230, 91, 66, 50); panel.add(lblvalido); ; JButton btnNewButton = new JButton("Validar"); btnNewButton.setBounds(275, 171, 89, 23); panel.add(btnNewButton); final JRadioButton rdbtnSi = new JRadioButton("Si"); rdbtnSi.setSelected(true); rdbtnSi.setBounds(302, 105, 57, 23); panel.add(rdbtnSi); final JRadioButton rdbtnNo = new JRadioButton("No"); rdbtnNo.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { rdbtnSi.setSelected(false); } }); rdbtnNo.setBounds(364, 105, 109, 23); panel.add(rdbtnNo); rdbtnSi.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { rdbtnNo.setSelected(false); } }); btnNewButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (rdbtnNo.isSelected()) { Alert alerta = new Alert(); alerta.mostrar(); } } }); }
/** create the form */ private void createForm() { // create the panel setName(getMyType() + " editor"); // create the information message String msg = "1. Use the buttons to the right to add/remove and re-order the points in the " + getMyType() + ".\r\n"; msg += " 2. Use the Drag button to switch on and off dragging of " + getMyType() + " points.\r\n"; msg += " 3. Select a point from the list below to edit it in Point Editor (below).\r\n"; msg += " 4. Use Reset to return to the original " + getMyType() + ".\r\n"; msg += " 5. Finally use Apply then Close to update the shape.\r\n"; // create the information panel final JTextArea info = new JTextArea(); info.setBackground(this.getBackground()); info.setLineWrap(true); info.setWrapStyleWord(true); info.setText(msg); // make the text a little smaller final Font infoFont = info.getFont(); info.setFont(infoFont.deriveFont((float) 10.0)); // create the top panel (with the new, up, down button) final JPanel infoPanel = new JPanel(); infoPanel.setLayout(new BorderLayout()); final JPanel btnBar = new JPanel(); btnBar.setLayout(new GridLayout(2, 0)); infoPanel.add("East", btnBar); infoPanel.add("Center", info); // and the new, up, down buttons final JButton upBtn = createButton("Move current point up", "images/Up.gif", "Up"); upBtn.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent e) { doUpDown(true); } }); final JButton downBtn = createButton("Move current point down", "images/Down.gif", "Down"); downBtn.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent e) { doUpDown(false); } }); final JButton newBtn = createButton("Add new point", "images/NewPin.gif", "New"); newBtn.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent e) { addNew(); } }); final JButton deleteBtn = createButton("Delete current point", "images/DeletePin.gif", "Delete"); deleteBtn.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent e) { deleteCurrent(); } }); btnBar.add(upBtn); btnBar.add(downBtn); btnBar.add(newBtn); btnBar.add(deleteBtn); // create the list _myList = new JList(); _myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); _myList.setBorder(new javax.swing.border.EtchedBorder()); _myList.addListSelectionListener( new ListSelectionListener() { public void valueChanged(final ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!_myList.isSelectionEmpty()) { final WorldLocation loc = (WorldLocation) _myList.getSelectedValue(); if (loc != null) editThis(_myList.getSelectedValue()); } } } }); // show the list final JPanel listHolder = new JPanel(); listHolder.setLayout(new BorderLayout()); _dragger = new DragButton(getChart(), _theParent); listHolder.add("North", _dragger); listHolder.add("Center", _myList); // create the sub-form _subPanel = new JPanel(); _subPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Point Editor")); _subPanel.setName("Point editor"); _subPanel.setLayout(new BorderLayout()); _subPanel.add("Center", _editor.getCustomEditor()); final JButton subApply = new JButton("Apply"); subApply.setToolTipText("Apply the changes to our " + getMyType()); subApply.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent e) { final WorldLocation curLoc = (WorldLocation) _myList.getSelectedValue(); if (curLoc != null) { curLoc.copy((WorldLocation) _editor.getValue()); _myList.repaint(); // also update the point in the path final int index = _myList.getSelectedIndex(); getPath().getLocationAt(index).copy(curLoc); // update the plot getChart().getLayers().fireReformatted(null); } } }); // create the bottom toolbar final JButton closeBtn = new JButton("Close"); closeBtn.setToolTipText("Close this panel"); closeBtn.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent e) { doClose(); } }); // now the reset button final JButton resetBtn = new JButton("Reset"); resetBtn.setToolTipText("Reset the data"); resetBtn.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent e) { doReset(); } }); final JPanel buttonHolder = new JPanel(); buttonHolder.setLayout(new GridLayout(1, 0)); buttonHolder.add(closeBtn); buttonHolder.add(subApply); buttonHolder.add(resetBtn); final JPanel bottomHolder = new JPanel(); bottomHolder.setLayout(new BorderLayout()); bottomHolder.add("Center", _subPanel); bottomHolder.add("South", buttonHolder); // put them into the form setLayout(new BorderLayout()); add("North", infoPanel); add("Center", listHolder); add("South", bottomHolder); }
// Build the form public PackagesFrame() { super("Packages", true, true, true, true); // Hide the frame when closed, don't destroy it as it is only created // once setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); getContentPane().setLayout(null); getContentPane().setSize(800, 550); // Add CRUD buttons // Add all panels to form getContentPane().add(new JLabel("Viewing Packages"), "North"); getContentPane().add(pnlCrudPanel, "South"); pnlCrudPanel.setBounds(0, 496, 756, 31); pnlCrudPanel.add(btnDelete); pnlCrudPanel.add(btnSave); pnlCrudPanel.add(btnEdit); { jScrollPane1 = new JScrollPane(); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(12, 34, 774, 223); btnNew.setBounds(304, 415, 35, 21); btnNew.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addNewRow(); } }); btnEdit.setBounds(350, 415, 32, 21); pnlCrudPanel.add(btnNew); btnEdit.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnEditMouseClicked(e); } }); btnSave.setBounds(393, 415, 38, 21); btnSave.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnSaveMouseClicked(e); } }); btnDelete.setBounds(442, 415, 45, 21); btnDelete.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnDeleteMouseClicked(e); } }); { tblPackages = new JTable(); jScrollPane1.setViewportView(tblPackages); tblPackages.setRowHeight(25); // initialize package table with result set pkgTblModel = new PackagesTableModel(); tblPackages.setSurrendersFocusOnKeystroke(true); tblPackages.setBorder(BorderFactory.createBevelBorder(1)); tblPackages.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent evt) {} public void mouseClicked(java.awt.event.MouseEvent e) { int clicked = e.getClickCount(); if (clicked == 2) { Point pt = e.getPoint(); int i = tblPackages.rowAtPoint(pt); int j = tblPackages.columnAtPoint(pt); // System.out.println("<" + i + "," + j + ">"); if (j == PackagesTableModel.START_DATE || j == PackagesTableModel.END_DATE) { // show calendar if (JOptionPane.showConfirmDialog(null, calStartDate) == JOptionPane.OK_OPTION) { java.sql.Date d = new java.sql.Date(calStartDate.getCalendar().getTimeInMillis()); pkgTblModel.setValueAt(d, i, j); } } } } }); tblPackages .getSelectionModel() .addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { // if (e.getValueIsAdjusting() // && (e.getFirstIndex() != e // .getLastIndex())) listSelectionChaged(e); } }); tblPackages.setModel(pkgTblModel); initTable(pkgTblModel, -1); // sorter = new TableRowSorter<PackagesTableModel>(pkgTblModel); // sorter confuses my table model // tblPackages.setRowSorter(sorter); tblPackages.setDefaultRenderer(Object.class, new EvenOddRenderer()); // final NumericTextField ntf = new NumericTextField(currency); final NumericTextField ntf = new NumericTextField(); tblPackages .getColumnModel() .getColumn(PackagesTableModel.COMMISSION) .setCellEditor(new DefaultCellEditor(ntf)); tblPackages .getColumnModel() .getColumn(PackagesTableModel.PRICE) .setCellEditor(new DefaultCellEditor(ntf)); ntf.addFocusListener( new FocusListener() { @Override public void focusGained(FocusEvent e) { eraseNonNumeric(e); NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.CANADA); try { Double dblValue = currency.parse(((JTextField) e.getComponent()).getText()).doubleValue(); ((JTextField) e.getComponent()).setText(dblValue.toString()); } catch (ParseException e1) { e1.printStackTrace(); } } @Override public void focusLost(FocusEvent e) {} }); ntf.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { TXLogger.logger.debug("NumericTextFiled: " + e.getKeyCode()); // System.out.println("NumericTextFiled: " // + e.getKeyChar()); String txtOld = ((JTextField) e.getComponent()).getText(); if (e.getKeyChar() >= KeyEvent.VK_0 && e.getKeyChar() <= KeyEvent.VK_9) { if (txtOld.indexOf('.') == -1 && txtOld.length() >= 15) { e.consume(); return; } return; } else if (e.getKeyChar() == '.') { if (((JTextField) e.getComponent()).getText().indexOf('.') > -1) e.consume(); TXLogger.logger.debug( "index of ." + ((JTextField) e.getComponent()).getText().indexOf('.')); // System.out.println("index of ." // + ((JTextField) e.getComponent()).getText() // .indexOf('.')); } else if (e.getKeyCode() != '\n') { e.consume(); } } }); JTextField cellNotNull = new JTextField(); tblPackages .getColumnModel() .getColumn(PackagesTableModel.PACKAGE_NAME) .setCellEditor(new DefaultCellEditor(cellNotNull)); tblPackages .getColumnModel() .getColumn(PackagesTableModel.DESCRIPTION) .setCellEditor(new DefaultCellEditor(cellNotNull)); cellNotNull.addFocusListener( new FocusListener() { @Override public void focusGained(FocusEvent e) { String txt = ((JTextField) (e.getComponent())).getText(); if ((txt.indexOf((VALUE_REQUIRED)) >= 0)) { ((JTextField) (e.getComponent())).setText(""); } } @Override public void focusLost(FocusEvent e) {} }); // Column 5 and 6 only accept numeric input cellNotNull.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { TXLogger.logger.debug(e.getKeyChar()); // System.out.println(e.getKeyChar()); if (((JTextField) e.getComponent()).getText().length() >= 100) { e.consume(); return; } } }); // popup memu tblPackages.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent evt) { if (tblPackages.getSelectedRow() >= 0 && evt.getButton() == MouseEvent.BUTTON3) { popupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); } } }); cellNotNull.addFocusListener( new FocusListener() { @Override public void focusGained(FocusEvent e) { if (((JTextField) e.getComponent()).getText().trim().equals(VALUE_REQUIRED)) { ((JTextField) e.getComponent()).setText(""); } ((JTextField) e.getComponent()).setBackground(Color.RED); } @Override public void focusLost(FocusEvent e) {} }); tblPackages.setBounds(32, 12, 700, 203); tblPackages.setPreferredSize(new java.awt.Dimension(756, 422)); popupMenu = new JPopupMenu(); copyItem = new JMenuItem("Copy and create a new package"); copyItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyAndCreate(tblPackages.getSelectedRow()); } }); JMenuItem deleteItem = new JMenuItem("Delete"); deleteItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnDeleteMouseClicked(null); } }); JMenuItem newItem = new JMenuItem("New"); newItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addNewRow(); } }); JMenuItem editItem = new JMenuItem("Edit"); editItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnEditMouseClicked(null); } }); JMenuItem saveItem = new JMenuItem("Save"); saveItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnSaveMouseClicked(null); } }); JMenuItem printItem = new JMenuItem("Print"); printItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { // openURL("http://google.com"); openURL("http://localhost:8081/CrystalWeb2/PackageList.rpt-viewer.jsp"); } catch (RuntimeException e1) { TXLogger.logger.error(e1.getMessage()); // e1.printStackTrace(); } catch (IOException e2) { TXLogger.logger.error(e2.getMessage()); // e2.printStackTrace(); } } }); popupMenu.add(copyItem); popupMenu.addSeparator(); popupMenu.add(deleteItem); popupMenu.add(saveItem); popupMenu.add(editItem); popupMenu.add(newItem); popupMenu.addSeparator(); popupMenu.add(printItem); } } { cmbProdFilterModel = new DefaultComboBoxModel(); cmbProdFilter = new JComboBox(); getContentPane().add(cmbProdFilter); cmbProdFilter.setModel(cmbProdFilterModel); cmbProdFilter.setBounds(436, 283, 204, 21); cmbProdFilter.setEditable(true); cmbProdFilter.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent evt) { cmbProdFilterItemStateChanged(evt); } }); } { jLabel1 = new JLabel(); getContentPane().add(jLabel1); jLabel1.setBounds(33, 9, 129, 14); jLabel1.setName("jLabel1"); } { jLabel2 = new JLabel(); getContentPane().add(jLabel2); jLabel2.setBounds(34, 248, 94, 14); jLabel2.setName("jLabel2"); } { jLabel3 = new JLabel(); getContentPane().add(jLabel3); jLabel3.setBounds(436, 248, 119, 14); jLabel3.setName("jLabel3"); } { btnInc = new JButton("<"); getContentPane().add(btnInc); btnInc.setBounds(351, 327, 52, 21); btnInc.setName("btnInc"); btnInc.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent evt) { TXLogger.logger.debug("btnInc.mouseClicked, event"); // System.out.println("btnInc.mouseClicked, event=" + evt); btnIncMouseClicked(evt); } }); } { btnIncAll = new JButton("<<"); getContentPane().add(btnIncAll); btnIncAll.setBounds(351, 362, 52, 21); btnIncAll.setName("btnIncAll"); btnIncAll.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent evt) { btnIncAllMouseClicked(evt); } }); } { btnExc = new JButton(">"); getContentPane().add(btnExc); btnExc.setBounds(351, 394, 52, 21); btnExc.setName("btnExc"); btnExc.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent evt) { btnExcMouseClicked(evt); } }); } { btnExcAll = new JButton(">>"); getContentPane().add(btnExcAll); btnExcAll.setBounds(351, 426, 52, 21); btnExcAll.setName("btnExcAll"); btnExcAll.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent evt) { btnExcAllMouseClicked(evt); } }); } { jScrollPane3 = new JScrollPane(); getContentPane().add(jScrollPane3); jScrollPane3.setBounds(437, 306, 286, 169); { ListModel jList1Model = new DefaultComboBoxModel(new String[] {"Item One", "Item Two"}); lstProdAvi = new JList(new Object[] {"First Class Flight", "Car Rental", "Scuba Diving Adventure"}); jScrollPane3.setViewportView(lstProdAvi); lstProdAvi.setModel(jList1Model); lstProdAvi.setBorder( BorderFactory.createTitledBorder( BorderFactory.createBevelBorder(1), "Product--Supplier")); lstProdAvi.setBounds(436, 284, 286, 169); dlmAvi = new DefaultListModel(); lstProdAvi.setModel(dlmAvi); } } { jScrollPane2 = new JScrollPane(); getContentPane().add(jScrollPane2); getContentPane().add(getJLabel4()); getContentPane().add(getJLabel5()); getContentPane().add(getJLabel7()); getContentPane().add(getCmbPkgFilter()); getContentPane().add(getJLabel8()); getContentPane().add(getJLabel6()); getContentPane().add(getCmbOrderBy()); jScrollPane2.setBounds(34, 303, 286, 166); jScrollPane2.setViewportView(lstProdInc); } // Draw fancy border for the list lstProdInc.setBorder( BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(1), "Product--Supplier")); lstProdInc.setBounds(33, 281, 286, 166); lstProdInc.setModel(dlmInc); validate(); pack(); Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this); getAllProdList(""); initCboProdFilter(); tblPackages.getColumn(pkgTblModel.getColumnName(0)).setPreferredWidth(15); tblPackages.getColumn(pkgTblModel.getColumnName(1)).setPreferredWidth(100); tblPackages.getColumn(pkgTblModel.getColumnName(2)).setPreferredWidth(40); tblPackages.getColumn(pkgTblModel.getColumnName(3)).setPreferredWidth(40); tblPackages.getColumn(pkgTblModel.getColumnName(4)).setPreferredWidth(200); tblPackages.getColumn(pkgTblModel.getColumnName(5)).setPreferredWidth(40); tblPackages.getColumn(pkgTblModel.getColumnName(6)).setPreferredWidth(40); tblPackages.setName("tblPackages"); setButtonState(false); }
/** * This method populates the ProjectSelector with all the subpanels and buttons * * @param main The object to notify when the ok button is pressed. */ public void populate(Object main) { this.main = main; // gather all projects String[] projects = getAllProjectNames(); if (projects == null) { Main.fatalError( "Cannot find the project folder. Please ensure that the framework is installed properly."); } Arrays.sort(projects); // sort the projects in ascending order this.addComponentListener( new ComponentListener() { int oldX = appConfig.projectSelectorWindowPosX, oldY = appConfig.projectSelectorWindowPosY; public void componentResized(ComponentEvent e) { if (ProjectSelector.this.getExtendedState() == JFrame.MAXIMIZED_BOTH) { appConfig.projectSelectorIsMaximized = true; appConfig.projectSelectorWindowPosX = oldX; appConfig.projectSelectorWindowPosY = oldY; } else { appConfig.projectSelectorIsMaximized = false; appConfig.projectSelectorWindowWidth = ProjectSelector.this.getWidth(); appConfig.projectSelectorWindowHeight = ProjectSelector.this.getHeight(); } customParameters.setSize( 100, customParameters .getHeight()); // needed to ensure that the text field shrinks as well } public void componentMoved(ComponentEvent e) { oldX = appConfig.projectSelectorWindowPosX; oldY = appConfig.projectSelectorWindowPosY; appConfig.projectSelectorWindowPosX = ProjectSelector.this.getX(); appConfig.projectSelectorWindowPosY = ProjectSelector.this.getY(); } public void componentShown(ComponentEvent e) {} public void componentHidden(ComponentEvent e) {} }); // safe the overal config file when the project selector closes this.addWindowListener( new WindowListener() { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { appConfig.projectSelectorSelectedTab = 1 + right.getSelectedIndex(); appConfig.writeConfig(); } public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }); this.setLayout(new BorderLayout()); this.setResizable(true); if (appConfig.projectSelectorIsMaximized) { setExtendedState(JFrame.MAXIMIZED_BOTH); } this.setSize( new Dimension(appConfig.projectSelectorWindowWidth, appConfig.projectSelectorWindowHeight)); this.setLocation(appConfig.projectSelectorWindowPosX, appConfig.projectSelectorWindowPosY); JPanel left = new JPanel(); left.setLayout(new BorderLayout()); // List of all projects selection.setListData(projects); selection.setSelectedValue(appConfig.lastChosenProject, true); if (!selection.isSelectionEmpty()) { selectedProjectName = (String) selection.getSelectedValue(); } else { selectedProjectName = ""; } selection.addListSelectionListener(this); selection.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 0)); selection.setBackground(listPanel.getBackground()); listScroller = new JScrollPane(selection); listPanel.setLayout(new BorderLayout()); listScroller.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); listPanel.add(listScroller, BorderLayout.CENTER); listPanel.setBorder(BorderFactory.createTitledBorder("Available Projects")); left.add(listPanel, BorderLayout.CENTER); // OK / Cancel buttons buttonPanel.add(ok); buttonPanel.add(cancel); ok.addActionListener(this); cancel.addActionListener(this); buttonPanel.setPreferredSize(new Dimension(projectListWidth, 40)); left.add(buttonPanel, BorderLayout.SOUTH); this.add(left, BorderLayout.WEST); // right.setBorder(BorderFactory.createTitledBorder("Project Description & Configuration")); // The tab containing the description of the selected project JPanel description = new JPanel(); description.setLayout(new BorderLayout()); scrollableDescriptionPane = new JScrollPane(descriptionText); description.add(scrollableDescriptionPane); descriptionText.setEditable(false); descriptionText.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); int i = selection.getSelectedIndex(); if (i == -1) { // there was no defaultProject descriptionText.setText("Please select a project."); } else { generateGUIDescription(selectedProjectName); } right.addTab("Description", description); // The tab containing the config-file entries configuration.setLayout(new BoxLayout(configuration, BoxLayout.Y_AXIS)); scrollableConfigurationPane = new JScrollPane(frameworkConfigurationPanel); // increment the scroll speed (for some reason the speed for the scrollableConfigurationPane is // very low) scrollableConfigurationPane.getVerticalScrollBar().setUnitIncrement(15); frameworkConfigurationPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); configuration.add(scrollableConfigurationPane); JPanel bp = new JPanel(); bp.add(saveConfig); saveConfig.addActionListener(this); saveConfig.setMnemonic(java.awt.event.KeyEvent.VK_S); configuration.add(bp); expand = createFrameworkIconButton("expand", "expand.gif", "Show advanced settings"); collapse = createFrameworkIconButton("collapse", "collapse.gif", "Hide advanced settings"); customConfigurationPanel.setLayout(new BorderLayout()); JPanel mainCustomConfigurationPanel = new JPanel(); mainCustomConfigurationPanel.setLayout( new BoxLayout(mainCustomConfigurationPanel, BoxLayout.Y_AXIS)); mainCustomConfigurationPanel.add(customConfigurationPanel); // and the save button JPanel bp2 = new JPanel(); bp2.add(saveConfig2); saveConfig2.addActionListener(this); saveConfig2.setMnemonic(java.awt.event.KeyEvent.VK_S); mainCustomConfigurationPanel.add(bp2); right.addTab("Framework Config", configuration); right.addTab("Project Config", mainCustomConfigurationPanel); right.setMnemonicAt(0, java.awt.event.KeyEvent.VK_D); right.setMnemonicAt(1, java.awt.event.KeyEvent.VK_F); right.setMnemonicAt(2, java.awt.event.KeyEvent.VK_P); right.setSelectedIndex(appConfig.projectSelectorSelectedTab - 1); if (i == -1) { JTextField msg = new JTextField("Please select a project."); msg.setEditable(false); frameworkConfigurationPanel.add(msg); } else { generateGUIGonfiguration(selectedProjectName); } this.add(right, BorderLayout.CENTER); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.getRootPane().setDefaultButton(ok); this.setVisible(true); // this.setUndecorated(true); // GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this); }
public FilterPanel(Set<String> filters) { setPreferredSize(new Dimension(320, 240)); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] {0, 0}; gridBagLayout.rowHeights = new int[] {0, 0}; gridBagLayout.columnWeights = new double[] {1.0, 0.0}; gridBagLayout.rowWeights = new double[] {0.0, 1.0}; setLayout(gridBagLayout); textEditNewFilter = new JTextField(); GridBagConstraints gbc_textEditNewFilter = new GridBagConstraints(); gbc_textEditNewFilter.weightx = 1.0; gbc_textEditNewFilter.insets = new Insets(0, 0, 5, 5); gbc_textEditNewFilter.fill = GridBagConstraints.HORIZONTAL; gbc_textEditNewFilter.gridx = 0; gbc_textEditNewFilter.gridy = 0; add(textEditNewFilter, gbc_textEditNewFilter); textEditNewFilter.setColumns(10); JButton buttonAddFilter = new JButton("Add"); buttonAddFilter.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (textEditNewFilter.getText().length() > 0 && !filtersModel.contains(textEditNewFilter.getText())) { filtersModel.add(0, textEditNewFilter.getText()); textEditNewFilter.requestFocus(); } } }); GridBagConstraints gbc_buttonAddFilter = new GridBagConstraints(); gbc_buttonAddFilter.fill = GridBagConstraints.HORIZONTAL; gbc_buttonAddFilter.insets = new Insets(0, 0, 5, 0); gbc_buttonAddFilter.gridx = 1; gbc_buttonAddFilter.gridy = 0; add(buttonAddFilter, gbc_buttonAddFilter); jListFilters = new JList<>(); jListFilters.setBorder(new LineBorder(Color.LIGHT_GRAY)); GridBagConstraints gbc_jListFilters = new GridBagConstraints(); gbc_jListFilters.weighty = 1.0; gbc_jListFilters.weightx = 1.0; gbc_jListFilters.insets = new Insets(0, 0, 0, 5); gbc_jListFilters.fill = GridBagConstraints.BOTH; gbc_jListFilters.gridx = 0; gbc_jListFilters.gridy = 1; add(jListFilters, gbc_jListFilters); JButton buttonRemoveFilter = new JButton("Remove"); buttonRemoveFilter.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int selectedFilterIndex = jListFilters.getSelectedIndex(); if (selectedFilterIndex != -1) { filtersModel.removeElementAt(selectedFilterIndex); } if (filtersModel.getSize() > 0) { jListFilters.setSelectedIndex( Math.min(selectedFilterIndex, filtersModel.getSize() - 1)); } } }); GridBagConstraints gbc_buttonRemoveFilter = new GridBagConstraints(); gbc_buttonRemoveFilter.anchor = GridBagConstraints.NORTH; gbc_buttonRemoveFilter.gridx = 1; gbc_buttonRemoveFilter.gridy = 1; add(buttonRemoveFilter, gbc_buttonRemoveFilter); for (String filter : filters) { filtersModel.addElement(filter); } jListFilters.setModel(filtersModel); }
@SuppressWarnings("unchecked") // we must be compatible with 1.6 public VersionManagementPanel(final VisualCanvas canvas) { super(canvas); setLayout(new GridLayout()); // TODO @Christian Poliwoda what does manual testing mean? // numbers tested manually Dimension prefScrollPaneDim = new Dimension(100, 30); Dimension visibleRectDim = canvas.getVisibleRect().getSize(); final VersionController controller = canvas.getProjectController().getProject().getProjectFile(); final int numVersions = controller.getNumberOfVersions() - 1; versionData = new Object[numVersions]; ArrayList<RevCommit> versions = new ArrayList<RevCommit>(); try { versions = controller.getVersions(); } catch (IOException ex) { Logger.getLogger(VersionManagementPanel.class.getName()).log(Level.SEVERE, null, ex); } int maxTextwidth = 0; String longestText = null; // the history with timestamp and a short commit message for (int i = 1; i < versions.size(); i++) { String text = // + Message.generateHTMLSpace(3) new Date(versions.get(i).getCommitTime() * 1000L) + ": " + versions.get(i).getShortMessage(); // truncate texts that are too long int maxTextLength = 100; String dots = "..."; int textLength = text.length() - dots.length(); if (textLength > maxTextLength) { text = text.substring(0, maxTextLength) + dots; } versionData[versions.size() - i - 1] = new Version(text, i); if (text.length() > maxTextwidth) { maxTextwidth = text.length(); longestText = text; } } resultModel = new DefaultListModel(); // first init to show all if search not started yet for (int i = 0; i < versionData.length; i++) { resultModel.addElement(versionData[i]); } versionList = new JList(resultModel); // set the width of version managment window // dependent on largest git short message length double maxFontWidth = versionList .getFontMetrics(versionList.getFont()) .getStringBounds(longestText, versionList.getGraphics()) .getWidth(); if (maxFontWidth <= visibleRectDim.width) { prefScrollPaneDim.width = (int) maxFontWidth; } else { if (visibleRectDim.width < 400) { prefScrollPaneDim.width = visibleRectDim.width; } else { prefScrollPaneDim.width = 400; } } versionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); versionList.setOpaque(false); versionList.setBackground(VSwingUtil.TRANSPARENT_COLOR); versionList.setBorder(new EmptyBorder(3, 3, 3, 3)); Box upperTopBox = Box.createVerticalBox(); // press the commits to top with VerticalGlue // contains search area at top and // search results at the botton Box upperOuterBox = Box.createVerticalBox(); JButton searchButton = new JButton("search"); searchButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { searchAndAddToResultList(); } }); searchField = new JTextArea(); // search area box Box upperBox1 = Box.createHorizontalBox(); upperBox1.add(searchField); upperBox1.add(searchButton); Dimension fieldDim = new Dimension(Short.MAX_VALUE, searchField.getPreferredSize().height); searchField.setMaximumSize(fieldDim); searchField.addKeyListener( new KeyAdapter() { String tmp = ""; @Override public void keyReleased(KeyEvent ke) { searchAndAddToResultList(); } }); // upperOuterBox.add(upperBox1); upperTopBox.add(upperBox1); upperTopBox.add(upperOuterBox); // result area box Box upperBox2 = Box.createHorizontalBox(); upperBox2.add(Box.createHorizontalGlue()); upperBox2.add(versionList); upperBox2.add(Box.createHorizontalGlue()); upperOuterBox.add(upperBox2); upperOuterBox.add(Box.createVerticalGlue()); // added for optical reasons to force correct scrollbar position Box upperInnerBorderPane = Box.createHorizontalBox(); upperInnerBorderPane.add(upperOuterBox); upperInnerBorderPane.setBorder(new EmptyBorder(5, 15, 5, 15)); upperInnerBorderPane.setBackground(VSwingUtil.TRANSPARENT_COLOR); VScrollPane upperScrollPane = new VScrollPane(upperInnerBorderPane); upperScrollPane.setHorizontalScrollBarPolicy(VScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); upperScrollPane.setVerticalScrollBarPolicy(VScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); upperScrollPane.setMinimumSize(prefScrollPaneDim); JSplitPane splitPane = new VSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setEnabled(true); // true = transparent splitPane.setBackground(VSwingUtil.TRANSPARENT_COLOR); splitPane.setBorder(new EmptyBorder(5, 5, 5, 5)); splitPane.setDividerLocation(0.5); upperTopBox.add(upperScrollPane); splitPane.add(upperTopBox); // add in the upper part htmlCommit.setBackground(VSwingUtil.TRANSPARENT_COLOR); htmlCommit.setContentType("text/html"); htmlCommit.setOpaque(false); htmlCommit.setEditable(false); htmlCommit.setBorder(new EmptyBorder(0, 15, 0, 15)); Box lowerBox = Box.createVerticalBox(); lowerBox.setAlignmentX(Component.LEFT_ALIGNMENT); lowerBox.add(htmlCommit); lowerBox.add(Box.createVerticalGlue()); VScrollPane lowerScrollPane = new VScrollPane(lowerBox); lowerScrollPane.setHorizontalScrollBarPolicy(VScrollPane.HORIZONTAL_SCROLLBAR_NEVER); lowerScrollPane.setVerticalScrollBarPolicy(VScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); lowerScrollPane.setMinimumSize(new Dimension(0, 0)); // add in the lower part splitPane.setBottomComponent(lowerScrollPane); add(splitPane); versionList.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // show commit message in lower part if clicked on a row // in upper part if (e.getClickCount() == 1) { final VersionController controller = canvas.getProjectController().getProject().getProjectFile(); final int numVersions = controller.getNumberOfVersions() - 1; ArrayList<RevCommit> versions = new ArrayList<RevCommit>(); try { versions = controller.getVersions(); } catch (IOException ex) { Logger.getLogger(VersionManagementPanel.class.getName()) .log(Level.SEVERE, null, ex); } int versionIndex = ((Version) versionList.getSelectedValue()).getVersion(); htmlCommit.setText( "<html>" + "<pre> <font color=white><br>" + "<b>SHA-1:</b> " + versions.get(versionIndex).getName() + "<br><br>" + "<b>Message:</b><br><br>" + versions.get(versionIndex).getFullMessage() + "</pre></p>" + "</html>"); htmlCommit.setCaretPosition(0); } if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) { if (((Version) versionList.getSelectedValue()).getVersion() < 2) { VDialog.showMessageDialog( canvas, "Cannot Load Version", "The first version in a project contains no" + " sessions and cannot be loaded!"); return; } // if (VDialog.showConfirmDialog(canvas, // "Checkout Version:", // "<html><div align=Center>" // + "<p>Do you want to checkout the selected" // + " version?<p>" // + "<p><b>Unsaved changes will be lost!</b></p>" // + "</div></html>", // VDialog.DialogType.YES_NO) != VDialog.YES) { // return; // } int answer = VDialog.showConfirmDialog( canvas, "Checkout Version:", "<html><div align=Center>" + "<p>Checking out selected version.<p><br>" + "<p>Do you want to save the current session?</p><br>" + "<p><b>Unsaved changes will be lost!</b></p>" + "</div></html>", new String[] {"Save", "Discard", "Cancel"}); if (answer == 0) { try { canvas.getProjectController().saveProject(false); } catch (IOException ex) { Logger.getLogger(VersionManagement.class.getName()).log(Level.SEVERE, null, ex); VDialog.showMessageDialog( canvas, "Cannot save Project:", "<html><div align=Center>" + "Project cannot be saved!" + "</div></html>"); } } else if (answer == 1) { // nothing to do } else if (answer == 2) { return; } try { int versionIndex = ((Version) versionList.getSelectedValue()).getVersion(); canvas.setActive(false); String currentSessionName = canvas.getProjectController().getCurrentSession(); canvas.getProjectController().close(currentSessionName); controller.checkoutVersion(versionIndex); if (dialog != null) { dialog.close(); dialog = null; } if (canvas .getProjectController() .getProject() .getSessionFileByEntryName(currentSessionName) .exists()) { canvas.getProjectController().open(currentSessionName, false, true); } else { // VDialog.showMessageDialog(canvas, // "Cannot load \"" // + currentSessionName // +"\":", "<html><div align=Center>" // + "<p>The Session " // + Message.EMPHASIZE_BEGIN // + currentSessionName // + Message.EMPHASIZE_END // + " does not exist in the current" // + " version." // + "<p>The <b>Main</b>-Session will" // + "be loaded instead</div></html>"); canvas.getProjectController().open("Main", false, true); } } catch (IOException ex) { Logger.getLogger(VersionManagementPanel.class.getName()) .log(Level.SEVERE, null, ex); } } } }); // setMinimumSize(visibleRectDim); setMaximumSize(visibleRectDim); int width = getPreferredSize().width; setPreferredSize(new Dimension(width, (int) (visibleRectDim.height * 0.5))); } // end constructure
/** Setup GUI. */ private void setupGUI() { // start layout this.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTH; gbc.weightx = 1; gbc.weighty = 0; gbc.insets = new Insets(2, 5, 2, 5); JLabel plotsLabel = new JLabel( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.plots.column.label")); plotsLabel.setToolTipText( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.plots.column.tip")); this.add(plotsLabel, gbc); gbc.gridx = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0; this.add(errorIndicatorLabel, gbc); plotList = new JList(); plotList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); plotList.setBorder(BorderFactory.createLoweredBevelBorder()); plotList.addListSelectionListener(updatePlotListSelectionListener); plotList.setToolTipText( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.plots.column.tip")); gbc.insets = new Insets(2, 5, 2, 5); gbc.gridx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1; gbc.anchor = GridBagConstraints.NORTH; gbc.weightx = 1; gbc.gridwidth = 2; ExtendedJScrollPane plotSeriesScrollPane = new ExtendedJScrollPane(plotList); this.add(plotSeriesScrollPane, gbc); absoluteValuesCheckBox = new JCheckBox( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.absolute_values.label")); absoluteValuesCheckBox.setToolTipText( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.absolute_values.tip")); absoluteValuesCheckBox.setSelected(histogramTemplate.isUsingAbsoluteValues()); absoluteValuesCheckBox.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { histogramTemplate.setUseAbsoluteValues(absoluteValuesCheckBox.isSelected()); } }); gbc.gridy = 3; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = 0; // TODO: Add again when supported // this.add(absoluteValuesCheckBox, gbc); columnLogCheckBox = new JCheckBox( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.plots.log.label")); columnLogCheckBox.setToolTipText( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.plots.log.tip")); columnLogCheckBox.setSelected(histogramTemplate.isYAxisLogarithmic()); columnLogCheckBox.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { histogramTemplate.setYAxisLogarithmic(columnLogCheckBox.isSelected()); } }); gbc.gridy = 4; this.add(columnLogCheckBox, gbc); // rotateLabelsCheckBox = new JCheckBox(I18N.getMessage(I18N.getGUIBundle(), // "gui.plotter.histogram.rotate_labels.label")); // rotateLabelsCheckBox.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), // "gui.plotter.histogram.rotate_labels.tip")); // rotateLabelsCheckBox.addActionListener(updatePlotActionListener); // gbc.gridy = 5; // this.add(rotateLabelsCheckBox, gbc); JLabel binsLabel = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.bins.label")); binsLabel.setToolTipText( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.bins.tip")); gbc.gridy = 6; this.add(binsLabel, gbc); binsSlider = new JSlider(1, 100, histogramTemplate.getBins()); binsSlider.setMajorTickSpacing(99); binsSlider.setMinorTickSpacing(10); binsSlider.setPaintTicks(true); binsSlider.setPaintLabels(true); binsSlider.setToolTipText( I18N.getMessage( I18N.getGUIBundle(), "gui.plotter.histogram.bins.tip", binsSlider.getValue())); binsSlider.addChangeListener( new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { binsSlider.setToolTipText( I18N.getMessage( I18N.getGUIBundle(), "gui.plotter.histogram.bins.tip", binsSlider.getValue())); } }); binsSlider.addChangeListener( new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (e.getSource() instanceof JSlider) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { histogramTemplate.setBins(binsSlider.getValue()); } } } }); gbc.gridy = 7; this.add(binsSlider, gbc); JLabel opaquenessLabel = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.opaqueness.label")); opaquenessLabel.setToolTipText( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.opaqueness.tip")); gbc.gridy = 8; this.add(opaquenessLabel, gbc); opaqueSlider = new JSlider(1, 255, histogramTemplate.getOpacity()); opaqueSlider.setToolTipText( I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.histogram.opaqueness.tip")); opaqueSlider.addChangeListener( new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (e.getSource() instanceof JSlider) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { histogramTemplate.setOpaque(opaqueSlider.getValue()); } } } }); gbc.gridy = 9; this.add(opaqueSlider, gbc); // add export buttons JPanel exportPanel = new JPanel(new BorderLayout()); JButton exportImageButton = new JButton(new ExportImageAction(histogramTemplate)); JButton exportPdfButton = new JButton(new ExportPdfAction(histogramTemplate)); exportPanel.add(exportPdfButton, BorderLayout.PAGE_START); exportPanel.add(exportImageButton, BorderLayout.PAGE_END); gbc.gridy = 10; this.add(exportPanel, gbc); }
public FormPanel() { // each component has a default size Dimension dim = getPreferredSize(); // set the size of the formPanel dim.width = 250; setPreferredSize(dim); nameLabel = new JLabel("Name: "); occupationLabel = new JLabel("Occupation: "); // 10 is the default width in characters nameField = new JTextField(10); occupationField = new JTextField(10); okBtn = new JButton("OK"); ageList = new JList(); DefaultListModel ageModel = new DefaultListModel(); ageModel.addElement("Under 18"); ageModel.addElement("18 to 65"); ageModel.addElement("over 65"); ageList.setModel(ageModel); ageList.setPreferredSize(new Dimension(110, 68)); Border ageListBorder = BorderFactory.createEtchedBorder(); ageList.setBorder(ageListBorder); // set default value ageList.setSelectedIndex(1); /* when okBtn is clicked, submit the text entered * in the other 2 fields */ okBtn.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String name = nameField.getText(); String occupation = occupationField.getText(); FormEvent ev = new FormEvent(this, name, occupation); String ageCat = (String) ageList.getSelectedValue(); if (formListener != null) { formListener.formEventOccurred(ev); } } }); /* each graphic element can have a border, with setBorder. In this case, the * static method compoundBorder takes two border objects as parameters */ Border innerBorder = BorderFactory.createTitledBorder("Add Person"); Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5); setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder)); setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); ///////////////////// First Row ////////////////////////////////// /* as in Android, the weight dictates the relative amount of space each element * takes in relation with the others. */ gc.weightx = 1; gc.weighty = 0.2; gc.gridx = 0; gc.gridy = 0; gc.fill = GridBagConstraints.NONE; // the anchor method positions the content "inside" it's container gc.anchor = GridBagConstraints.LINE_END; add(nameLabel, gc); gc.gridx = 1; gc.gridy = 0; gc.anchor = GridBagConstraints.LINE_START; add(nameField, gc); ///////////////////// Second Row ////////////////////////////////// gc.weightx = 1; gc.weighty = 0.2; gc.gridx = 0; gc.gridy = 1; gc.anchor = GridBagConstraints.LINE_END; add(occupationLabel, gc); gc.gridx = 1; gc.gridy = 1; gc.anchor = GridBagConstraints.LINE_START; add(occupationField, gc); ///////////////////// Third Row ////////////////////////////////// gc.weightx = 1; gc.weighty = 4; gc.gridx = 1; gc.gridy = 2; gc.anchor = GridBagConstraints.FIRST_LINE_START; add(ageList, gc); ///////////////////// Foutrh Row ////////////////////////////////// gc.weightx = 1; gc.weighty = 0.2; gc.gridx = 1; gc.gridy = 3; // at the top-left corner of it's container gc.anchor = GridBagConstraints.FIRST_LINE_START; add(okBtn, gc); }