Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Swing (Java)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Another example=== In this example let javax.swing.JFrame be super class and add our own widget(s) to it (in this case, a JButton). <syntaxhighlight lang="java"> import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Sample extends JFrame { private final JButton b = new JButton(); public Sample() { super(); this.setTitle("HelloApp"); this.getContentPane().setLayout(null); this.setBounds(100, 100, 180, 140); this.add(makeButton()); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } private JButton makeButton() { b.setText("Click me!"); b.setBounds(40, 40, 100, 30); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(b, "Hello World!"); } }); return b; } public static void main(String[] args) throws InvocationTargetException, InterruptedException { // Swing calls must be run by the event dispatching thread. SwingUtilities.invokeAndWait(() -> new Sample()); } } </syntaxhighlight> The layout is set to null using the {{Javadoc:SE|member=setLayout(LayoutManager)|java/awt|Container|setLayout(java.awt.LayoutManager)|module=java.desktop}} method since JFrame uses java.awt.BorderLayout as its default layout-manager. With BorderLayout anything which is added to the container is placed in the center and stretched to accommodate any other widgets. Of course, most real world GUI applications would prefer to use a layout-manager instead of placing everything on absolute co-ordinates.<ref>{{cite book|last1=Eckel|first1=Bruce|title=Thinking in Java|date=2006|publisher=Prentice Hall|isbn=978-0131872486|page=942|edition=4|url=http://www.agentgroup.unimore.it/~nicola/courses/IngegneriaDelSoftware/java/books/ThinkingInJava.pdf|access-date=13 May 2016|url-status=dead|archive-url=https://web.archive.org/web/20160514000820/http://www.agentgroup.unimore.it/~nicola/courses/IngegneriaDelSoftware/java/books/ThinkingInJava.pdf|archive-date=14 May 2016}}</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)