Skip to main content

Java Swing: JDialog, JPanel & JToggleButton

Java JDialog

The JDialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons.

JDialog class declaration

Let's see the declaration for javax.swing.JDialog class.

  1. public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer  

Commonly used Constructors:

ConstructorDescription
JDialog()It is used to create a modeless dialog without a title and without a specified Frame owner.
JDialog(Frame owner)It is used to create a modeless dialog with specified Frame as its owner and an empty title.
JDialog(Frame owner, String title, boolean modal)It is used to create a dialog with the specified title, owner Frame and modality.

Java JDialog Example

  1. import javax.swing.*;  
  2. import java.awt.*;  
  3. import java.awt.event.*;  
  4. public class DialogExample {  
  5.     private static JDialog d;  
  6.     DialogExample() {  
  7.         JFrame f= new JFrame();  
  8.         d = new JDialog(f , "Dialog Example"true);  
  9.         d.setLayout( new FlowLayout() );  
  10.         JButton b = new JButton ("OK");  
  11.         b.addActionListener ( new ActionListener()  
  12.         {  
  13.             public void actionPerformed( ActionEvent e )  
  14.             {  
  15.                 DialogExample.d.setVisible(false);  
  16.             }  
  17.         });  
  18.         d.add( new JLabel ("Click button to continue."));  
  19.         d.add(b);   
  20.         d.setSize(300,300);    
  21.         d.setVisible(true);  
  22.     }  
  23.     public static void main(String args[])  
  24.     {  
  25.         new DialogExample();  
  26.     }  
  27. }  

Output:

Java Jdialog 1

Java JPanel

The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class.

It doesn't have title bar.

JPanel class declaration

  1. public class JPanel extends JComponent implements Accessible  

Commonly used Constructors:

ConstructorDescription
JPanel()It is used to create a new JPanel with a double buffer and a flow layout.
JPanel(boolean isDoubleBuffered)It is used to create a new JPanel with FlowLayout and the specified buffering strategy.
JPanel(LayoutManager layout)It is used to create a new JPanel with the specified layout manager.

Java JPanel Example

  1. import java.awt.*;  
  2. import javax.swing.*;  
  3. public class PanelExample {  
  4.      PanelExample()  
  5.         {  
  6.         JFrame f= new JFrame("Panel Example");    
  7.         JPanel panel=new JPanel();  
  8.         panel.setBounds(40,80,200,200);    
  9.         panel.setBackground(Color.gray);  
  10.         JButton b1=new JButton("Button 1");     
  11.         b1.setBounds(50,100,80,30);    
  12.         b1.setBackground(Color.yellow);   
  13.         JButton b2=new JButton("Button 2");   
  14.         b2.setBounds(100,100,80,30);    
  15.         b2.setBackground(Color.green);   
  16.         panel.add(b1); panel.add(b2);  
  17.         f.add(panel);  
  18.                 f.setSize(400,400);    
  19.                 f.setLayout(null);    
  20.                 f.setVisible(true);    
  21.         }  
  22.         public static void main(String args[])  
  23.         {  
  24.         new PanelExample();  
  25.         }  
  26.     }  

Output:

Java Jpanel 1Java JFileChooser

The object of JFileChooser class represents a dialog window from which the user can select file. It inherits JComponent class.


JFileChooser class declaration

Let's see the declaration for javax.swing.JFileChooser class.

  1. public class JFileChooser extends JComponent implements Accessible  

Commonly used Constructors:

ConstructorDescription
JFileChooser()Constructs a JFileChooser pointing to the user's default directory.
JFileChooser(File currentDirectory)Constructs a JFileChooser using the given File as the path.
JFileChooser(String currentDirectoryPath)Constructs a JFileChooser using the given path.

