devxlogo

Creating Hidden Buttons with Swing

Creating Hidden Buttons with Swing

Using Swing, you can easily create hidden buttons similar to the Back button used in Netscape Communicator 4. Hidden buttons look like normal graphic elements on the screen until you float over them with the mouse. This code was tested using JDK1.1.6 and Swing 1.0.3 under Win95:

 import java.awt.*;import java.awt.event.*;import com.sun.java.swing.*;public class SwingHiddenButton01 extends JFrame {	public static void main(String args[]) {		SwingHiddenButton01 demoFrame = 				new SwingHiddenButton01();	}//end main()	//-----------------------------------------------------//  	SwingHiddenButton01() {//constructor		setTitle("Hidden Buttons");		getContentPane().setLayout(new FlowLayout());		//Create two hidden buttons with no action listeners		JButton myJButton = new JButton("myButton");		myJButton.setBorderPainted(false);		myJButton.addMouseListener(new MyMouseListener());		getContentPane().add(myJButton);    		JButton urJButton = new JButton("urButton");		urJButton.setBorderPainted(false);		urJButton.addMouseListener(new MyMouseListener());		getContentPane().add(urJButton); 		//Set to windows look & feel    		String plafClassName = 			 "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";		try{			UIManager.setLookAndFeel(plafClassName);		}catch(Exception ex){System.out.println(ex);}		SwingUtilities.updateComponentTreeUI(this);		setSize(300,100);		setVisible(true);    		// Inner class WindowAdapter to terminate the		// program when the JFrame is closed.		addWindowListener(new WindowAdapter() {			public void windowClosing(WindowEvent e) {				System.exit(0);}});//end WindowListener    	}//end constructor	//=====================================================//	//Inner mouse listener class to show and hide buttons 	class MyMouseListener extends MouseAdapter{		public void mouseEntered(MouseEvent e){			//Display border on the button			((JButton)e.getSource()).setBorderPainted(true);		}//end mouseEntered()		public void mouseExited(MouseEvent e){			//Hide border on the button			((JButton)e.getSource()).setBorderPainted(false);		}//end mouseEntered()	}//end inner class myMouseListener     }//end class SwingHiddenButton01
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist