- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Components in JRuby Swing
In this part of the JRuby Swing programming tutorial, we will cover basic Swing components.
Components are basic building blocks of a GUI application. Over the years, several components became a standard in all toolkits on all OS platforms. For example a button, a check box or a scroll bar. Swing has a rich set of components which covers most of the programming needs. More specialised components can be created as custom components.
JCheckBox
The JCheckBox
is a component that has two states: on and off. The On state is visualised by a check mark. It is used to denote some boolean property. The JCheckBox
component provides a check box with a text label.
#!/usr/local/bin/jruby # ZetCode JRuby Swing tutorial # # This program uses JCheckBox # component to show/hide the title # of the window # # author: Jan Bodnar # website: www.zetcode.com # last modified: December 2010 include Java import java.awt.Dimension import javax.swing.JCheckBox import javax.swing.Box import javax.swing.BoxLayout import javax.swing.JFrame class Example < JFrame def initialize super "JCheckBox example" self.initUI end def initUI self.setLayout BoxLayout.new getContentPane, BoxLayout::Y_AXIS self.add Box.createRigidArea Dimension.new 15, 20 cb = JCheckBox.new "Show Title", true cb.setBounds 50, 60, 80, 30 cb.setFocusable(false) cb.add_action_listener do |e| if self.getTitle.empty? self.setTitle "JCheckBox example" else self.setTitle "" end end add cb self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE self.setSize 300, 200 self.setLocationRelativeTo nil self.setVisible true end end Example.new
In our example, we place a check box on the window. The check box shows or hides the title of the window.
self.setLayout BoxLayout.new getContentPane, BoxLayout::Y_AXIS self.add Box.createRigidArea Dimension.new 15, 20
In this example, we use a BoxLayout
layout manager. We put some space there, so that the check box is not too close to the corner.
cb = JCheckBox.new "Show Title", true
The JCheckBox
component is created. The first parameter of the constructor is its text label. The second parameter is a boolean value indicating the initial selection state. If true the check box is selected.
cb.setFocusable false
We disable the focus for the check box. A JCheckBox
that has a focus may be selected or unselected with a spacebar.
cb.add_action_listener do |e| if self.getTitle.empty? self.setTitle "JCheckBox example" else self.setTitle "" end end
Inside the action listener, we check if the title is set. If there is a title, we remove it. If there is no title, we set one. This way we toggle the visibility of a title.

JLabel
The JLabel
component is used to display text, image or both. No user interaction is available.
#!/usr/local/bin/jruby # ZetCode JRuby Swing tutorial # # In this program, we show lyrics of a # song in a window. # # author: Jan Bodnar # website: www.zetcode.com # last modified: December 2010 include Java import java.awt.BorderLayout import java.awt.Color import java.awt.Font import javax.swing.JFrame import javax.swing.BorderFactory import javax.swing.JPanel import javax.swing.JLabel class Example < JFrame def initialize super "Lyrics" self.initUI end def initUI lyrics = "<html>It's way too late to think of<br> Someone I would call now<br> And neon signs got tired<br> Red eye flights help the stars out<br> I'm safe in a corner<br> Just hours before me<br> <br> I'm waking with the roaches<br> The world has surrendered<br> I'm dating ancient ghosts<br> The ones I made friends with<br> The comfort of fireflies<br> Long gone before daylight<br> <br> And if I had one wishful field tonight<br> I'd ask for the sun to never rise<br> If God leant his voice for me to speak<br> I'd say go to bed, world<br> <br> I've always been too late<br> To see what's before me<br> And I know nothing sweeter than<br> Champaign from last New Years<br> Sweet music in my ears<br> And a night full of no fears<br> <br> But if I had one wishful field tonight<br> I'd ask for the sun to never rise<br> If God passed a mic to me to speak<br> I'd say stay in bed, world<br> Sleep in peace</html>" panel = JPanel.new panel.setLayout BorderLayout.new 10, 10 label = JLabel.new lyrics label.setFont Font.new "Georgia", Font::PLAIN, 14 label.setForeground Color.new 50, 50, 25 panel.add label, BorderLayout::CENTER panel.setBorder BorderFactory.createEmptyBorder 10, 10, 10, 10 self.add panel self.pack self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE self.setLocationRelativeTo nil self.setVisible true end end Example.new
Our example shows lyrics of a song in the window. We can use HTML tags in JLabel
component. We use the <br> tag to separate lines.
lyrics = "<html>It's way too late to think of<br> Someone I would call now<br> And neon signs got tired<br> ...
We define a multi line text.
label = JLabel.new lyrics label.setFont Font.new "Georgia", Font::PLAIN, 14
Here we create the label component. We set its font to plain Georgia, 14px tall.
panel.add label, BorderLayout::CENTER panel.setBorder BorderFactory.createEmptyBorder 10, 10, 10, 10
We put the label into the center of the panel. We put 10px around the label.

JSlider
JSlider
is a component that lets the user graphically select a value by sliding a knob within a bounded interval. Our example will show a volume control.
#!/usr/local/bin/jruby # ZetCode JRuby Swing tutorial # # In this program we use a JSlider # component to control volume images. # # author: Jan Bodnar # website: www.zetcode.com # last modified: December 2010 include Java import java.awt.Dimension import java.awt.BorderLayout import javax.swing.event.ChangeListener import javax.swing.JFrame import javax.swing.JSlider import javax.swing.JLabel import javax.swing.JPanel import javax.swing.BorderFactory import javax.swing.Box import javax.swing.BoxLayout import javax.swing.ImageIcon class ChangeEvent include ChangeListener def setLabel label @label = label end def setIcons mute, min, med, max @mute = mute @min = min @med = med @max = max end def stateChanged e sender = e.getSource value = sender.getValue if value == 0 @label.setIcon(@mute) elsif value > 0 and value <= 30 @label.setIcon(@min) elsif value > 30 and value < 80 @label.setIcon(@med) else @label.setIcon(@max) end end end class Example < JFrame def initialize super "JSlider" self.initUI end def initUI mute = ImageIcon.new "mute.png" min = ImageIcon.new "min.png" med = ImageIcon.new "med.png" max = ImageIcon.new "max.png" panel = JPanel.new panel.setLayout BoxLayout.new panel, BoxLayout::X_AXIS panel.setBorder BorderFactory.createEmptyBorder 40, 40, 40, 40 self.setLayout BorderLayout.new panel.add Box.createHorizontalGlue label = JLabel.new mute, JLabel::CENTER slider = JSlider.new 0, 150, 0 ce = ChangeEvent.new ce.setLabel label ce.setIcons mute, min, med, max slider.add_change_listener ce slider.setPreferredSize Dimension.new 150, 30 panel.add slider panel.add label panel.add Box.createRigidArea Dimension.new 5, 0 panel.add Box.createHorizontalGlue self.add panel, BorderLayout::CENTER self.pack self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE self.setSize 300, 200 self.setLocationRelativeTo nil self.setVisible true end end Example.new
In the code example, we show a JSlider
and a JLabel
. By dragging the slider, we change the icon on the label component. We have four images that represent various states of the sound.
mute = ImageIcon.new "mute.png"
Here we create an image icon.
panel.setLayout BoxLayout.new panel, BoxLayout::X_AXIS
Panel component has a horizontal BoxLayout
.
panel.setBorder BorderFactory.createEmptyBorder 40, 40, 40, 40
We creare a 40px border around the panel.
panel.add Box.createHorizontalGlue
We put resizable space to both sides, left and right. It is to prevent JSlider
from growing to unnatural sizes.
label = JLabel.new mute, JLabel::CENTER
This line creates a JLabel
instance with the specified image and horizontal alignment. The label is centered vertically in its display area by default.
slider = JSlider.new 0, 150, 0
This is a JSlider
constructor. The parameters are minimum value, maximum value and current value.
ce = ChangeEvent.new ce.setLabel label ce.setIcons mute, min, med, max
A ChangeEvent
object is created. We set a label and icons to this object.
slider.add_change_listener ce
Each time we move the slider, the stateChanged
method of the ChangeEvent
object will be called.
panel.add Box.createRigidArea Dimension.new 5, 0
We place a 5px rigid space between the two components. They are too close to each other, when the slider is at the end position.
class ChangeEvent include ChangeListener
This is a ChangeEvent
class, which implements the ChangeListener
. As a consequence, this class must implement a changeEvent
method.
sender = e.getSource value = sender.getValue
Inside the changeEvent
method, we get the event source. It is the slider, which has generated the event. From the sender, we get the current value.
if value == 0 @label.setIcon(@mute)
If the value is equal to zero, we update the label to have a mute.png
image.

JToggleButton
JToggleButton
is a button that has two states. Pressed and not pressed. You toggle between these two states by clicking on it. There are situations where this functionality fits well.
#!/usr/local/bin/jruby # ZetCode JRuby Swing tutorial # # This program uses toggle buttons to # change the background color of # a panel. # # author: Jan Bodnar # website: www.zetcode.com # last modified: December 2010 include Java import java.awt.Color import java.awt.Dimension import java.awt.event.ActionListener import javax.swing.JToggleButton import javax.swing.Box import javax.swing.BoxLayout import javax.swing.BorderFactory import javax.swing.JFrame import javax.swing.JPanel import javax.swing.border.LineBorder class Example < JFrame include ActionListener def initialize super "JToggleButton" self.initUI end def initUI self.setPreferredSize Dimension.new 280, 200 bottom = JPanel.new bottom.setLayout BoxLayout.new bottom, BoxLayout::X_AXIS bottom.setBorder BorderFactory.createEmptyBorder 20, 20, 20, 20 leftPanel = JPanel.new leftPanel.setLayout BoxLayout.new leftPanel, BoxLayout::Y_AXIS @display = JPanel.new @display.setPreferredSize Dimension.new 110, 110 @display.setBorder LineBorder.createGrayLineBorder @display.setBackground Color.black bottom.add @display redButton = JToggleButton.new "red" redButton.addActionListener self greenButton = JToggleButton.new "green" greenButton.addActionListener self blueButton = JToggleButton.new "blue" blueButton.addActionListener self blueButton.setMaximumSize greenButton.getMaximumSize redButton.setMaximumSize greenButton.getMaximumSize leftPanel.add redButton leftPanel.add Box.createRigidArea Dimension.new 25, 7 leftPanel.add greenButton leftPanel.add Box.createRigidArea Dimension.new 25, 7 leftPanel.add blueButton bottom.add leftPanel bottom.add Box.createRigidArea Dimension.new 20, 0 self.add bottom self.pack self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE self.setSize 300, 200 self.setLocationRelativeTo nil self.setVisible true end def actionPerformed e color = @display.getBackground red = color.getRed green = color.getGreen blue = color.getBlue if e.getActionCommand == "red" if red == 0 red = 255 else red = 0 end end if e.getActionCommand == "green" if green == 0 green = 255 else green = 0 end end if e.getActionCommand == "blue" if blue == 0 blue = 255 else blue = 0 end end setCol = Color.new red, green, blue @display.setBackground setCol end end Example.new
In the code example, we use three toggle buttons to change the color of a rectangular component.
class Example < JFrame include ActionListener
The class implements the ActionListener
. We will do some action in the actionPerformed
method of the Example class.
redButton = JToggleButton.new "red" redButton.addActionListener self
We create a JToggleButton
component. We add an action listener to the button. The action listener is the Example class. When we click on the redButton, the actionPerformed
method of the Example class will be called.
blueButton.setMaximumSize greenButton.getMaximumSize redButton.setMaximumSize greenButton.getMaximumSize
We make all three buttons of equal size.
color = @display.getBackground red = color.getRed green = color.getGreen blue = color.getBlue
We determine the current red, green, blue parts of the display background color.
if e.getActionCommand == "red" if red == 0 red = 255 else red = 0 end end
We determine, which button was toggled, and update the color part of the RGB value accordingly.
setCol = Color.new red, green, blue @display.setBackground setCol
Here a new color is created and the display panel is updated to a new color.

JList
JList
is a component that displays a list of objects. It allows the user to select one or more items.
#!/usr/local/bin/jruby # ZetCode JRuby Swing tutorial # # In this program, we show all # available fonts of a system in # a JList component. # # author: Jan Bodnar # website: www.zetcode.com # last modified: December 2010 include Java import java.awt.BorderLayout import java.awt.Dimension import java.awt.Font import java.awt.GraphicsEnvironment import javax.swing.JFrame import javax.swing.BorderFactory import javax.swing.JScrollPane import javax.swing.JPanel import javax.swing.JLabel import javax.swing.JList class Example < JFrame def initialize super "JList" initUI end def initUI panel = JPanel.new panel.setLayout BorderLayout.new panel.setBorder BorderFactory.createEmptyBorder 20, 20, 20, 20 ge = GraphicsEnvironment.getLocalGraphicsEnvironment fonts = ge.getAvailableFontFamilyNames list = JList.new fonts list.add_list_selection_listener do |e| sender = e.source if not e.getValueIsAdjusting name = sender.getSelectedValue font = Font.new name, Font::PLAIN, 13 @label.setFont font end end pane = JScrollPane.new pane.getViewport.add list pane.setPreferredSize Dimension.new 250, 200 panel.add pane @label = JLabel.new "Aguirre, der Zorn Gottes" @label.setFont Font.new "Serif", Font::PLAIN, 12 self.add @label, BorderLayout::SOUTH self.add panel self.pack self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE self.setLocationRelativeTo nil self.setVisible true end end Example.new
In our example, we will display a JList
and a JLabel
components. The list component contains a list of all available font family names on our system. If we select an item from the list, the label will be displayed in a font, we have chosen.
ge = GraphicsEnvironment.getLocalGraphicsEnvironment fonts = ge.getAvailableFontFamilyNames
Here we obtain all possible font family names on our system.
list = JList.new fonts
We create an instance of the JList
component. It will display all font family names.
if not e.getValueIsAdjusting
Events in list selection are grouped. We receive events for both selecting and unselecting. To filter only the selecting events, we use the getValueIsAdjusting
method.
name = sender.getSelectedValue font = Font.new name, Font::PLAIN, 13 @label.setFont font
We get the selected item and set a new font for the label.
pane = JScrollPane.new pane.getViewport.add list
JList
component is not scrollable by default. We put the list into the JScrollPane
to make it scrollable.

In this part of the JRuby Swing tutorial, we have presented several Swing components.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论