Using the tkinter.messagebox library

Previous entries in this series:

  1. Welcome to tkinter
  2. Questions and answers for a basic tkinter GUI
  3. Feet to Meters using tkinter and ttk

While I am mostly looking at the ttk module at present, there is a module in the tkinter library that is so useful that I want to take a break and cover it. The module is called messagebox. It is located in the tkinter library.
Continue reading Using the tkinter.messagebox library

Feet to Meters using tkinter and ttk

Previous entries in this series:

  1. Welcome to tkinter
  2. Questions and answers for a basic tkinter GUI

Previously we have made an application that doesn’t really do anything. Its purpose was to show the necessary code to create the application in a GUI on the screen. Now it’s time to create an application that actually does something.

The application that we are going to make is based on the wonderful tutorial provided by TkDocs. specifically, we are going to be recreating a first (real) example, but instead of using non-object-oriented code, we will be using python classes.
Continue reading Feet to Meters using tkinter and ttk

Welcome to tkinter

I have fallen in love with the python programming language. It has everything that I commonly use when I am programming in C/C++, but it also has the advantage of being cross-platform. As a C/C++ programmer, learning the language was relatively easy, and the joy of my programs being able to run on virtually any system without heroic efforts was truly exhilarating. The only thing that seemed to be missing was the ability to have a GUI that was available across all platforms while still avoiding those aforementioned heroic efforts.

Python already had a self-contained answer to my desire for a cross-platform GUI. When I installed python, it brought along its own GUI for the ride. While it is true that the GUI might not be as all-inclusive and robust as, say, the Windows GUI or GTK+, it seems to be just perfect for the same reasons that the python language, itself, is so wonderful.
Continue reading Welcome to tkinter

Text Manipulation in Java – JTextComponents

OK, obviously I need some extra work on text manipulation in Java. Manipulating text in Java is a double edged sword. On one hand, it is really easy to get started. Java keeps track of the text models and deals with them automatically so you don’t really even have to have a working concept of them. On the other hand, if you want to do anything more serious than what has already been created by someone else, you have to be able to manipulate the model yourself. And, of course, in order to manipulate the model in some other way than throwing things against the wall and seeing what sticks, you actually have to understand what the model is doing.

In order to be a decent programmer, it is important to understand what the code causes the computer to do. That sounds obvious, but often we don’t really understand. Often, we don’t have any better understanding than Pavlov’s dog. [1] We simply learn that when we do something, something else happens in response. What we don’t know is what the change is doing down in the code to cause those changes to appear.

Most Java Swing components use models: [2]

Most Swing components have models. A button (JButton), for example, has a model (a ButtonModel object) that stores the button’s state — what its keyboard mnemonic is, whether it’s enabled, selected, or pressed, and so on. Some components have multiple models. A list (JList), for example, uses a ListModel to hold the list’s contents, and a ListSelectionModel to track the list’s current selection.

We don’t need to know all the details of these models. In most cases, we don’t even need to know that the Swing component uses models at all. We learn some API function to call, and Swing takes care of the rest. But that doesn’t work when we really need to customize something like a JTextPane. We not only need to know that it has a model, but how to manipulate it to store the information we want, as well as needing to know how it will effect the view.

From “How to Use Models”: [2]

Although Swing’s model architecture is sometimes referred to as a Model-View-Controller (MVC) design, it really isn’t. Swing components are generally implemented so that the view and controller are indivisible, implemented by a single UI object provided by the look and feel. The Swing model architecture is more accurately described as a separable model architecture. If you’re interested in learning more about the Swing model architecture, see A Swing Architecture Overview, an article in The Swing Connection.

Now that we have a general idea of what models do, we want to look closer at text models. Here is a list of what text models do: [3]

The JTextComponent class is the foundation for Swing text components. This class provides the following customizable features for all of its descendants:

  • A model, known as a document, that manages the component’s content.
  • A view, which displays the component on screen.
  • A controller, known as an editor kit, that reads and writes text and implements editing capabilities with actions.
  • Support for infinite undo and redo.
  • A pluggable caret and support for caret change listeners and navigation filters.

From the above description, you can see where Swing components get the Model-View-Controller (MVC) reference even if it might not be accurate with all Swing components.

A text component’s model is known as a document and is an instance of a class that implements the Document interface. … [3]

That quote is very important. The Document we are working with is the model for the text component. Whether we realize it or not, it is going to store all the information necessary to format the document the way we want. And if we truly want to manipulate the text, we must know how to manipulate the document (model).

There is only one thing left to point out. While it is true that JTextPane is a descendant of JTextComponent, JTextPane uses a special model called StyledDocument as its model. It needs this expanded model to hold the various text attributes that aren’t present in a regular text document (model).

… A document provides the following services for a text component:

  • Contains the text. A document stores the textual content in Element
    objects, which can represent any logical text structure, such as
    paragraphs, or text runs that share styles. We do not describe Element objects here.
  • Provides support for editing the text through the remove and insertString methods.
  • Notifies document listeners and undoable edit listeners of changes to the text.
  • Manages Position objects, which track a particular location within the text even as the text is modified.
  • Allows you to obtain information about the text, such as its length, and segments of the text as a string.

The Swing text package contains a subinterface of Document,
StyledDocument, that adds support for marking up the text with styles. One JTextComponent subclass, JTextPane, requires that its document be a StyledDocument rather than merely a Document.[3]

[1] Classical Conditioning – Wikipedia
[2] How to Use Models – Oracle Java Tutorial
[3] Text Component Features – Oracle Java Tutorials

Java Graphics Programming Study 1: Simple Swing Graphics

I have been playing with Java Swing graphics programming. As it turns out, it is fairly easy and yet extremely powerful. Points, lines, colors, curves, and shapes are all created easily from existing classes. All I have to do is learn how to use them.

I would love to take full credit for this code, but most of it was created by someone else. I have been using the “Custom Graphics Programming – Java Programming Tutorial” for the raw material for this study: specifically, example 3 was my starting point.

I reworked the code to make it more to update it, make it more to my liking, and understand it better. I also extensively commented it for a more clear understanding.

If you would like to download the code I wrote, it is available for download here. You can either pull the java files out of the zip file or import the project into the NetBeans IDE.

The code consists of two different java files. No other resources other than those included with the Java Development Kit (JDK) are needed.

File # 1

package GUI;

// imports are individually listed for clarity
import java.awt.BorderLayout;       // for JFrame use
import java.awt.Color;              // for use in drawing
import java.awt.Dimension;          // for specifying JPanel size
import java.awt.Graphics;           // variable type passed to methods
import java.awt.event.MouseAdapter;         // for mouse tracking
import java.awt.event.MouseEvent;           // for mouse tracking
import java.awt.event.MouseMotionAdapter;   // for mouse tracking
import java.util.ArrayList;         // multiuse storage class
import javax.swing.JFrame;          // for creating JFrames
import javax.swing.JPanel;          // for creating JPanels
import javax.swing.SwingUtilities;  // to access the Event Dispatch Thread

public class GraphicsStudy extends JFrame {
    // class variables
    ArrayList<MultipointLine> linesArray;   // stores completed lines
    JPanel graphicsPanel;                   // used for the drawing surface
    MultipointLine currentLine;             // an individual line in progress
    // constructor sets up the entire JFrame window
    public GraphicsStudy() {
        // initialize the new array that will store all the finished lines
        linesArray = new ArrayList();
        // GraphicsPanel is an inside class
        // it is a JPanel that will be used for drawing
        graphicsPanel = new GraphicsPanel(600, 400);
        // add a mouse click listener
        // every time the mouse is clicked, start a new line
        graphicsPanel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent event) {
                currentLine = new MultipointLine(event.getX(), event.getY());
        // add a mouse motion listener
        // when the mouse is dragged (button down while moving),
        // add points to the line that was created when the button
        // was initially pressed
        // then call for a repaint of the graphics area
        graphicsPanel.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent event) {
                currentLine.addPoint(event.getX(), event.getY());
        // create the window, give it a title,
        // add the JPanel to the JFrame to use for drawing,
        // pack the JFrame,
        // use platform specific placement of the window,
        // and finally, make the window visible
        this.setTitle("Graphics Study");
        this.getContentPane().add(graphicsPanel, BorderLayout.CENTER);
        this.pack();                            // pack or set size
    public static void main(String[] args) {
        // all the main class has to do is call the
        // constructor for the JPanel and put it on
        // the event dispatch thread
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new GraphicsStudy();
    // this is an inner class. It creates the Jpanel that
    // will be used as a drawing surface.
    class GraphicsPanel extends JPanel {
        // this constructor isn't really needed, but I am using
        // it to set the dimensions for the JPanel
        public GraphicsPanel(int rows, int cols) {
            this.setPreferredSize(new Dimension(rows, cols));
        // Override the paintComponent method and put the
        // graphics creating code inside it.
        // Since it is an inner class, it can access the stored
        // lines from its parent class (GraphicsStudy).
        protected void paintComponent(Graphics graphics) {
            // call the super method to paint the background
            // set the drawing line color
            // what can I say, Magenta is my color
            // draw the saved lines
            // lines were stored in the GraphicsStudy class
            // but can be accessed by this inner class
            for(MultipointLine line : linesArray) {

File # 2:

package GUI;

// import
import java.awt.Graphics;       // for drawLine function
import java.util.ArrayList;     // to store the points in the line

public class MultipointLine {
    private ArrayList<Integer> xArray;
    private ArrayList<Integer> yArray;
    // constructor creates a new line and sets the first point.
    // The constructor is called when the mouse button is pressed.
    public MultipointLine(int x, int y) {
        xArray = new ArrayList();
        yArray = new ArrayList();
        addPoint(x, y);
    // add a point to the end of the x and y arrays.
    // these points will be used to draw a bunch of tiny lines
    final public void addPoint(int x, int y) {
    // draw out the crazy line from the storage arrays
    public void drawMultipointLine(Graphics graphics) {
        for(int x = 0; x < xArray.size() - 1; ++x) {
            graphics.drawLine(xArray.get(x), yArray.get(x),
                    xArray.get(x+1), yArray.get(x+1));