Created
March 1, 2022 10:20
-
-
Save marius-m/82086a8b8b97c31f7637e0332b94121d to your computer and use it in GitHub Desktop.
GUI App snippet for testing out line count in JTextArea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lt.linecounter | |
import org.slf4j.Logger | |
import org.slf4j.LoggerFactory | |
import java.awt.* | |
import java.awt.event.ComponentAdapter | |
import java.awt.event.ComponentEvent | |
import javax.swing.JFrame | |
import javax.swing.JPanel | |
import javax.swing.JTextArea | |
import javax.swing.SwingUtilities | |
class MainJTextArea( | |
private val l: Logger | |
): JPanel(GridBagLayout()) { | |
init { | |
val inputStr = "Lorem ipsum dolor sit amet, consectetur adipisicing\n elit, sed do eiusmo," + | |
" Lorem ipsum \ndolor sit amet, consectetur adipisicing elit, sed do eiusmo," + | |
" Lorem ipsum dolor sit amet, \nconsectetur adipisicing elit, sed do eiusmo," + | |
" Lorem ipsum dolor sit amet, \nconsectetur adipisicing elit, sed do eiusmo" | |
val textArea = drawTextArea( | |
text = inputStr, | |
fontSize = 12.0 | |
) | |
val textAreaLineCounter = TextAreaLineCounter(textArea) | |
// Add Components to this panel. | |
val c = GridBagConstraints().apply { | |
gridwidth = GridBagConstraints.REMAINDER | |
fill = GridBagConstraints.BOTH | |
weightx = 1.0 | |
weighty = 1.0 | |
} | |
add(textArea, c) | |
addComponentListener(object : ComponentAdapter() { | |
override fun componentResized(e: ComponentEvent?) { | |
super.componentResized(e) | |
l.debug("Line count: ${textAreaLineCounter.countLines()}") | |
} | |
}) | |
} | |
private fun drawTextArea( | |
text: String, | |
fontSize: Double = 12.0 | |
): JTextArea { | |
val textArea = JTextArea(text) | |
textArea.size = Dimension(width, height) | |
textArea.foreground = Color.BLACK | |
textArea.background = Color(0, 0, 0, 0) | |
textArea.font = Font(null, Font.LAYOUT_LEFT_TO_RIGHT, fontSize.toInt()) | |
textArea.lineWrap = true | |
textArea.wrapStyleWord = true | |
return textArea | |
} | |
companion object { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val logger = LoggerFactory.getLogger(MainJTextArea::class.java)!! | |
SwingUtilities.invokeLater { | |
val frame = JFrame("JTextAreaLineCountDemo").apply { | |
preferredSize = Dimension(400, 360) | |
defaultCloseOperation = JFrame.EXIT_ON_CLOSE | |
add(MainJTextArea(logger)) | |
pack() | |
} | |
frame.isVisible = true | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment