Layouts
Tabs, a split pane, a grid of buttons and a table.
What you will learn#
JTabbedPane,JSplitPane,GridLayout,JTablewith a model,- selecting in a list to change another control.
The program#
# Tutorial 18: layouts - tabs, a split pane, a grid and a table
load "java.ring"
using {
"javax.swing"
"java.awt"
"javax.swing.table"
}
oFrame = new JFrame("Layouts")
oFrame.setDefaultCloseOperation(2)
oFrame.setSize([520,340])
oFrame.setLocationRelativeTo(NULL)
oTabs = new JTabbedPane
# tab 1: a grid of buttons (GridLayout: rows, columns, gaps)
oGrid = new JPanel((new GridLayout).@New([3,3,6,6]))
for nI = 1 to 9
oGrid.add(new JButton("" + nI))
next
oTabs.addTab([ "Grid" , oGrid ])
# tab 2: a split pane with a list on the left and a text on the right
oNames = new DefaultListModel
for cName in ["Ring","Java","Swing","Maven","JDBC"]
oNames.addElement(cName)
next
oList = new JList(oNames)
oText = new JTextArea("Select a name in the list")
oText.setEditable(false)
oSplit = (new JSplitPane).@New([1,new JScrollPane(oList),new JScrollPane(oText)])
oSplit.setDividerLocation(120)
oTabs.addTab([ "Split" , oSplit ])
oList.addListSelectionListener("onSelect")
# tab 3: a table (a model with columns and rows)
oModel = (new DefaultTableModel).@New([["Language","Year"],0])
oModel.addRow(["Ring",2016])
oModel.addRow(["Java",1995])
oModel.addRow(["C",1972])
oTable = new JTable(oModel)
oTable.setAutoCreateRowSorter(true) # click a column header to sort
oTabs.addTab([ "Table" , new JScrollPane(oTable) ])
oFrame.add(oTabs)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
func onSelect aArgs
if oList.getSelectedIndex() >= 0
oText.setText("You selected " + oList.getSelectedValue() + nl + "The list has " + oNames.size() + " names")
ok
How it works#
A layout decides where the controls go. BorderLayout has five areas, GridLayout is rows and columns, and a split pane divides the space between two components. A table gets its rows from a DefaultTableModel; add a row with addRow.
Exercises#
- Add a fourth tab.
- Sort the table by a column (
setAutoCreateRowSorter(true)). - Put the list and the table in a split pane.