What you are wasting today is tomorrow for those who died yesterday; what you hate now is the future you can not go back.
你所浪费的今天是昨天死去的人奢望的明天; 你所厌恶的现在是未来的你回不去的曾经。
本人入门Golang的gui, 只是想做一些小的工具日常工作使用, 因为对Golang的热爱已经到了如痴如醉的地步。
开始今天的lxn/walk练习:
package main
import (
"encoding/json"
"github.com/lxn/walk"
. "github.com/lxn/walk/declarative"
)
func main() {
var inTE, outTE *walk.TextEdit
MainWindow{
Title: "格式化工具",
MinSize: Size{600, 400},
Layout: VBox{},
Children: []Widget{
HSplitter{
Children: []Widget{
TextEdit{AssignTo: &inTE},
TextEdit{AssignTo: &outTE, ReadOnly: true},
},
},
PushButton{
Text: "格式化",
MinSize:Size{150, 36},
OnClicked: func() {
var jsonStr interface{}
err := json.Unmarshal([]byte(inTE.Text()), &jsonStr)
jsonStr, _ = json.MarshalIndent(jsonStr, "\r\n", "\t")
if err != nil {
// 暂时未找到设置颜色值
//outTE.SetTextColor(walk.Color(32))
outTE.SetText("数据格式不正确")
} else {
outTE.SetText(string(jsonStr.([]uint8)))
}
},
},
},
}.Run()
}
本案例尽在Windows 10 上测试。
运行首先使用rsrc工具编译加载manifest文件,然后build生成可执行文件
======================小优化======================
- 添加格式化的字符
- 控件的优化
package main
import (
"encoding/json"
"github.com/lxn/walk"
. "github.com/lxn/walk/declarative"
)
func main() {
var inTE, outTE *walk.TextEdit
var RadioTypeTab,RadioTypeSpace *walk.RadioButton
MainWindow{
Title: "格式化工具",
MinSize: Size{600, 400},
Layout: VBox{},
Children: []Widget{
HSplitter{
MinSize: Size{600, 300},
Children: []Widget{
TextEdit{AssignTo: &inTE, HScroll:true, VScroll:true},
TextEdit{AssignTo: &outTE, ReadOnly: true, HScroll:true, VScroll:true},
},
},
Composite{
MinSize: Size{600, 50},
Layout: Grid{Columns: 6, Spacing: 10},
Children: []Widget{
HSplitter{
Children: []Widget{
RadioButtonGroup{
Buttons: []RadioButton{
RadioButton{Name: "SplitType", Text: "Tab", Value: "Tab", RowSpan: 3, ToolTipText: "这是默认选项",AssignTo:&RadioTypeTab},
RadioButton{Name: "SplitType", Text: "空格", Value: "space", ToolTipText: "4个空格",AssignTo:&RadioTypeSpace}}},
},
},
},
},
PushButton{
Text: "格式化",
MinSize: Size{150, 36},
OnClicked: func() {
typeStr := " "
checked := RadioTypeTab.Checked()
if checked {
typeStr = "\t"
}
var TextColor walk.Color
if inTE.Text() == "" {
TextColor = walk.RGB(byte(255), byte(48), byte(48))
outTE.SetTextColor(TextColor)
outTE.SetText("数据为空")
return
}
var jsonStr interface{}
err := json.Unmarshal([]byte(inTE.Text()), &jsonStr)
jsonStr, _ = json.MarshalIndent(jsonStr, "\r\n", typeStr)
if err != nil {
TextColor = walk.RGB(byte(255), byte(48), byte(48))
outTE.SetTextColor(TextColor)
outTE.SetText("数据格式不正确")
return
}
TextColor = walk.RGB(byte(34), byte(139), byte(34))
//outTE.SetTextSelection(1, 10)
outTE.SetTextColor(TextColor)
outTE.SetText(string(jsonStr.([]uint8)))
},
},
},
}.Run()
}
运行的最终效果图:
由于是练习GUI的使用方式,并未在代码阅读性和性能方面做功夫,
比如: 应该将处理数据的逻辑代码独立出来, 与gui代码逻辑分离
更多建议贵请留言 ^_^