By Alvin Alexander. Last updated: August 7, 2022
As a brief note to self, I used the following Scala source code to build a semi-transparent dialog (a Java JFrame
, actually) for the second version of Sarah:
import java.awt._ import javax.swing._ /** * How to use: * * val b = new TextWindowBuilder("Hello, world") * b.setVisible(true) * * // later * b.setVisible(false) * */ class TextWindowBuilder ( textToDisplay: String, windowSize: Dimension = new Dimension(400, 300), location: Point = new Point(200, 200), textAreaRows: Int = 10, textAreaColumns: Int = 40, alpha: Float = 0.8f ) { // textarea and scrollpane val textArea = new JTextArea(textAreaRows, textAreaColumns) textArea.setFont(new Font("Helvetica Neue", Font.PLAIN, 20)) textArea.setEditable(false) textArea.setMargin(new Insets(12, 12, 12, 12)) val scrollPane = new JScrollPane(textArea) textArea.setText(textToDisplay) scrollPane.setPreferredSize(windowSize) scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS) scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) // jframe val f = new JFrame() f.setUndecorated(true) f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) f.getRootPane.putClientProperty("Window.alpha", alpha) f.getContentPane.add(scrollPane, BorderLayout.CENTER) f.setLocation(location) def setText(text: String) { val code = textArea.setText(text) invokeLater(code) } def setVisible(makeVisible: Boolean) { if (makeVisible) { val block = { f.pack f.setVisible(true) } invokeLater(block) } else { val block = f.setVisible(false) invokeLater(block) } } private def invokeLater[A](blockOfCode: => A) = { SwingUtilities.invokeLater(new Runnable { def run { blockOfCode } }) } }
As one example of how to create a semi-transparent popup window with this code, I instantiated a new window in Sarah like this:
// this is the secondary window i use in Sarah2 to display output val textWindow = new TextWindowBuilder( "", new Dimension(mainFrame.getWidth, 400), new Point(372, 395) )
This code shows several things, including:
- How to create and show a JFrame
- How to put a JTextArea in a JScrollPane
- How to provide default parameter values in a Scala constructor (or method)
- How to set various attributes on a JScrollPane
- How to use SwingUtilities.invokeLater
I hope there’s something in there that might be of use.