Title: Java Swing MVC Example - Java Code Geeks
Open Graph Title: Java Swing MVC Example - Java Code Geeks
Description: In this example we are going to demonstrate Java Swing MVC, The MVC pattern is a model of how a user interface can be structured. Therefore it defines the
Open Graph Description: In this example we are going to demonstrate Java Swing MVC, The MVC pattern is a model of how a user interface can be structured. Therefore it defines the
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/"},"author":{"name":"Ashraf Sarhan","@id":"https://examples.javacodegeeks.com/#/schema/person/553eb8f56e9ffb76e6bcc85d6157fc91"},"headline":"Java Swing MVC Example","datePublished":"2016-01-26T13:00:23+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/"},"wordCount":483,"commentCount":3,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","keywords":["Swing MVC"],"articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/","url":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/","name":"Java Swing MVC Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2016-01-26T13:00:23+00:00","description":"In this example we are going to demonstrate Java Swing MVC, The MVC pattern is a model of how a user interface can be structured. Therefore it defines the","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-development/core-java/java-swing-mvc-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"Java Swing MVC Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/553eb8f56e9ffb76e6bcc85d6157fc91","name":"Ashraf Sarhan","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2024/04/cropped-ashraf_sarhan_photo-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2024/04/cropped-ashraf_sarhan_photo-96x96.jpg","caption":"Ashraf Sarhan"},"description":"Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.","sameAs":["http://www.javacodegeeks.com","https://www.facebook.com/ashraf.sar7an","https://eg.linkedin.com/in/ashrafsarhan","https://x.com/http://twitter.com/ashraf_sarhan"],"url":"https://examples.javacodegeeks.com/author/ashraf-sarhan/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2016-01-26T15:00:23+02:00","datePublished":"2016-01-26T15:00:23+02:00","dateModified":"2016-01-23T09:48:47+02:00","headline":"Java Swing MVC Example","name":"Java Swing MVC Example","keywords":"Swing MVC","url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/java-swing-mvc-example\/","description":"In this example we are going to demonstrate Java Swing MVC, The MVC pattern is a model of how a user interface can be structured. Therefore it defines the following 3 elements: Model that represents t","copyrightYear":"2016","articleSection":"Core Java","articleBody":"In this example we are going to demonstrate Java Swing MVC, The MVC pattern is a model of how a user interface can be structured. Therefore it defines the following 3 elements:\r\n\r\n\tModel that represents the data for the application.\r\n\tView that is the visual representation of that data.\r\n\tController that takes user input on the view and translates that to changes in the model.\r\n\r\n\r\n1. MVC Components\r\n1.1. Model\r\nA model is an abstraction of something that is presented to the user. The models provided by Swing fall into two general categories: GUI-state models and application-data models.\u00a0GUI state models are interfaces that define the visual status of a GUI control, such as whether a button is pressed or armed like ButtonModel. An application-data model is an interface that represents some quantifiable data that the UI\u00a0presents to the user, such as the value of a cell in a table like TableModel.\r\n1.2. View\r\nThe view is a UI\u00a0component that is responsible for presenting data to the user. Thus it is responsible for all UI dependent issues like layout, drawing, etc. JTable is a good example for the view.\r\n1.3. Controller\r\nA controller encapsulates the application code that is executed in order to an user interaction (mouse motion, mouse click, key press, etc.). Controllers might need input for their execution and they produce output. They read their input from models and update models as result of the execution. In swing a controller is normally implemented by an ActionListener or Action.\r\n\r\n\r\n\r\nNow, lets see our concrete Swing MVC example where we have an application that let you filter\u00a0stocks. The application UI contains\u00a0a text field where the user can enter a filter\u00a0string, button to start the filter and table\u00a0where the filter\u00a0results are displayed.\r\n2. Swing MVC Example\r\n2.1. Model\r\nWe create Model.java class which implements the TableModel interface (or, more likely, subclass the AbstractTableModel class). The job of this\u00a0TableModel implementation is to serve as the interface between your data and the\u00a0JTable as a view component. Also, we add a supplementary Constants.java class contains constants used through our code.\r\n\r\nModel.java:\r\npackage com.jcg;\r\n\r\nimport javax.swing.table.DefaultTableModel;\r\n\r\n\/**\r\n * @author ashraf\r\n *\r\n *\/\r\n@SuppressWarnings(\"serial\")\r\npublic class Model extends DefaultTableModel {\r\n\r\n\tpublic Model() {\r\n\t\tsuper(Constants.DATA, Constants.TABLE_HEADER);\r\n\t}\r\n\r\n}\r\n\r\nConstants.java:\r\npackage com.jcg;\r\n\r\n\/**\r\n * @author ashraf_sarhan\r\n * \r\n *\/\r\npublic class Constants {\r\n\r\n\tpublic static final Object[] TABLE_HEADER = { \"Symbol\", \"Company Name\",\r\n\t\t\t\"Price\", \"Change\", \"% Change\", \"Volume\" };\r\n\r\n\tpublic static final Object[][] DATA = {\r\n\t\t\t{ \"BAC\", \"Bank of America Corporation\", 15.98, 0.14, \"+0.88%\",\r\n\t\t\t\t\t32157250 },\r\n\t\t\t{ \"AAPL\", \"Apple Inc.\", 126.57, -1.97, \"-1.54%\", 31367143 },\r\n\t\t\t{ \"ABBV\", \"AbbVie Inc.\", 57.84, -2.43, \"-4.03%\", 30620258 },\r\n\t\t\t{ \"ECA\", \"Encana Corporation\", 11.74, -0.53, \"-4.33%\", 27317436 },\r\n\t\t\t{ \"VALE\", \"Vale S.A.\", 6.55, -0.33, \"-4.80%\", 19764400 },\r\n\t\t\t{ \"FB\", \"Facebook, Inc.\", 81.53, 0.64, \"+0.78%\", 16909729 },\r\n\t\t\t{ \"PBR\", \"Petr\u00f3leo Brasileiro S.A. - Petrobras\", 6.05, -0.12,\r\n\t\t\t\t\t\"-2.02%\", 16181759 },\r\n\t\t\t{ \"NOK\", \"Nokia Corporation\", 8.06, 0.01, \"+0.12%\", 13611860 },\r\n\t\t\t{ \"PCYC\", \"Pharmacyclics Inc.\", 254.67, 24.19, \"+10.50%\", 13737834 },\r\n\t\t\t{ \"RAD\", \"Rite Aid Corporation\", 7.87, -0.18, \"-2.24%\", 13606253 } };\r\n\t\r\n}\r\n\r\n2.2. View\r\nWe create View.java class which contains\u00a0our main UI components, a JTextField where the user can enter a filter\u00a0string, JButton to start the filter and\u00a0JTable where the filter\u00a0results are displayed.\r\n\r\nView.java:\r\npackage com.jcg;\r\n\r\nimport java.awt.Dimension;\r\n\r\nimport javax.swing.BorderFactory;\r\nimport javax.swing.JButton;\r\nimport javax.swing.JFrame;\r\nimport javax.swing.JPanel;\r\nimport javax.swing.JScrollPane;\r\nimport javax.swing.JSplitPane;\r\nimport javax.swing.JTable;\r\nimport javax.swing.JTextField;\r\nimport javax.swing.border.TitledBorder;\r\n\r\n\/**\r\n * @author ashraf\r\n *\r\n *\/\r\npublic class View {\r\n\r\n\tpublic View() {\r\n\t\t\/\/ Create views swing UI components \r\n\t\tJTextField searchTermTextField = new JTextField(26);\r\n\t\tJButton filterButton = new JButton(\"Filter\");\r\n\t\tJTable table = new JTable();\r\n\r\n\t\t\/\/ Create table model\r\n\t\tModel model = new Model();\r\n\t\ttable.setModel(model);\r\n\r\n\t\t\/\/ Create controller\r\n\t\tController controller = new Controller(searchTermTextField, model);\r\n\t\tfilterButton.addActionListener(controller);\r\n\r\n\t\t\/\/ Set the view layout\r\n\t\tJPanel ctrlPane = new JPanel();\r\n\t\tctrlPane.add(searchTermTextField);\r\n\t\tctrlPane.add(filterButton);\r\n\r\n\t\tJScrollPane tableScrollPane = new JScrollPane(table);\r\n\t\ttableScrollPane.setPreferredSize(new Dimension(700, 182));\r\n\t\ttableScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), \"Market Movers\",\r\n\t\t\t\tTitledBorder.CENTER, TitledBorder.TOP));\r\n\r\n\t\tJSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ctrlPane, tableScrollPane);\r\n\t\tsplitPane.setDividerLocation(35);\r\n\t\tsplitPane.setEnabled(false);\r\n\r\n\t\t\/\/ Display it all in a scrolling window and make the window appear\r\n\t\tJFrame frame = new JFrame(\"Swing MVC Demo\");\r\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n\t\tframe.add(splitPane);\r\n\t\tframe.pack();\r\n\t\tframe.setLocationRelativeTo(null);\r\n\t\tframe.setVisible(true);\r\n\t}\r\n\r\n}\r\n\r\n2.3. Controller\r\nWe create Controller.java class which implements the\u00a0ActionListener interface, it will be invoked as a result of a user\u2019s action on a view (i.e., it will be invoked because of the filter button click).\r\n\r\nController.java:\r\npackage com.jcg;\r\n\r\nimport java.awt.event.ActionEvent;\r\nimport java.awt.event.ActionListener;\r\n\r\nimport javax.swing.JOptionPane;\r\nimport javax.swing.JTextField;\r\nimport javax.swing.table.DefaultTableModel;\r\n\r\n\/**\r\n * @author ashraf\r\n *\r\n *\/\r\npublic class Controller implements ActionListener {\r\n\t\r\n\tprivate JTextField searchTermTextField = new JTextField(26);\r\n\tprivate DefaultTableModel model;\r\n\r\n\tpublic Controller(JTextField searchTermTextField, DefaultTableModel model) {\r\n\t\tsuper();\r\n\t\tthis.searchTermTextField = searchTermTextField;\r\n\t\tthis.model = model;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void actionPerformed(ActionEvent e) {\r\n\r\n\t\tString searchTerm = searchTermTextField.getText();\r\n\t\tif (searchTerm != null && !\"\".equals(searchTerm)) {\r\n\t\t\tObject[][] newData = new Object[Constants.DATA.length][];\r\n\t\t\tint idx = 0;\r\n\t\t\tfor (Object[] o: Constants.DATA) {\r\n\t\t\t\tif (\"*\".equals(searchTerm.trim())) {\r\n\t\t\t\t\tnewData[idx++] = o;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(String.valueOf(o[0]).startsWith(searchTerm.toUpperCase().trim())){\r\n\t\t\t\t\t\tnewData[idx++] = o;\r\n\t\t\t\t\t}\t\r\n\t\t\t\t}\t\r\n\t\t\t}\r\n\t\t\tmodel.setDataVector(newData, Constants.TABLE_HEADER);\r\n\t\t} else {\r\n\t\t\tJOptionPane.showMessageDialog(null,\r\n\t\t\t\t\t\"Search term is empty\", \"Error\",\r\n\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\n2.4. Running the Swing MVC Example\r\nWe create SwingMVCDemo.java class which serve as main class to running our example.\r\n\r\nSwingMVCDemo.java:\r\npackage com.jcg;\r\n\r\nimport javax.swing.SwingUtilities;\r\n\r\n\/**\r\n * @author ashraf_sarhan\r\n * \r\n *\/\r\npublic class SwingMVCDemo {\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tSwingUtilities.invokeLater(new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tcreateAndShowGUI();\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\tpublic static void createAndShowGUI() throws Exception {\r\n\t\tnew View();\r\n\t}\r\n}\r\n\r\nOutput:\r\n\r\n\r\n3. Download the Source Code\r\nThis was an example to show Java Swing MVC.\r\nDownload\r\nYou can download the full source code of this example here: SwingMVCExampleCode.zip","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/java-swing-mvc-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Ashraf Sarhan","url":"https:\/\/examples.javacodegeeks.com\/author\/ashraf-sarhan\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:author | https://www.facebook.com/ashraf.sar7an |
| article:published_time | 2016-01-26T13:00:23+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Ashraf Sarhan |
| twitter:card | summary_large_image |
| twitter:creator | @http://twitter.com/ashraf_sarhan |
| twitter:label1 | Written by |
| twitter:data1 | Ashraf Sarhan |
| twitter:label2 | Est. reading time |
| twitter:data2 | 5 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1