- JButton basic tutorial and examples
- 1. Creating a JButton object
- 2. Adding the button to a container
- 3. Adding event listener for JButton
- 4. Setting mnemonic and hotkey for JButton
- 5. Setting a JButton as the default button
- 6. Customizing JButton’s appearance
- 7. JButton demo program
- Other Java Swing Tutorials:
- About the Author:
- Add comment
- Comments
- Modifying the Appearance of Buttons in Java Swing
- Java JButton styling
- Lect 2.7 — Cool Button Styles in JAVA || Make a Round
- How to style in java swing?
- Java Swing buttons to make them equal
JButton basic tutorial and examples
In this Java Swing tutorial, you will learn how to use button that allows the user to perform action in a desktop application.
You know, JButton is a fundamental Swing component that renders a button on screen and responds to user’s clicking event for performing a specific task. This article summarizes common programming practices for using JButton in Swing.
Table of content:
1. Creating a JButton object
JButton button = new JButton("Edit");
Image:
Create a button with only an icon in the file system:
JButton button = new JButton(new ImageIcon("images/start.gif"));
Here the icon file start.gif is placed under images directory which is relative to the program.
Image:
Create a button with only icon inside a jar file or in classpath:
String iconPath = "/net/codejava/swing/jbutton/stop.jpg"; Icon icon = new ImageIcon(getClass().getResource(iconPath)); JButton button = new JButton(icon);
Here the icon file stop.jpg is placed under a specific package in the classpath.
Image:
Create a button with a caption and an icon:
JButton button = new JButton("Start", new ImageIcon("images/start.gif"));
Image:
2. Adding the button to a container
frame.add(button); dialog.add(button); panel.add(button); applet.getContentPane().add(button);
frame.add(button, BorderLayout.CENTER); panel.add(button, gridbagConstraints);
3. Adding event listener for JButton
button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent evt) < // do everything here. >>);
button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent evt) < // delegate to event handler method buttonActionPerformed(evt); >>);
private void buttonActionPerformed(ActionEvent evt) < // do something here. >
public class App extends JFrame implements ActionListener < public App() < // creates the button. // adds event listener: button.addActionListener(this); >@Override public void actionPerformed(ActionEvent evt) < // do something here. >>
Here the container ( JFrame ) must implement the ActionListener interface and override the method actionPerformed() .
4. Setting mnemonic and hotkey for JButton
button.setMnemonic(KeyEvent.VK_E);
The letter E is underlined: so user can invoke that button’s action by pressing Alt + Einstead of clicking mouse.
String mapKey = "KEY_F2"; InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke("F2"), mapKey); button.getActionMap().put(mapKey, new AbstractAction() < public void actionPerformed(ActionEvent evt) < buttonActionPerformed(evt); >>);
5. Setting a JButton as the default button
A window can have a default button whose action will be invoked when the user hits Enter key. Here is the code to set the button as default button in the frame window:
getRootPane().setDefaultButton(button);
The default button is bold in the window like the 3 rd button in this screenshot:
6. Customizing JButton’s appearance
button.setFont(new java.awt.Font("Arial", Font.BOLD, 14)); button.setBackground(Color.YELLOW); button.setForeground(Color.BLUE);
Image:
7. JButton demo program
For reference, we created a demo program which incorporates all the practices mentioned above. The program looks like this:
You can download source code of this program in the attachment section.
Other Java Swing Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Add comment
Comments
merci
I want to add to the button text using a variable. how do I get this to work? jpFormatPanel.add(new JButton(«Format Citation: «
+ strTemplateName
I want to add to the button text using a variable. how do I get this to work? jpFormatPanel.add(new JButton(«Format Citation: »
+ strTemplateName
+ » — »
+ strTemplateCode),
BorderLayout.NORTH);
CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.
Copyright © 2012 — 2023 CodeJava.net, all rights reserved.
Modifying the Appearance of Buttons in Java Swing
The ‘=’ button at the center is larger than the » buttons on the East and West sides respectively. The sizes of my », and ‘=’ buttons are not equal.
Java JButton styling
Looking for suggestions to style a JButton to resemble NetBeans toolbar buttons. Specifically, I want it to display only an image initially and display a 1px rounded corner gray border on hover, with a different background on the top and bottom. Despite my efforts, I’m unable to style the JButton in this manner. Any help is appreciated. The accompanying image shows the desired appearance of the button when normal, on hover, and on focus. Even if the half-half background is not achievable, I’m struggling to get the borders to appear on hover.
JButton.setRolloverEnabled(true);
To set a unique icon for the «rollover,» utilize the setRolloverIcon() and setRolloverSelectedIcon() techniques.
Do you approve of my approach? I incorporated a netbeans.png green triangle that I discovered on Google and cited another question as a reference. Nonetheless, there’s a tiny «TODO» section for you to complete — painting the button border with a distinct background when it gets the focus. I trust that you’ll find this response favorable.
import java.awt.Color; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Area; import java.awt.geom.RoundRectangle2D; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; public class StylistButton extends JButton implements MouseListener < boolean mouseIn = false; public StylistButton(String s) < addMouseListener(this); setBorderPainted(false); setContentAreaFilled(false); >protected static ImageIcon createImageIcon(String path) < URL imgURL = TextSamplerDemo.class.getResource(path); if (imgURL != null) < return new ImageIcon(imgURL); >else < System.err.println("Couldn't find file: " + path); return null; >> protected void paintComponent(Graphics g) < // set button big enough so we can see the rounding curve. setSize(60, 40); ImageIcon netbeans = createImageIcon("netbeans.png"); if (netbeans != null) < setIcon(netbeans); >setIcon(netbeans); Color[] gradients; Graphics2D g2 = (Graphics2D) g; super.paintComponent(g2); if(getModel().isRollover()) < g2.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); Shape firstClip = g.getClip(); RoundRectangle2D rect = new RoundRectangle2D.Double(); double arc = Math.ceil(getSize().getHeight() / ****.setRoundRect(0, 0, Math.ceil(getSize().getWidth()), Math.ceil(getSize().getHeight()), arc, arc); Area secondClip = new Area(getBounds()); secondClip.subtract(new Area(rect)); Area finalClip = new Area(firstClip); finalClip.subtract(secondClip); g2.setClip(finalClip); super.paintComponent(g2); gradients = new Color[] < new Color(184, 207, 229), new Color(122, 138, 153), new Color(184, 207, 229) >; for(int i = 0; i < gradients.length; i++) < arc -= 2; g2.setColor(gradients[i]); g2.drawRoundRect(i+1, i+1, (int)Math.ceil(getSize().getWidth()-2)-(i*2), (int)Math.ceil(getSize().getHeight()-2)-(i*2), (int)arc, (int)arc); >> else if (getModel().isSelected()) < // TODO, leave a permanent focus mark here. >> public static void main(String[] args) < JFrame frame = new JFrame(); frame.getContentPane().setLayout(new FlowLayout()); StylistButton sButton = new StylistButton("stylistButton"); frame.getContentPane().add(sButton); frame.setSize(250, 250); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); >@Override public void mouseClicked(MouseEvent e) < >@Override public void mousePressed(MouseEvent e) < >@Override public void mouseReleased(MouseEvent e) < >@Override public void mouseEntered(MouseEvent e) < >@Override public void mouseExited(MouseEvent e) < >>
How to set background color of a button in Java GUI?, The background color is the color behing the button. Using setBorderPainted (false) would solve the above mentioned issue. btn [i].setBackground (Color.RGBtoHSB (int, int, int, float [])); Changing the background property might not be enough as the component won’t look like a button anymore.
Lect 2.7 — Cool Button Styles in JAVA || Make a Round
In this video we are going to discuss that how to make a rounder button with hover effect. Provide a CSS type look to your GUI’s.For Make a online button : h
How to style in java swing?
As a newcomer to Java, I am encountering styling issues while attempting to develop a program. My objective is to create a basic program with a specific structure.
The topmost line should display the menubar containing buttons for file and about. Following that, a text input labeled «url: » should be accompanied by a «go» button on the second line. Finally, a tabbed menu consisting of three tabs — tab1, tab2, and tab3 — should be displayed on the third line.
The content below the window’s top should consist of a table containing rows and columns. The table must include vertical and horizontal bars in case the content exceeds the window’s size, and it should fill the window’s width if it is smaller than the table.
For now I have only this code:
import javax.swing.*; public class main < public static void main(String args[])< JFrame frame = new JFrame("SEO Tool"); frame.setSize(500,300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH); frame.setVisible(true); menubar menubar = new menubar(); menubar.createmenubar_site(frame); tabs tabs = new tabs(); tabs.createtabs(frame); >>
import javax.swing.*; import javax.swing.BoxLayout; public class tabs < public void createtabs(JFrame frame)< JLabel sitelabel = new JLabel("A"); JPanel sitepanel = new JPanel(); sitepanel.setLayout(new BoxLayout(sitepanel, BoxLayout.X_AXIS)); sitepanel.setSize(400,400); sitepanel.add(sitelabel); frame.add(sitepanel); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); //panel.setBounds(); frame.add(panel); JTabbedPane tabs = new JTabbedPane(); JPanel yoursite = new JPanel(); JPanel yourcompetitors = new JPanel(); tabs.addTab("Your site",yoursite); tabs.addTab("Your competitors",yourcompetitors); panel.add(tabs); sitetab sitetab = new sitetab(); sitetab.createcontent(yoursite); >>
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class menubar < public void createmenubar_site(JFrame frame)< JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu file = new JMenu("File"); menubar.add(file); JMenuItem newproject = new JMenuItem("New Project"); newproject .addActionListener(new click_newproject()); file.add(newproject); >static class click_newproject implements ActionListener < public void actionPerformed (ActionEvent e)< >> >
The layout example I made using NetBeans WYSIWYG, which you described and I understood, can provide you with a basic understanding of how it can be done. Although it doesn’t use your code, it’s still a good tool. However, it’s recommended that you read more about layouts on this website: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html.
private void initComponents() < urlPanel = new javax.swing.JPanel(); urlLabel = new javax.swing.JLabel(); urlField = new javax.swing.JTextField(); urlButton = new javax.swing.JButton(); tabbedPane = new javax.swing.JTabbedPane(); tab1 = new javax.swing.JPanel(); tab2 = new javax.swing.JPanel(); tab3 = new javax.swing.JPanel(); tableScrollPane = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); mainMenu = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); aboutMenu = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS)); urlPanel.setLayout(new java.awt.BorderLayout()); urlLabel.setText("url:"); urlPanel.add(urlLabel, java.awt.BorderLayout.WEST); urlField.setText("http://google.com"); urlPanel.add(urlField, java.awt.BorderLayout.CENTER); urlButton.setText("Go"); urlPanel.add(urlButton, java.awt.BorderLayout.EAST); getContentPane().add(urlPanel); javax.swing.GroupLayout tab1Layout = new javax.swing.GroupLayout(tab1); tab1.setLayout(tab1Layout); tab1Layout.setHorizontalGroup( tab1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 395, Short.MAX_VALUE) ); tab1Layout.setVerticalGroup( tab1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 32, Short.MAX_VALUE) ); tabbedPane.addTab("tab1", tab1); javax.swing.GroupLayout tab2Layout = new javax.swing.GroupLayout(tab2); tab2.setLayout(tab2Layout); tab2Layout.setHorizontalGroup( tab2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 395, Short.MAX_VALUE) ); tab2Layout.setVerticalGroup( tab2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 32, Short.MAX_VALUE) ); tabbedPane.addTab("tab2", tab2); javax.swing.GroupLayout tab3Layout = new javax.swing.GroupLayout(tab3); tab3.setLayout(tab3Layout); tab3Layout.setHorizontalGroup( tab3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 395, Short.MAX_VALUE) ); tab3Layout.setVerticalGroup( tab3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 32, Short.MAX_VALUE) ); tabbedPane.addTab("tab3", tab3); getContentPane().add(tabbedPane); tableScrollPane.setViewportView(table); getContentPane().add(tableScrollPane); fileMenu.setText("File"); mainMenu.add(fileMenu); aboutMenu.setText("About"); mainMenu.add(aboutMenu); setJMenuBar(mainMenu); pack(); >
Java Swing: How JToolbar changes appearance of a, To change text color of disabled button you can override UIManager’s default property. And to make button work more likely as in toolBar add mouseListener to it and change its enable status in mouseEnter and Exit method. Example: JFrame frame = new JFrame («tool bar button demo»); …
Java Swing buttons to make them equal
import javax.swing.*; import java.awt.*; public class MathsTutorProgram < public static void main(String[]args) < JFrame a = new JFrame(); //Create a blank window JPanel panel = new JPanel(); //Create a panel //Buttons JLabel welcome = new JLabel("Welome to Maths Tutor!"); JButton lessThan = new JButton ("<"); JButton greaterThan = new JButton (">"); JButton equals = new JButton ("="); JButton askMe = new JButton ("Ask me a question!"); //panels panel.add(welcome); panel.add(lessThan); panel.add(greaterThan); panel.add(equals); panel.add(askMe); a.setContentPane(panel); //Use panel on Window //sets a.setTitle("Maths Tutor Program"); //Change window title a.setSize(300,200); //Change window size a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); a.setVisible(true); //Border layout + Location BorderLayout layout = new BorderLayout(); panel.setLayout(layout); panel.add("North", welcome); panel.add("East", equals); panel.add("South", askMe); panel.add("West", lessThan); panel.add("Center", greaterThan); > >
//Border layout + Location BorderLayout layout = new BorderLayout(); panel.setLayout(layout); panel.add("North", welcome); panel.add("South", askMe); JPanel buttonPanel = new JPanel(new GridLayout(1,3)); buttonPanel.add(lessThan); buttonPanel.add(equals); buttonPanel.add(greaterThan); panel.add(buttonPanel);
The code has been resolved to make sure that the , and = buttons located on the west and center are uniformly sized, regardless of the window size.
Combine the three buttons onto a single panel and position it in the center. The preferred sizes of the buttons are not respected when using BorderLayout , causing them to be stretched. Instead, use a JPanel with a default FlowLayout to ensure that the preferred sizes are maintained. Lastly, remember to perform setVisible(true) as the final step.
panel.add(welcome, BorderLayout.NORTH); panel.add(askMe, BorderLayout.SOUTH); JPanel centerPanel = new JPanel(); centerPanel.add(lessThan); centerPanel.add(greaterThan); centerPanel.add(equals); JPanel justToCenterPanel = new JPanel(new GridBagLayout()); justToCenterPanel.add(centerPanel); panel.add(justToCenterPanel, BorderLayout.CENTER);
Please be aware that the method you are currently utilizing, which is the add method, is no longer in use. We suggest that you switch to add(component, BorderLayout.CENTER) for better functionality.
Upon review, it was observed that a BorderLayout was utilized. Consequently, please refer to peeskillet’s response above (https://stackoverflow.com/a/21912257).
An extremely practical approach could be similar to.
greaterThan.setPreferredSize(lessThan.getPreferredSize()); equals.setPreferredSize(lessThan.getPreferredSize());
To ensure uniformity, you can either enlarge the lessThan button or create a custom-sized Dimension button. However, it’s advisable to explore alternative LayoutManagers as the default one ( FlowLayout ) offers limited flexibility. For instance, you can group the three buttons and place them in a JPanel buttonPanel = new JPanel(new GridLayout(1,3)); for better layout.
To utilize Eclipse IDE, simply include the WindowBuilder Plugin, select the absolute layout option, and customize the layout as desired. WindowBuilder is a convenient plugin for drag and drop of swing UI components.
Lect 2.7 — Cool Button Styles in JAVA || Make a Round, In this video we are going to discuss that how to make a rounder button with hover effect. Provide a CSS type look to your GUI’s.For Make a online button : h