Skip to content

Instantly share code, notes, and snippets.

@kishida
Created February 27, 2022 07:59
Show Gist options
  • Save kishida/b5638ad01aa303a14aaad592f58f1f68 to your computer and use it in GitHub Desktop.
Save kishida/b5638ad01aa303a14aaad592f58f1f68 to your computer and use it in GitHub Desktop.
Fluent Style Swing
package kis;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class FluentSwing {
public static void main(String[] args) {
new Frame("hello")
.add("North", new Panel()
.add(new JTextField(10))
.add(new Button("hello")))
.add(new JTextArea())
.setSize(600, 400)
.setVisible(true);
}
interface ComponentHolder<T extends JComponent> {
T component();
}
static class Frame {
JFrame f;
public Frame(String title) {
this.f = new JFrame(title);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Frame setSize(int w, int h) {
f.setSize(w, h);
return this;
}
Frame setVisible(boolean v) {
f.setVisible(v);
return this;
}
Frame add(String place, ComponentHolder<?> comp) {
f.add(place, comp.component());
return this;
}
Frame add(JComponent comp) {
f.add(comp);
return this;
}
}
static class Button implements ComponentHolder<JButton> {
JButton b;
public Button(String text) {
this.b = new JButton(text);
}
@Override
public JButton component() {
return b;
}
Button addActionListener(ActionListener al) {
b.addActionListener(al);
return this;
}
}
static class Panel implements ComponentHolder<JPanel> {
JPanel p;
public Panel() {
this.p = new JPanel();
}
Panel add(JComponent compo) {
p.add(compo);
return this;
}
Panel add(ComponentHolder<?> como) {
p.add(como.component());
return this;
}
@Override
public JPanel component() {
return p;
}
}
}
@kishida
Copy link
Author

kishida commented Feb 27, 2022

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment