Search Results

Search found 54 results on 3 pages for 'flowlayout'.

Page 1/3 | 1 2 3  | Next Page >

  • Positioning child panels using FlowLayout

    - by extro
    I have two panels: main_panel child_panel The main_panel layout is set using: main_panel.setLayout(flowlayout) I then added child_panel to main_panel: main_panel.add(child_panel) The child_panel gets added to main_panel but its position is at the cross-section of horizontal midpoint and top vertical section of screen. I want child_panel to be at the top left corner, something I could have done by using child_panel.setlocation(a,b) method, if I have set the layout of main_panel as null. I have used FlowLayout here because I want components in the JPanel to keep adjusting with the size of JFrame. So can I add child_panel to main_panel at the exact location I want, even if I set the Layout of main_panel as not null?

    Read the article

  • Top alignment for FlowLayout

    - by mrpaint
    I'm using a FlowLayout JPanel. The panel looks ugly when it's children components height are different. I'm looking for a solution to make them top-align (similar to valign="top" with table cell in HTML). Sorry for my bad English and hope someone can come up with a brilliant idea. Thank you

    Read the article

  • Problem with FlowLayout

    - by atch
    public class MyFrame extends JFrame { public MyFrame(String title) { setSize(200, 200); setTitle(Integer.toString(super.getSize().width)); setLayout(new FlowLayout()); for (int i = 0; i < 5; ++i) { JButton b = new JButton(); b.setSize(90,50); b.setText(Integer.toString(b.getSize().width)); this.add(b);![alt text][1] } this.setVisible(true); } } why if having button widht 90 I'm getting window where three buttons are in one row instead of two?

    Read the article

  • Nested flowlayout panel not wrapping

    - by SnOrfus
    I've got a FlowLayoutPanel with properties: Dock = Fill (in a usercontrol) FlowDirection = TopDown WrapContents = false I do it this way so that each item added to the panel gets added to the bottom. The items that I add to this panel are usercontrols which themselves have FlowLayoutPanels on them, however they have the standard behaviour (LeftToRight, WrapContents = true). The problem that I'm having is that the interior usercontrol's FlowLayoutPanel isn't resizing to fill the outer control, but when I set autosizing to true on these controls, then the panel won't wrap its contents - which is a known problem apparently. If it helps visualize what I'm trying to do, it looks like this: ______________________________ | __________________________ | Outer box = exterior flowlayout | |Text____________________| | (TopDown, NoWrap) | | # # # # # # # # # # # #| | | | # # # # | | Interior boxes = usercontrols with text and a | |________________________| | flowlayoutpanel on them | __________________________ | (LeftToRight, Wrap) | |Text____________________| | | | # # # # # # # # # # # #| | # = pictures | | # # | | | |________________________| | |____________________________|

    Read the article

  • Swing layout with miglayout and nested panels

    - by Jazzepi
    I have a Swing program using SwingLayout. The structure of the Swing components looks like this. JFrame JPanel (Cardlayout) JPanel (Miglayout) - Main panel Jpanel (Flowlayout) - Checkbox Panel JPanel (Flowlayout) - Option Panel My problem right now is that I'm not sure how to prevent the checkbox panel from growing. I don't want it to "push" out the column that it's in to the right. I want Wraplayout (which works fine on the option panel) to wrap the content of the checkbox panel when it grows too big. This is the view of it from the Windowsbuilder GUI inside of Eclipse. The panel with the label "sites" in it is the Checkbox Panel. Directly to the right of the Checkbox panel is the Option panel. The big panel containing both of them is the main panel. http://i.imgur.com/S7Njo.png This is what happens when I add too many checkboxes http://i.imgur.com/f2SZz.png My main problem is that I don't understand why setting "grow 0" on the column constraint for the first column in mainpanel doesn't prevent it from growing when the component inside gets too big as I add new checkboxes to the site panel (the site panel can have an arbitrary number of checkboxes). This is my miglayout for the main panel. mainPanel.setLayout(new MigLayout("", "[][grow]", "[][][][][][][][grow]")); Here are my component constraints for when I add the checkbox panel siteCheckBoxPanel = new JPanel(); mainPanel.add(siteCheckBoxPanel, "cell 0 0,alignx left,gapx 0px,aligny center"); siteCheckBoxPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); I've also tried it without flow layout, and that doesn't fix anything. Any insight you could provide would be great! I'm also happy to provide more information if people have questions. FYI I've also tried "grow 0" on both the column and row constraint for the cell that the Checkbox Panel is inside.

    Read the article

  • -Java- Swing GUI - Moving around components specifically with layouts

    - by Xemiru Scarlet Sanzenin
    I'm making a little test GUI for something I'm making. However, problems occur with the positioning of the panels. public winInit() { super("Chatterbox - Login"); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (UnsupportedLookAndFeelException e) { } setSize(300,135); pn1 = new JPanel(); pn2 = new JPanel(); pn3 = new JPanel(); l1 = new JLabel("Username"); l2 = new JLabel("Password"); l3 = new JLabel("Random text here"); l4 = new JLabel("Server Address"); l5 = new JLabel("No address set."); i1 = new JTextField(10); p1 = new JPasswordField(10); b1 = new JButton("Connect"); b2 = new JButton("Register"); b3 = new JButton("Set IP"); l4.setBounds(10, 12, getDim(l4).width, getDim(l4).height); l1.setBounds(10, 35, getDim(l1).width, getDim(l1).height); l2.setBounds(10, 60, getDim(l2).width, getDim(l2).height); l3.setBounds(10, 85, getDim(l3).width, getDim(l3).height); l5.setBounds(l4.getBounds().width + 14, 12, l5.getPreferredSize().width, l5.getPreferredSize().height); l5.setForeground(Color.gray); i1.setBounds(getDim(l1).width + 15, 35, getDim(i1).width, getDim(i1).height); p1.setBounds(getDim(l1).width + 15, 60, getDim(p1).width, getDim(p1).height); b1.setBounds(getDim(l1).width + getDim(i1).width + 23, 34, getDim(b2).width, getDim(b1).height - 5); b2.setBounds(getDim(l1).width + getDim(i1).width + 23, 60, getDim(b2).width, getDim(b2).height - 5); b3.setBounds(getDim(l1).width + getDim(i1).width + 23, 10, etDim(b2).width, getDim(b3).height - 5); b1.addActionListener(clickButton); b2.addActionListener(clickButton); b3.addActionListener(clickButton); pn1.setLayout(new FlowLayout(FlowLayout.RIGHT)); pn2.setLayout(new FlowLayout(FlowLayout.RIGHT)); pn1.add(l1); pn1.add(i1); pn1.add(b1); pn2.add(l2); pn2.add(p1); pn2.add(b2); add(pn1); add(pn2); } I am attempting to use FlowLayout to position the panels in the way desired. I'd use BorderLayout while adding, but the vertical spacing is too far away when I just use directions closest to one another. The output of this code is to create a window, 300,150, place whatever's in the two panels in the exact same spaces. Yes, I realize there's useless code there with setBounds(), but that was just me screwing around with Absolute Positioning, which wasn't working out for me either.

    Read the article

  • Flowlayout panel and autosizing child controls doesn't work

    - by Pete
    I am trying to get a very simple autosizing layout on a winform (C# .NET). I've tried TableLayoutPanels and FlowLayoutPanels but nothing works. I have a usercontrol which is a container for other usercontrols which are created at runtime - I've called it StackPanel as I want it to list the child controls vertically. I've tried this using a FlowLayoutPanel, TableLayoutPanel and a Panel (with each control docked to the top). The child usercontrol consists of a label and then any number of radiobuttons (or any other standard control - it doesn't matter). When the child controls are created, the label text is set (if this is long it needs to wrap to a new line) and the radio buttons are added. There seems to be no combination of docking/autosizing or manual size setting using the Resize events that can get everything to show without clipping and still resize with the form. Thanks!

    Read the article

  • How to arrange labels in a flowlayout manner?

    - by Tim Büthe
    How do I arrange some UILabels and/or UIButtons of a variable length? I just want to add them to a UITableViewCell and they should arrange in a left-to-right flow, much like lines of text in a paragraph. I only found possibilities to create lables with a fixed size and position using "initWithFrame:...". Same seems to be true for Interface Builder, as far as I can tell. Any solution is appreciated no matter if it's done in code or using a custom cell XIB-file.

    Read the article

  • all individual panels are not shown inside root panel

    - by Suresh Kumar
    Respected sir/madam, I want to add multiple jpanels to jpanel.So i added a root panel to jscrollpane.and then added all individual jpanels to this root panel.I made jscrollpane's scrolling policy as needed.i.e HORIZONTAL_SCROLLBAR_AS_NEEDED,VERTICAL_SCROLLBAR_AS_NEEDED. But the problem is all individual panels are not shown inside root panel. Code: JScrollPane scPanel=new JScrollPane(); JPanel rootPanel=new JPanel(); rootPanel.setLayout(new FlowLayout()); JPanel indPanel = new JPanel(); rootPanel.add(indPanel); JPanel indPanel2 = new JPanel(); rootPanel.add(indPanel2); //.....like this added indPanals to rootPanel. scPanel.setViewPortView(rootPanel); //scPanel.setHorizontalScrollPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED); And one more thing is, as i scroll the scrollbar the panels are going out of jscrollpane area. I am not able to see all individual panels, Please suggest me.

    Read the article

  • Help with java GUI- has error in main thread

    - by jan
    Hello guys, Basically im trying to do a Insurance Application form in java. And it uses multiple JPanels in a JFrame. -adding of JPanel into main program frame was done like this: //jpCenterArea to hold jp1-jp7 jpCenterArea.add(jp1); jpCenterArea.add(jp2); jpCenterArea.add(jp3); jpCenterArea.add(jp4); ...etc ********Add Jpanels to JFrame*****/ add(jpTitle, BorderLayout.NORTH); add(jpCenterArea, BorderLayout.CENTER); add(jpBottom, BorderLayout.SOUTH); However, even though program can compile, it cannot be run. error as mentioned below: Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl<Container.java:1045> at java.awt.Container.add<Container.java:365> at TravelInsuranceApplication.<init>TravelInsuranceApplication.java:120> at TravelInsuranceApplication.main<TravelInsuranceApplication.java:154> 1 import javax.swing.*; 2 import java.awt.*; 3 public class TravelInsuranceApplication extends JFrame 4 { 5 //declare private variables 6 private JLabel jlblTitle, jlblName, jlblNRIC, jlblAdd, jlblPostal, jlblContact, jlblDOB, 7 jlblEmail, jlblPeriod; 8 private JLabel jlblDeparture, jlblDays, jlblZone, jlblPlan; 9 private JTextField jtfName, jtfIC, jtfAdd, jtfPostal, jtfContact, jtfEmail, jtfZone; 10 private JRadioButton jrbResident, jrbOffice, jrbDeluxe, jrbClassic, jrbAsia, jrbWorldwide; 11 private ButtonGroup bgContact, bgZone, bgPlan; 12 private JComboBox jcDay, jcMonth, jcYear; 13 private JButton jbtnSubmit, jbtnCalculate, jbtnClear; 14 private JPanel jpTitle,jp1, jp2, jp3, jp4, jp5, jp6, jp7, jpBottom, jpCenterArea; 15 String[] day = {"1", "2", "3"}; 16 String[] month = {"january", "february"}; 17 String[] year = {"1981", "1985", "1990", "1995"}; 18 19 //constructor and GUI development 20 public TravelInsuranceApplication() 21 { 22 setSize(500,200); 23 setTitle("Travel Insurance Application"); 24 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 25 setLayout(new BorderLayout()); 26 27 //create ALL component objects/ 28 jlblTitle = new JLabel("Travel Insurance Application: "); 29 jlblName = new JLabel("Name of Insured: "); 30 jlblNRIC = new JLabel("NRIC: "); 31 jlblAdd = new JLabel("Address: "); 32 jlblPostal = new JLabel("Postal Code: "); 33 jlblContact = new JLabel("Telephone: "); 34 jlblDOB = new JLabel("Date Of Birth: "); 35 jlblEmail = new JLabel("Email Address: "); 36 jlblPeriod = new JLabel("Period Of Insurance "); 37 jlblDeparture = new JLabel("Departure Date "); 38 jlblDays = new JLabel("How Many Days To Insure "); 39 jlblZone = new JLabel("Zone: "); 40 jlblPlan = new JLabel("Plan: "); 41 42 jtfName = new JTextField(50); 43 jtfIC = new JTextField(15); 44 jtfAdd = new JTextField(50); 45 jtfPostal = new JTextField(15); 46 jtfContact = new JTextField(15); 47 jtfEmail = new JTextField(50); 48 jtfZone = new JTextField(100); 49 50 jrbResident = new JRadioButton("Rseident/Pgr"); 51 jrbOffice = new JRadioButton("Office/HP"); 52 jrbAsia = new JRadioButton("Asia"); 53 jrbAsia = new JRadioButton("Worldwide"); 54 jrbDeluxe = new JRadioButton("Deluxe"); 55 jrbClassic = new JRadioButton("Classic"); 56 57 jcDay = new JComboBox(day); 58 jcMonth = new JComboBox(month); 59 jcYear = new JComboBox(year); 60 61 jbtnSubmit = new JButton("Submit"); 62 jbtnCalculate = new JButton("Calculate"); 63 jbtnClear = new JButton("Clear"); 64 65 /****create JPanels - jpTitle, JpCenterArea & jp2-jp8 , jpBottom + setLayout 66 for ALL JPanels******/ 67 jpTitle = new JPanel(new FlowLayout(FlowLayout.CENTER)); 68 jpCenterArea = new JPanel(new FlowLayout()); 69 jp1 = new JPanel(new FlowLayout()); 70 jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 71 jp3 = new JPanel(new FlowLayout()); 72 jp4 = new JPanel(new FlowLayout()); 73 jp5 = new JPanel(new FlowLayout()); 74 jp6 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 75 jp7 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 76 jpBottom = new JPanel(new FlowLayout(FlowLayout.CENTER)); 77 78 79 80 81 //add components to JPanels 82 jpTitle.add(jlblTitle); 83 84 //jp1 85 jp1.add(jlblName); 86 jp1.add(jtfName); 87 jp1.add(jlblNRIC); 88 jp1.add(jtfIC); 89 90 //jp2 91 jp2.add(jlblAdd); 92 jp2.add(jtfAdd); 93 jp2.add(jlblPostal); 94 jp2.add(jtfPostal); 95 96 //jp3 97 jp3.add(jlblContact); 98 jp3.add(jtfContact); 99 jp3.add(jrbResident); 100 jp3.add(jrbOffice); 101 jp3.add(jlblDOB); 102 jp3.add(jcDay); 103 jp3.add(jcMonth); 104 jp3.add(jcYear); 105 106 //jp4 107 jp4.add(jlblEmail); 108 jp4.add(jtfEmail); 109 110 //jp5 111 jp5.add(jlblPeriod); 112 jp5.add(jlblDeparture); 113 jp5.add(jcDay); 114 jp5.add(jcMonth); 115 jp5.add(jcYear); 116 jp5.add(jlblDays); 117 jp5.add(jcDay); 118 119 //jp6 120 jp6.add(jlblZone); 121 jp6.add(jrbAsia); 122 jp6.add(jrbWorldwide); 123 jp6.add(jlblPlan); 124 jp6.add(jrbDeluxe); 125 jp6.add(jrbClassic); 126 127 //jp7 128 jp7.add(jtfZone); 129 130 //jpCenterArea to hold jp1-jp7 131 jpCenterArea.add(jp1); 132 jpCenterArea.add(jp2); 133 jpCenterArea.add(jp3); 134 jpCenterArea.add(jp4); 135 jpCenterArea.add(jp5); 136 jpCenterArea.add(jp6); 137 jpCenterArea.add(jp7); 138 139 //jpBottom 140 jpBottom.add(jbtnSubmit); 141 jpBottom.add(jbtnCalculate); 142 jpBottom.add(jbtnClear); 143 144 /********Add Jpanels to JFrame*****/ 145 add(jpTitle, BorderLayout.NORTH); 146 add(jpCenterArea, BorderLayout.CENTER); 147 add(jpBottom, BorderLayout.SOUTH); 148 149 setVisible(true); 150 151 152 153 }//end null constructor 154 public static void main(String[] args) 155 { 156 TravelInsuranceApplication travel = new TravelInsuranceApplication(); 157 158 }//end main 159 160 }//end class

    Read the article

  • Search in Projects API

    - by Geertjan
    Today I got some help from Jaroslav Havlin, the creator of the new "Search in Projects API". Below are the steps to create a search provider that finds recently modified files, via a new tab in the "Find in Projects" dialog: Here's how to get to the above result. Create a new NetBeans module project named "RecentlyModifiedFilesSearch". Then set dependencies on these libraries: Search in Projects API Lookup API Utilities API Dialogs API Datasystems API File System API Nodes API Create and register an implementation of "SearchProvider". This class tells the application the name of the provider and how it can be used. It should be registered via the @ServiceProvider annotation.Methods to implement: Method createPresenter creates a new object that is added to the "Find in Projects" dialog when it is opened. Method isReplaceSupported should return true if this provider support replacing, not only searching. If you want to disable the search provider (e.g., there aren't required external tools available in the OS), return false from isEnabled. Method getTitle returns a string that will be shown in the tab in the "Find in Projects" dialog. It can be localizable. Example file "org.netbeans.example.search.ExampleSearchProvider": package org.netbeans.example.search; import org.netbeans.spi.search.provider.SearchProvider; import org.netbeans.spi.search.provider.SearchProvider.Presenter; import org.openide.util.lookup.ServiceProvider; @ServiceProvider(service = SearchProvider.class) public class ExampleSearchProvider extends SearchProvider { @Override public Presenter createPresenter(boolean replaceMode) { return new ExampleSearchPresenter(this); } @Override public boolean isReplaceSupported() { return false; } @Override public boolean isEnabled() { return true; } @Override public String getTitle() { return "Recent Files Search"; } } Next, we need to create a SearchProvider.Presenter. This is an object that is passed to the "Find in Projects" dialog and contains a visual component to show in the dialog, together with some methods to interact with it.Methods to implement: Method getForm returns a JComponent that should contain controls for various search criteria. In the example below, we have controls for a file name pattern, search scope, and the age of files. Method isUsable is called by the dialog to check whether the Find button should be enabled or not. You can use NotificationLineSupport passed as its argument to set a display error, warning, or info message. Method composeSearch is used to apply the settings and prepare a search task. It returns a SearchComposition object, as shown below. Please note that the example uses ComponentUtils.adjustComboForFileName (and similar methods), that modifies a JComboBox component to act as a combo box for selection of file name pattern. These methods were designed to make working with components created in a GUI Builder comfortable. Remember to call fireChange whenever the value of any criteria changes. Example file "org.netbeans.example.search.ExampleSearchPresenter": package org.netbeans.example.search; import java.awt.FlowLayout; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.netbeans.api.search.SearchScopeOptions; import org.netbeans.api.search.ui.ComponentUtils; import org.netbeans.api.search.ui.FileNameController; import org.netbeans.api.search.ui.ScopeController; import org.netbeans.api.search.ui.ScopeOptionsController; import org.netbeans.spi.search.provider.SearchComposition; import org.netbeans.spi.search.provider.SearchProvider; import org.openide.NotificationLineSupport; import org.openide.util.HelpCtx; public class ExampleSearchPresenter extends SearchProvider.Presenter { private JPanel panel = null; ScopeOptionsController scopeSettingsPanel; FileNameController fileNameComboBox; ScopeController scopeComboBox; ChangeListener changeListener; JSlider slider; public ExampleSearchPresenter(SearchProvider searchProvider) { super(searchProvider, false); } /** * Get UI component that can be added to the search dialog. */ @Override public synchronized JComponent getForm() { if (panel == null) { panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); JPanel row1 = new JPanel(new FlowLayout(FlowLayout.LEADING)); JPanel row2 = new JPanel(new FlowLayout(FlowLayout.LEADING)); JPanel row3 = new JPanel(new FlowLayout(FlowLayout.LEADING)); row1.add(new JLabel("Age in hours: ")); slider = new JSlider(1, 72); row1.add(slider); final JLabel hoursLabel = new JLabel(String.valueOf(slider.getValue())); row1.add(hoursLabel); row2.add(new JLabel("File name: ")); fileNameComboBox = ComponentUtils.adjustComboForFileName(new JComboBox()); row2.add(fileNameComboBox.getComponent()); scopeSettingsPanel = ComponentUtils.adjustPanelForOptions(new JPanel(), false, fileNameComboBox); row3.add(new JLabel("Scope: ")); scopeComboBox = ComponentUtils.adjustComboForScope(new JComboBox(), null); row3.add(scopeComboBox.getComponent()); panel.add(row1); panel.add(row3); panel.add(row2); panel.add(scopeSettingsPanel.getComponent()); initChangeListener(); slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { hoursLabel.setText(String.valueOf(slider.getValue())); } }); } return panel; } private void initChangeListener() { this.changeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { fireChange(); } }; fileNameComboBox.addChangeListener(changeListener); scopeSettingsPanel.addChangeListener(changeListener); slider.addChangeListener(changeListener); } @Override public HelpCtx getHelpCtx() { return null; // Some help should be provided, omitted for simplicity. } /** * Create search composition for criteria specified in the form. */ @Override public SearchComposition<?> composeSearch() { SearchScopeOptions sso = scopeSettingsPanel.getSearchScopeOptions(); return new ExampleSearchComposition(sso, scopeComboBox.getSearchInfo(), slider.getValue(), this); } /** * Here we return always true, but could return false e.g. if file name * pattern is empty. */ @Override public boolean isUsable(NotificationLineSupport notifySupport) { return true; } } The last part of our search provider is the implementation of SearchComposition. This is a composition of various search parameters, the actual search algorithm, and the displayer that presents the results.Methods to implement: The most important method here is start, which performs the actual search. In this case, SearchInfo and SearchScopeOptions objects are used for traversing. These objects were provided by controllers of GUI components (in the presenter). When something interesting is found, it should be displayed (with SearchResultsDisplayer.addMatchingObject). Method getSearchResultsDisplayer should return the displayer associated with this composition. The displayer can be created by subclassing SearchResultsDisplayer class or simply by using the SearchResultsDisplayer.createDefault. Then you only need a helper object that can create nodes for found objects. Example file "org.netbeans.example.search.ExampleSearchComposition": package org.netbeans.example.search; public class ExampleSearchComposition extends SearchComposition<DataObject> { SearchScopeOptions searchScopeOptions; SearchInfo searchInfo; int oldInHours; SearchResultsDisplayer<DataObject> resultsDisplayer; private final Presenter presenter; AtomicBoolean terminated = new AtomicBoolean(false); public ExampleSearchComposition(SearchScopeOptions searchScopeOptions, SearchInfo searchInfo, int oldInHours, Presenter presenter) { this.searchScopeOptions = searchScopeOptions; this.searchInfo = searchInfo; this.oldInHours = oldInHours; this.presenter = presenter; } @Override public void start(SearchListener listener) { for (FileObject fo : searchInfo.getFilesToSearch( searchScopeOptions, listener, terminated)) { if (ageInHours(fo) < oldInHours) { try { DataObject dob = DataObject.find(fo); getSearchResultsDisplayer().addMatchingObject(dob); } catch (DataObjectNotFoundException ex) { listener.fileContentMatchingError(fo.getPath(), ex); } } } } @Override public void terminate() { terminated.set(true); } @Override public boolean isTerminated() { return terminated.get(); } /** * Use default displayer to show search results. */ @Override public synchronized SearchResultsDisplayer<DataObject> getSearchResultsDisplayer() { if (resultsDisplayer == null) { resultsDisplayer = createResultsDisplayer(); } return resultsDisplayer; } private SearchResultsDisplayer<DataObject> createResultsDisplayer() { /** * Object to transform matching objects to nodes. */ SearchResultsDisplayer.NodeDisplayer<DataObject> nd = new SearchResultsDisplayer.NodeDisplayer<DataObject>() { @Override public org.openide.nodes.Node matchToNode( final DataObject match) { return new FilterNode(match.getNodeDelegate()) { @Override public String getDisplayName() { return super.getDisplayName() + " (" + ageInMinutes(match.getPrimaryFile()) + " minutes old)"; } }; } }; return SearchResultsDisplayer.createDefault(nd, this, presenter, "less than " + oldInHours + " hours old"); } private static long ageInMinutes(FileObject fo) { long fileDate = fo.lastModified().getTime(); long now = System.currentTimeMillis(); return (now - fileDate) / 60000; } private static long ageInHours(FileObject fo) { return ageInMinutes(fo) / 60; } } Run the module, select a node in the Projects window, press Ctrl-F, and you'll see the "Find in Projects" dialog has two tabs, the second is the one you provided above:

    Read the article

  • Button inside text box

    - by user542719
    My code shows a button inside a textbox, but when the input value changes, the size of the text box also changes. That I don't like. Is there any solution such that the textbox size remains fixed? Or any other idea on how to create a button inside textbox? The following is my code: JPanel panel = new JPanel(); panel.setLayout( new FlowLayout(FlowLayout.CENTER, 0, 0) ); panel.add(textField); panel.add(button); panel.setBackground( textField.getBackground() ); panel.setBorder( textField.getBorder() ); textField.setBorder(null);

    Read the article

  • How to center Label vertical and horizontal in draw2d Figure ?

    - by aphex
    I have the following situation: Label label = new Label(); label.setText("bla"); RoundedRectangle fig = new RoundedRectangle(); fig.add(label); FlowLayout layout = new FlowLayout(); layout.setStretchMinorAxis(true); fig.setLayoutManager(layout); fig.setOpaque(true); That works only to center the label vertical or horizontal by using layout.setHorizontal(true/false); , but not together. Any idea how to make it work ?

    Read the article

  • Question about layout in java.

    - by extro
    I have two panels main_panel and child_panel. I have set layout for main_panel by using "main_panel.setLayout(flowlayout)" and added child_panel in main_panel by using "main_panel.add(child_panel)". This child_panel gets added to main_panel but its position is at the cross-section of horizontal midpoint and top vertical section of screen. But I want child_panel to be at the top left corner, something I could have done by using "child_panel.setlocation(a,b)" method, if I have set the Layout of main_panel as NULL. I have used flowlayout here because I want components in the JPanel to keep adjusting with the size of JFrame. So question is, can I add child_panel to main_panel at the exact location I want, even if I set the Layout of main_panel as not NULL.

    Read the article

  • How To Make Moving News Bar in Windows Forms Application without Timer

    - by Ehab Sutan
    I'm making a desktop application in C# which contains a moving News Bar labels. I'm using a timer to move these labels but the problem is that when i make the interval of this timer low (1-10 for example) the application takes very high percentage of CPU Usage, And when i make it higher(200 -500 ) the movement of the labels becomes intermittent or not smooth movement even that the user may not be able to read the news in Comfortable way. ((More Information)) it is Windows form application. the way i move the labels is as follows : the news items from RSS feeds are represented in a group of linklabels. All these linklabels are added to a flowlayout container. The timer moves the whole flowlayout container. I found this way according to my knowledge the best way to making the news bar. If you have better idea or solution please help

    Read the article

  • Laying out JPanels to make a simple GUI

    - by Elvis
    Hello, first of all, this is more or less my first GUI and ive learned Java for not more then a week, so it might contain some serious programming errors. What i have right now is: Buttons and labels are part of OptionPanel and are on the left, DrawingPanel is about 5x5 px in size and is on the right. What I am trying to do is a simple test, to get me more familiar with the GUI. The rectangle should be movable and re-sizeable by the user when clicking the respective buttons: http://www.upload.ee/image/612005/JFrame2.jpg Right now i have: JFrame MainFrame - Makes JFrame (Not using the setSize function. using .pack() instead. not sure about it) JPanel MergedPanel - FlowLayout - Adds JPanel OptionsPanel and JPanel DrawingPanel together and gets injected to JFrame MainFrame JPanel DrawPanel - This JPanel is responsible of drawing the rectangle. JPanel OptionPanel - FlowLayout - This JPanel is responsible of the buttons. Help please.

    Read the article

  • Using getters/setters in Java

    - by Crystal
    I'm having some trouble with the idea of accessing variables from other classes. I had a post here: http://stackoverflow.com/questions/3011642/having-access-to-a-private-variable-from-other-classes-in-java where I got some useful information, and thought an example would be better show it, and ask a separate question as well. I have a form that I can input data to, and it has a List variable. I didn't make it static at first, but I thought if I needed to get the total size from another class, then I wouldn't create an instance of that class in order to use the function to getTotalContacts. I basically want to update my status bar with the total number of contacts that are in my list. One of the members said in the above post to use the original Foo member to get the contacts, but I'm not sure how that works in this case. Any thoughts would be appreciated. Thanks. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class AddressBook { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { AddressBookFrame frame = new AddressBookFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open"); JMenuItem saveItem = new JMenuItem("Save"); JMenuItem saveAsItem = new JMenuItem("Save As"); JMenuItem printItem = new JMenuItem("Print"); JMenuItem exitItem = new JMenuItem("Exit"); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(saveAsItem); fileMenu.add(printItem); fileMenu.add(exitItem); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); JMenuItem newItem = new JMenuItem("New"); JMenuItem editItem = new JMenuItem("Edit"); JMenuItem deleteItem = new JMenuItem("Delete"); JMenuItem findItem = new JMenuItem("Find"); JMenuItem firstItem = new JMenuItem("First"); JMenuItem previousItem = new JMenuItem("Previous"); JMenuItem nextItem = new JMenuItem("Next"); JMenuItem lastItem = new JMenuItem("Last"); editMenu.add(newItem); editMenu.add(editItem); editMenu.add(deleteItem); editMenu.add(findItem); editMenu.add(firstItem); editMenu.add(previousItem); editMenu.add(nextItem); editMenu.add(lastItem); menuBar.add(editMenu); JMenu helpMenu = new JMenu("Help"); JMenuItem documentationItem = new JMenuItem("Documentation"); JMenuItem aboutItem = new JMenuItem("About"); helpMenu.add(documentationItem); helpMenu.add(aboutItem); menuBar.add(helpMenu); frame.setVisible(true); } }); } } class AddressBookFrame extends JFrame { public AddressBookFrame() { setLayout(new BorderLayout()); setTitle("Address Book"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); AddressBookToolBar toolBar = new AddressBookToolBar(); add(toolBar, BorderLayout.NORTH); AddressBookStatusBar aStatusBar = new AddressBookStatusBar(); add(aStatusBar, BorderLayout.SOUTH); AddressBookForm form = new AddressBookForm(); add(form, BorderLayout.CENTER); } public static final int DEFAULT_WIDTH = 500; public static final int DEFAULT_HEIGHT = 500; } /* Create toolbar buttons and add buttons to toolbar */ class AddressBookToolBar extends JPanel { public AddressBookToolBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); JToolBar bar = new JToolBar(); JButton newButton = new JButton("New"); JButton editButton = new JButton("Edit"); JButton deleteButton = new JButton("Delete"); JButton findButton = new JButton("Find"); JButton firstButton = new JButton("First"); JButton previousButton = new JButton("Previous"); JButton nextButton = new JButton("Next"); JButton lastButton = new JButton("Last"); bar.add(newButton); bar.add(editButton); bar.add(deleteButton); bar.add(findButton); bar.add(firstButton); bar.add(previousButton); bar.add(nextButton); bar.add(lastButton); add(bar); } } /* Creates the status bar string */ class AddressBookStatusBar extends JPanel { public AddressBookStatusBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); this.statusBarString = new JLabel("Total: " + AddressBookForm.getTotalContacts()); add(this.statusBarString); } public void updateLabel() { contactsLabel.setText(AddressBookForm.getTotalContacts().toString()); } private JLabel statusBarString; private JLabel contactsLabel; } class AddressBookForm extends JPanel { public AddressBookForm() { // create form panel this.setLayout(new GridLayout(2, 1)); JPanel formPanel = new JPanel(); formPanel.setLayout(new GridLayout(4, 2)); firstName = new JTextField(20); lastName = new JTextField(20); telephone = new JTextField(20); email = new JTextField(20); JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT); formPanel.add(firstNameLabel); formPanel.add(firstName); JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT); formPanel.add(lastNameLabel); formPanel.add(lastName); JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT); formPanel.add(telephoneLabel); formPanel.add(telephone); JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT); formPanel.add(emailLabel); formPanel.add(email); add(formPanel); // create button panel JPanel buttonPanel = new JPanel(); JButton insertButton = new JButton("Insert"); JButton displayButton = new JButton("Display"); ActionListener insertAction = new AddressBookListener(); ActionListener displayAction = new AddressBookListener(); insertButton.addActionListener(insertAction); displayButton.addActionListener(displayAction); buttonPanel.add(insertButton); buttonPanel.add(displayButton); add(buttonPanel); } public static int getTotalContacts() { return addressList.size(); } //void addContact(Person contact); private JTextField firstName; private JTextField lastName; private JTextField telephone; private JTextField email; private JLabel contacts; private static List<Person> addressList = new ArrayList<Person>(); private class AddressBookListener implements ActionListener { public void actionPerformed(ActionEvent e) { String buttonPressed = e.getActionCommand(); System.out.println(buttonPressed); if (buttonPressed == "Insert") { Person aPerson = new Person(firstName.getText(), lastName.getText(), telephone.getText(), email.getText()); addressList.add(aPerson); } else { for (Person p : addressList) { System.out.println(p); } } } } } My other question is why do I get the error, "int cannot be dereferenced contactsLabel.setText(AddressbookForm.getTotalContacts().toString()); Thanks!

    Read the article

  • Passing ActionListeners in Java, pack()

    - by Crystal
    Two questions. First question is I'm trying to create a simple form that when you press a button, it adds a Person object to the ArrayList. However, since I am not used to GUIs, I tried creating one and am first just trying to get the user input from the JTextField, create an ActionListener object of the appropriate type, so once that works, then I can pass in all the JTextField inputs to create my Person object. Unfortunately, I am not getting any data when I type in something to the firstName JTextField and was wondering if someone could look at my code below. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class AddressBook { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { AddressBookFrame frame = new AddressBookFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open"); JMenuItem saveItem = new JMenuItem("Save"); JMenuItem saveAsItem = new JMenuItem("Save As"); JMenuItem printItem = new JMenuItem("Print"); JMenuItem exitItem = new JMenuItem("Exit"); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(saveAsItem); fileMenu.add(printItem); fileMenu.add(exitItem); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); JMenuItem newItem = new JMenuItem("New"); JMenuItem editItem = new JMenuItem("Edit"); JMenuItem deleteItem = new JMenuItem("Delete"); JMenuItem findItem = new JMenuItem("Find"); JMenuItem firstItem = new JMenuItem("First"); JMenuItem previousItem = new JMenuItem("Previous"); JMenuItem nextItem = new JMenuItem("Next"); JMenuItem lastItem = new JMenuItem("Last"); editMenu.add(newItem); editMenu.add(editItem); editMenu.add(deleteItem); editMenu.add(findItem); editMenu.add(firstItem); editMenu.add(previousItem); editMenu.add(nextItem); editMenu.add(lastItem); menuBar.add(editMenu); JMenu helpMenu = new JMenu("Help"); JMenuItem documentationItem = new JMenuItem("Documentation"); JMenuItem aboutItem = new JMenuItem("About"); helpMenu.add(documentationItem); helpMenu.add(aboutItem); menuBar.add(helpMenu); frame.setVisible(true); } }); } } class AddressBookFrame extends JFrame { public AddressBookFrame() { setLayout(new BorderLayout()); setTitle("Address Book"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); AddressBookToolBar toolBar = new AddressBookToolBar(); add(toolBar, BorderLayout.NORTH); AddressBookStatusBar aStatusBar = new AddressBookStatusBar("5"); add(aStatusBar, BorderLayout.SOUTH); AddressBookForm form = new AddressBookForm(); add(form, BorderLayout.CENTER); } public static final int DEFAULT_WIDTH = 500; public static final int DEFAULT_HEIGHT = 500; } /* Create toolbar buttons and add buttons to toolbar */ class AddressBookToolBar extends JPanel { public AddressBookToolBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); JToolBar bar = new JToolBar(); JButton newButton = new JButton("New"); JButton editButton = new JButton("Edit"); JButton deleteButton = new JButton("Delete"); JButton findButton = new JButton("Find"); JButton firstButton = new JButton("First"); JButton previousButton = new JButton("Previous"); JButton nextButton = new JButton("Next"); JButton lastButton = new JButton("Last"); bar.add(newButton); bar.add(editButton); bar.add(deleteButton); bar.add(findButton); bar.add(firstButton); bar.add(previousButton); bar.add(nextButton); bar.add(lastButton); add(bar); } } /* Creates the status bar string */ class AddressBookStatusBar extends JPanel { public AddressBookStatusBar(String statusBarString) { setLayout(new FlowLayout(FlowLayout.LEFT)); this.statusBarString = new JLabel("Total number of people: " + statusBarString); add(this.statusBarString); } private JLabel statusBarString; private int totalContacts; } class AddressBookForm extends JPanel { public AddressBookForm() { this.setLayout(new GridLayout(2, 1)); JPanel formPanel = new JPanel(); formPanel.setLayout(new GridLayout(4, 2)); JTextField firstName = new JTextField(20); JTextField lastName = new JTextField(20); JTextField telephone = new JTextField(20); JTextField email = new JTextField(20); JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT); formPanel.add(firstNameLabel); formPanel.add(firstName); JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT); formPanel.add(lastNameLabel); formPanel.add(lastName); JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT); formPanel.add(telephoneLabel); formPanel.add(telephone); JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT); formPanel.add(emailLabel); formPanel.add(email); add(formPanel); JPanel buttonPanel = new JPanel(); JButton insertButton = new JButton("Insert"); JButton displayButton = new JButton("Display"); // create button actions AddressBookManager insertAction = new AddressBookManager(firstName.getText()); insertButton.addActionListener(insertAction); buttonPanel.add(insertButton); buttonPanel.add(displayButton); add(buttonPanel); } private List<Person> addressList = new ArrayList<Person>(); private class AddressBookManager implements ActionListener { public AddressBookManager(String text) { // addressList.add( setName(text); System.out.println("Test" + text); } public void actionPerformed(ActionEvent e) { System.out.println("Hello" + name); } public void setName(String name) { this.name = name; } private String name; } } Second question is, how do I make my form not take up the whole center space. I don't like the stretch look and was hoping the JTextFields could be just one line long, not a big box. Same thing with the buttons. Any thoughts? Thanks.

    Read the article

  • Image not loading onto JPanel?

    - by None None
    I have been trying to figure out how to add an image to a JPanel as a background, but still have complete control over the placing of JButtons, JLabels, and etc. This is one method I found, but it is crashing and not loading the image or buttons. Here is the code: import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; public class PanelDemo extends JFrame { private static final long serialVersionUID = 1L; private JButton btn1 = new JButton("EASY"); private JButton btn2 = new JButton("MEDIUM"); private JButton btn3 = new JButton("HARD"); private JButton btn4 = new JButton("High Score"); public PanelDemo() { super("Image Panel Demo"); JPanel panel = new ImagePanel( new FlowLayout(FlowLayout.CENTER, 50, 180)); JPanel panelbtn = new JPanel(new GridLayout(4, 1)); btn1.setBackground(new java.awt.Color(0, 0, 0)); btn1.setFont(new java.awt.Font("Showcard Gothic", 1, 24)); btn1.setForeground(new java.awt.Color(0, 255, 102)); btn2.setBackground(new java.awt.Color(0, 0, 0)); btn2.setFont(new java.awt.Font("Showcard Gothic", 1, 24)); btn2.setForeground(new java.awt.Color(0, 255, 102)); btn3.setBackground(new java.awt.Color(0, 0, 0)); btn3.setFont(new java.awt.Font("Showcard Gothic", 1, 24)); btn3.setForeground(new java.awt.Color(0, 255, 102)); btn4.setBackground(new java.awt.Color(0, 0, 0)); btn4.setFont(new java.awt.Font("Showcard Gothic", 1, 24)); btn4.setForeground(new java.awt.Color(0, 255, 102)); panel.add(panelbtn); panelbtn.add(btn1); panelbtn.add(btn2); panelbtn.add(btn3); panelbtn.add(btn4); add(panel, BorderLayout.CENTER); setSize(640, 480); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String... args) { new PanelDemo().setVisible(true); } } ImagePanel.java import java.awt.Graphics; import java.awt.Image; import java.awt.LayoutManager; import javax.swing.ImageIcon; import javax.swing.JPanel; public class ImagePanel extends JPanel { private static final long serialVersionUID = 1L; String imageFile = "/rsc/img/background.jpg"; public ImagePanel() { super(); } public ImagePanel(String image) { super(); this.imageFile = image; } public ImagePanel(LayoutManager layout) { super(layout); } public void paintComponent(Graphics g) { ImageIcon imageicon = new ImageIcon(getClass().getResource(imageFile)); Image image = imageicon.getImage(); super.paintComponent(g); if (image != null) g.drawImage(image, 0, 0, getWidth(), getHeight(), this); } } Error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(Unknown Source) at ImagePanel.paintComponent(ImagePanel.java:27) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JLayeredPane.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paintToOffscreen(Unknown Source) at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source) at javax.swing.RepaintManager$PaintManager.paint(Unknown Source) at javax.swing.RepaintManager.paint(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source) at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source) at sun.awt.SunGraphicsCallback.runComponents(Unknown Source) at java.awt.Container.paint(Unknown Source) at java.awt.Window.paint(Unknown Source) at javax.swing.RepaintManager$3.run(Unknown Source) at javax.swing.RepaintManager$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.access$1000(Unknown Source) at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) Also, if anyone knows of a better way to put a background image on a JPanel, pease do tell. Thank you in advance.

    Read the article

  • Multiple Components in a JTree Node Renderer & Node Editor

    - by Samad Lotia
    I am attempting to create a JTree where a node has several components: a JPanel that holds a JCheckBox, followed by a JLabel, then a JComboBox. I have attached the code at the bottom if one wishes to run it. Fortunately the JTree correctly renders the components. However when I click on the JComboBox, the node disappears; if I click on the JCheckBox, it works fine. It seems that I am doing something wrong with how the TreeCellEditor is being set up. How could I resolve this issue? Am I going beyond the capabilities of JTree? Here's a quick overview of the code I have posted below. The class EntityListDialog merely creates the user interface. It is not useful to understand it other than the createTree method. Node is the data structure that holds information about each node in the JTree. All Nodes have a name, but samples may be null or an empty array. This should be evident by looking at EntityListDialog's createTree method. The name is used as the text of the JCheckBox. If samples is non-empty, it is used as the contents of the JCheckBox. NodeWithSamplesRenderer renders Nodes whose samples are non-empty. It creates the complicated user interface with the JPanel consisting of the JCheckBox and the JComboBox. NodeWithoutSamplesRenderer creates just a JCheckBox when samples is empty. RendererDispatcher decides whether to use a NodeWithSamplesRenderer or a NodeWithoutSamplesRenderer. This entirely depends on whether Node has a non-empty samples member or not. It essentially functions as a means for the NodeWith*SamplesRenderer to plug into the JTree. Code listing: import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.tree.*; public class EntityListDialog { final JDialog dialog; final JTree entitiesTree; public EntityListDialog() { dialog = new JDialog((Frame) null, "Test"); entitiesTree = createTree(); JScrollPane entitiesTreeScrollPane = new JScrollPane(entitiesTree); JCheckBox pathwaysCheckBox = new JCheckBox("Do additional searches"); JButton sendButton = new JButton("Send"); JButton cancelButton = new JButton("Cancel"); JButton selectAllButton = new JButton("All"); JButton deselectAllButton = new JButton("None"); dialog.getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JPanel selectPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); selectPanel.add(new JLabel("Select: ")); selectPanel.add(selectAllButton); selectPanel.add(deselectAllButton); c.gridx = 0; c.gridy = 0; c.weightx = 1.0; c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; dialog.getContentPane().add(selectPanel, c); c.gridx = 0; c.gridy = 1; c.weightx = 1.0; c.weighty = 1.0; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(0, 5, 0, 5); dialog.getContentPane().add(entitiesTreeScrollPane, c); c.gridx = 0; c.gridy = 2; c.weightx = 1.0; c.weighty = 0.0; c.insets = new Insets(0, 0, 0, 0); c.fill = GridBagConstraints.HORIZONTAL; dialog.getContentPane().add(pathwaysCheckBox, c); JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonsPanel.add(sendButton); buttonsPanel.add(cancelButton); c.gridx = 0; c.gridy = 3; c.weightx = 1.0; c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; dialog.getContentPane().add(buttonsPanel, c); dialog.pack(); dialog.setVisible(true); } public static void main(String[] args) { EntityListDialog dialog = new EntityListDialog(); } private static JTree createTree() { DefaultMutableTreeNode root = new DefaultMutableTreeNode( new Node("All Entities")); root.add(new DefaultMutableTreeNode( new Node("Entity 1", "Sample A", "Sample B", "Sample C"))); root.add(new DefaultMutableTreeNode( new Node("Entity 2", "Sample D", "Sample E", "Sample F"))); root.add(new DefaultMutableTreeNode( new Node("Entity 3", "Sample G", "Sample H", "Sample I"))); JTree tree = new JTree(root); RendererDispatcher rendererDispatcher = new RendererDispatcher(tree); tree.setCellRenderer(rendererDispatcher); tree.setCellEditor(rendererDispatcher); tree.setEditable(true); return tree; } } class Node { final String name; final String[] samples; boolean selected; int selectedSampleIndex; public Node(String name, String... samples) { this.name = name; this.selected = false; this.samples = samples; if (samples == null) { this.selectedSampleIndex = -1; } else { this.selectedSampleIndex = 0; } } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } public String toString() { return name; } public int getSelectedSampleIndex() { return selectedSampleIndex; } public void setSelectedSampleIndex(int selectedSampleIndex) { this.selectedSampleIndex = selectedSampleIndex; } public String[] getSamples() { return samples; } } interface Renderer { public void setForeground(final Color foreground); public void setBackground(final Color background); public void setFont(final Font font); public void setEnabled(final boolean enabled); public Component getComponent(); public Object getContents(); } class NodeWithSamplesRenderer implements Renderer { final DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel(); final JPanel panel = new JPanel(); final JCheckBox checkBox = new JCheckBox(); final JLabel label = new JLabel(" Samples: "); final JComboBox comboBox = new JComboBox(comboBoxModel); final JComponent components[] = {panel, checkBox, comboBox, label}; public NodeWithSamplesRenderer() { Boolean drawFocus = (Boolean) UIManager.get("Tree.drawsFocusBorderAroundIcon"); if (drawFocus != null) { checkBox.setFocusPainted(drawFocus.booleanValue()); } for (int i = 0; i < components.length; i++) { components[i].setOpaque(true); } panel.add(checkBox); panel.add(label); panel.add(comboBox); } public void setForeground(final Color foreground) { for (int i = 0; i < components.length; i++) { components[i].setForeground(foreground); } } public void setBackground(final Color background) { for (int i = 0; i < components.length; i++) { components[i].setBackground(background); } } public void setFont(final Font font) { for (int i = 0; i < components.length; i++) { components[i].setFont(font); } } public void setEnabled(final boolean enabled) { for (int i = 0; i < components.length; i++) { components[i].setEnabled(enabled); } } public void setContents(Node node) { checkBox.setText(node.toString()); comboBoxModel.removeAllElements(); for (int i = 0; i < node.getSamples().length; i++) { comboBoxModel.addElement(node.getSamples()[i]); } } public Object getContents() { String title = checkBox.getText(); String[] samples = new String[comboBoxModel.getSize()]; for (int i = 0; i < comboBoxModel.getSize(); i++) { samples[i] = comboBoxModel.getElementAt(i).toString(); } Node node = new Node(title, samples); node.setSelected(checkBox.isSelected()); node.setSelectedSampleIndex(comboBoxModel.getIndexOf(comboBoxModel.getSelectedItem())); return node; } public Component getComponent() { return panel; } } class NodeWithoutSamplesRenderer implements Renderer { final JCheckBox checkBox = new JCheckBox(); public NodeWithoutSamplesRenderer() { Boolean drawFocus = (Boolean) UIManager.get("Tree.drawsFocusBorderAroundIcon"); if (drawFocus != null) { checkBox.setFocusPainted(drawFocus.booleanValue()); } } public void setForeground(final Color foreground) { checkBox.setForeground(foreground); } public void setBackground(final Color background) { checkBox.setBackground(background); } public void setFont(final Font font) { checkBox.setFont(font); } public void setEnabled(final boolean enabled) { checkBox.setEnabled(enabled); } public void setContents(Node node) { checkBox.setText(node.toString()); } public Object getContents() { String title = checkBox.getText(); Node node = new Node(title); node.setSelected(checkBox.isSelected()); return node; } public Component getComponent() { return checkBox; } } class NoNodeRenderer implements Renderer { final JLabel label = new JLabel(); public void setForeground(final Color foreground) { label.setForeground(foreground); } public void setBackground(final Color background) { label.setBackground(background); } public void setFont(final Font font) { label.setFont(font); } public void setEnabled(final boolean enabled) { label.setEnabled(enabled); } public void setContents(String text) { label.setText(text); } public Object getContents() { return label.getText(); } public Component getComponent() { return label; } } class RendererDispatcher extends AbstractCellEditor implements TreeCellRenderer, TreeCellEditor { final static Color selectionForeground = UIManager.getColor("Tree.selectionForeground"); final static Color selectionBackground = UIManager.getColor("Tree.selectionBackground"); final static Color textForeground = UIManager.getColor("Tree.textForeground"); final static Color textBackground = UIManager.getColor("Tree.textBackground"); final JTree tree; final NodeWithSamplesRenderer nodeWithSamplesRenderer = new NodeWithSamplesRenderer(); final NodeWithoutSamplesRenderer nodeWithoutSamplesRenderer = new NodeWithoutSamplesRenderer(); final NoNodeRenderer noNodeRenderer = new NoNodeRenderer(); final Renderer[] renderers = { nodeWithSamplesRenderer, nodeWithoutSamplesRenderer, noNodeRenderer }; Renderer renderer = null; public RendererDispatcher(JTree tree) { this.tree = tree; Font font = UIManager.getFont("Tree.font"); if (font != null) { for (int i = 0; i < renderers.length; i++) { renderers[i].setFont(font); } } } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { final Node node = extractNode(value); if (node == null) { renderer = noNodeRenderer; noNodeRenderer.setContents(tree.convertValueToText( value, selected, expanded, leaf, row, false)); } else { if (node.getSamples() == null || node.getSamples().length == 0) { renderer = nodeWithoutSamplesRenderer; nodeWithoutSamplesRenderer.setContents(node); } else { renderer = nodeWithSamplesRenderer; nodeWithSamplesRenderer.setContents(node); } } renderer.setEnabled(tree.isEnabled()); if (selected) { renderer.setForeground(selectionForeground); renderer.setBackground(selectionBackground); } else { renderer.setForeground(textForeground); renderer.setBackground(textBackground); } renderer.getComponent().repaint(); renderer.getComponent().invalidate(); renderer.getComponent().validate(); return renderer.getComponent(); } public Component getTreeCellEditorComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) { return getTreeCellRendererComponent( tree, value, true, expanded, leaf, row, true); } public Object getCellEditorValue() { return renderer.getContents(); } public boolean isCellEditable(final EventObject event) { if (!(event instanceof MouseEvent)) { return false; } final MouseEvent mouseEvent = (MouseEvent) event; final TreePath path = tree.getPathForLocation( mouseEvent.getX(), mouseEvent.getY()); if (path == null) { return false; } Object node = path.getLastPathComponent(); if (node == null || (!(node instanceof DefaultMutableTreeNode))) { return false; } DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node; Object userObject = treeNode.getUserObject(); return (userObject instanceof Node); } private static Node extractNode(Object value) { if ((value != null) && (value instanceof DefaultMutableTreeNode)) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object userObject = node.getUserObject(); if ((userObject != null) && (userObject instanceof Node)) { return (Node) userObject; } } return null; } }

    Read the article

  • ComboBox Data Binding

    - by Geertjan
    Let's create a databound combobox, levering MVC in a desktop application. The result will be a combobox, provided by the NetBeans ChoiceView, that displays data retrieved from a database: What follows is not much different from the NetBeans Platform CRUD Application Tutorial and you're advised to consult that document if anything that follows isn't clear enough. One kind of interesting thing about the instructions that follow is that it shows that you're able to create an application where each element of the MVC architecture can be located within a separate module: Start by creating a new NetBeans Platform application named "MyApplication". Model We're going to start by generating JPA entity classes from a database connection. In the New Project wizard, choose "Java Class Library". Click Next. Name the Java Class Library "MyEntities". Click Finish. Right-click the MyEntities project, choose New, and then select "Entity Classes from Database". Work through the wizard, selecting the tables of interest from your database, and naming the package "entities". Click Finish. Now a JPA entity is created for each of the selected tables. In the Project Properties dialog of the project, choose "Copy Dependent Libraries" in the Packaging panel. Build the project. In your project's "dist" folder (visible in the Files window), you'll now see a JAR, together with a "lib" folder that contains the JARs you'll need. In your NetBeans Platform application, create a module named "MyModel", with code name base "org.my.model". Right-click the project, choose Properties, and in the "Libraries" panel, click Add Dependency button in the Wrapped JARs subtab to add all the JARs from the previous step to the module. Also include "derby-client.jar" or the equivalent driver for your database connection to the module. Controler In your NetBeans Platform application, create a module named "MyControler", with code name base "org.my.controler". Right-click the module's Libraries node, in the Projects window, and add a dependency on "Explorer & Property Sheet API". In the MyControler module, create a class with this content: package org.my.controler; import org.openide.explorer.ExplorerManager; public class MyUtils { static ExplorerManager controler; public static ExplorerManager getControler() { if (controler == null) { controler = new ExplorerManager(); } return controler; } } View In your NetBeans Platform application, create a module named "MyView", with code name base "org.my.view".  Create a new Window Component, in "explorer" view, for example, let it open on startup, with class name prefix "MyView". Add dependencies on the Nodes API and on the Explorer & Property Sheet API. Also add dependencies on the "MyModel" module and the "MyControler" module. Before doing so, in the "MyModel" module, make the "entities" package and the "javax.persistence" packages public (in the Libraries panel of the Project Properties dialog) and make the one package that you have in the "MyControler" package public too. Define the top part of the MyViewTopComponent as follows: public final class MyViewTopComponent extends TopComponent implements ExplorerManager.Provider { ExplorerManager controler = MyUtils.getControler(); public MyViewTopComponent() { initComponents(); setName(Bundle.CTL_MyViewTopComponent()); setToolTipText(Bundle.HINT_MyViewTopComponent()); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); controler.setRootContext(new AbstractNode(Children.create(new ChildFactory<Customer>() { @Override protected boolean createKeys(List list) { EntityManager entityManager = Persistence. createEntityManagerFactory("MyEntitiesPU").createEntityManager(); Query query = entityManager.createNamedQuery("Customer.findAll"); list.addAll(query.getResultList()); return true; } @Override protected Node createNodeForKey(Customer key) { Node customerNode = new AbstractNode(Children.LEAF, Lookups.singleton(key)); customerNode.setDisplayName(key.getName()); return customerNode; } }, true))); controler.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { Customer selectedCustomer = controler.getSelectedNodes()[0].getLookup().lookup(Customer.class); StatusDisplayer.getDefault().setStatusText(selectedCustomer.getName()); } }); JPanel row1 = new JPanel(new FlowLayout(FlowLayout.LEADING)); row1.add(new JLabel("Customers: ")); row1.add(new ChoiceView()); add(row1); } @Override public ExplorerManager getExplorerManager() { return controler; } ... ... ... Now run the application and you'll see the same as the image with which this blog entry started.

    Read the article

  • ActionListener problem

    - by thegamer
    Hello, i am trying to make an actionListener on a button in another button which has also an actionlistener and i just couldn't figure it out for some way. I am trying to make an action on the 2nd button but i couldn't figure it out.If anyone helps me i'd appreciate! here is the code below: import java.awt.; import java.awt.event.; import javax.swing.; import java.io.; import java.util.*; public class basic implements ActionListener{ public static void main(String[] args) { basic process = new basic (); } public basic(){ JFrame fan = new JFrame("Scheme"); JPanel one = new JPanel(new BorderLayout()); fan.add(one); JPanel uno = new JPanel(); uno.setLayout(new BoxLayout(uno, BoxLayout.Y_AXIS)); JButton addB = new JButton("first choice"); addB.setAlignmentX(Component.CENTER_ALIGNMENT); uno.add(addB); addDButton.setActionCommand("hehe"); addDButton.addActionListener(this); one.add(uno,BorderLayout.CENTER); fan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fan.setSize(500,700); fan.setLocationByPlatform(true); fan.setVisible(true); } public void actionPerformed(ActionEvent evt) { JPanel markP = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,20)); JDialog dialog = new JDialog((JFrame)null); dialog.getContentPane().add(markP,BorderLayout.CENTER); if (evt.getActionCommand().equals("hehe")) { JLabel title = new JLabel("Proceed"); title.setFont(new Font("Arial",Font.BOLD,15)); markP.add(title,BorderLayout.NORTH); JButton exit = new JButton("Exit"); markP.add(exit); //here i want to create another actionListener on the exit button only without affecting the other content which is in the button "addB " so that when i click on the addB button the J dialog pops up, and than when i click on exit button the program will return to the menu.I couldn't figure it out. dialog.toFront(); dialog.setModal(true); dialog.pack(); // dialog.setLocationRelativeTo(null); // dialog.setVisible(true); } // here the code goes on but the problem is that of the actionListener which is concerned.

    Read the article

  • How to set text above and below a JButton icon?

    - by mre
    I want to set text above and below a JButton's icon. At the moment, in order to achieve this, I override the layout manager and use three JLabel instances (i.e. 2 for text and 1 for the icon). But this seems like a dirty solution. Is there a more direct way of doing this? Note -I'm not looking for a multi-line solution, I'm looking for a multi-label solution. Although this article refers to it as a multi-line solution, it actually seems to refer to a multi-label solution. EXAMPLE import java.awt.Component; import java.awt.FlowLayout; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.UIManager; public final class JButtonDemo { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI(){ final JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new FlowLayout()); frame.add(new JMultiLabelButton()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static final class JMultiLabelButton extends JButton { private static final long serialVersionUID = 7650993517602360268L; public JMultiLabelButton() { super(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(new JCenterLabel("Top Label")); add(new JCenterLabel(UIManager.getIcon("OptionPane.informationIcon"))); add(new JCenterLabel("Bottom Label")); } } private static final class JCenterLabel extends JLabel { private static final long serialVersionUID = 5502066664726732298L; public JCenterLabel(final String s) { super(s); setAlignmentX(Component.CENTER_ALIGNMENT); } public JCenterLabel(final Icon i) { super(i); setAlignmentX(Component.CENTER_ALIGNMENT); } } }

    Read the article

1 2 3  | Next Page >