Java JFileChooser Example

  1. import javax.swing.*;    
  2. import java.awt.event.*;    
  3. import java.io.*;    
  4. public class FileChooserExample extends JFrame implements ActionListener{    
  5. JMenuBar mb;    
  6. JMenu file;    
  7. JMenuItem open;    
  8. JTextArea ta;    
  9. FileChooserExample(){    
  10. open=new JMenuItem("Open File");    
  11. open.addActionListener(this);            
  12. file=new JMenu("File");    
  13. file.add(open);             
  14. mb=new JMenuBar();    
  15. mb.setBounds(0,0,800,20);    
  16. mb.add(file);              
  17. ta=new JTextArea(800,800);    
  18. ta.setBounds(0,20,800,800);              
  19. add(mb);    
  20. add(ta);              
  21. }    
  22. public void actionPerformed(ActionEvent e) {    
  23. if(e.getSource()==open){    
  24.     JFileChooser fc=new JFileChooser();    
  25.     int i=fc.showOpenDialog(this);    
  26.     if(i==JFileChooser.APPROVE_OPTION){    
  27.         File f=fc.getSelectedFile();    
  28.         String filepath=f.getPath();    
  29.         try{  
  30.         BufferedReader br=new BufferedReader(new FileReader(filepath));    
  31.         String s1="",s2="";                         
  32.         while((s1=br.readLine())!=null){    
  33.         s2+=s1+"\n";    
  34.         }    
  35.         ta.setText(s2);    
  36.         br.close();    
  37.         }catch (Exception ex) {ex.printStackTrace();  }                 
  38.     }    
  39. }    
  40. }          
  41. public static void main(String[] args) {    
  42.     FileChooserExample om=new FileChooserExample();    
  43.              om.setSize(500,500);    
  44.              om.setLayout(null);    
  45.              om.setVisible(true);    
  46.              om.setDefaultCloseOperation(EXIT_ON_CLOSE);    
  47. }    
  48. }  

Output:

Java Jfilechooser 1 Java Jfilechooser 2 Java Jfilechooser 3

Java JToggleButton

JToggleButton is used to create toggle button, it is two-states button to switch on or off.

Nested Classes

Modifier and TypeClassDescription
protected classJToggleButton.AccessibleJToggleButtonThis class implements accessibility support for the JToggleButton class.
static classJToggleButton.ToggleButtonModelThe ToggleButton model

Constructors

ConstructorDescription
JToggleButton()It creates an initially unselected toggle button without setting the text or image.
JToggleButton(Action a)It creates a toggle button where properties are taken from the Action supplied.
JToggleButton(Icon icon)It creates an initially unselected toggle button with the specified image but no text.
JToggleButton(Icon icon, boolean selected)It creates a toggle button with the specified image and selection state, but no text.
JToggleButton(String text)It creates an unselected toggle button with the specified text.
JToggleButton(String text, boolean selected)It creates a toggle button with the specified text and selection state.
JToggleButton(String text, Icon icon)It creates a toggle button that has the specified text and image, and that is initially unselected.
JToggleButton(String text, Icon icon, boolean selected)It creates a toggle button with the specified text, image, and selection state.

Methods

Modifier and TypeMethodDescription
AccessibleContextgetAccessibleContext()It gets the AccessibleContext associated with this JToggleButton.
StringgetUIClassID()It returns a string that specifies the name of the l&f class that renders this component.
protected StringparamString()It returns a string representation of this JToggleButton.
voidupdateUI()It resets the UI property to a value from the current look and feel.

JToggleButton Example

  1. import java.awt.FlowLayout;  
  2. import java.awt.event.ItemEvent;  
  3. import java.awt.event.ItemListener;  
  4. import javax.swing.JFrame;  
  5. import javax.swing.JToggleButton;  
  6.   
  7. public class JToggleButtonExample extends JFrame implements ItemListener {  
  8.     public static void main(String[] args) {  
  9.         new JToggleButtonExample();  
  10.     }  
  11.     private JToggleButton button;  
  12.     JToggleButtonExample() {  
  13.         setTitle("JToggleButton with ItemListener Example");  
  14.         setLayout(new FlowLayout());  
  15.         setJToggleButton();  
  16.         setAction();  
  17.         setSize(200200);  
  18.         setVisible(true);  
  19.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  20.     }  
  21.     private void setJToggleButton() {  
  22.         button = new JToggleButton("ON");  
  23.         add(button);  
  24.     }  
  25.     private void setAction() {  
  26.         button.addItemListener(this);  
  27.     }  
  28.     public void itemStateChanged(ItemEvent eve) {  
  29.         if (button.isSelected())  
  30.             button.setText("OFF");  
  31.         else  
  32.             button.setText("ON");  
  33.     }  
  34. }  

Output

Java JTogglebutton





Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&