Showing posts with label Swing Components. Show all posts
Showing posts with label Swing Components. Show all posts

Spring Hibernate Set Background Color in JLabel - Swing

Here is a sample tutorial to set background for a JLabel. By default, calling the setBackground(Color color) will not do the thing.



import javax.swing.*;
import java.awt.*;
class JLabelBackgroundDemo extends JFrame
{
JLabel l1,l2;
public JLabelBackgroundDemo()
{
setTitle("JLabel Background Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,400);
setLayout(new FlowLayout());
setVisible(true);
// Create labels
l1=new JLabel("I am first label");
l2=new JLabel("I am second label");
// Make opaque
l1.setOpaque(true);
l2.setOpaque(true);
// Then, set background
l1.setBackground(Color.cyan);
l2.setBackground(Color.pink);
// Add labels
add(l1);
add(l2);
}
public static void main(String args[])
{
new JLabelBackgroundDemo();
}
}
Notes: By default, the JLabel is not opaque, so you will have to make it opaque first in order to set a background for it.

Spring Hibernate Setting Background Image in JFrame - Swing

Here is sample tutorial, a simple trick that enables you to set background image for JFrame.



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
JButton b1;
JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
One way
-----------------
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
*/
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
setSize(399,399);
setSize(400,400);
}
public static void main(String args[])
{
new BackgroundImageJFrame();
}
}
 Notes: 

The first way: Here i have taken a JLabel named background and an image icon to it and then set the layout of the frame as BorderLayout so that it appears whole window.And then, i have added the label background to the frame. Next, some components are added to the label background instead of the frame and the layout for the background label is set as FlowLayout so that the components come side by side from the starting of the frame.

The second way: Here i used the setContentPane(Container c) method, which means to set the container (the one that contains the components) to the frame. As JLabel being one of the sub-classes of the Container, i have used it, added an image icon to it. You could also note, the BorderLayout which is set in order to make the image spread on the whole frame Next, as usual i have changed the layout for the frame and then added components to it.

The Refresh: This is essential because, the background image will not visible when the frame is opened. So, we will need to refresh it. So, i have called the setSize(int w,int h) twice which resizes (i.e. refreshes) the frame so that the background image will be visible.

Spring Hibernate Set Background Color in JFrame - Swing

Here is a sample tutorial for setting the background color for a JFrame. By default, as in the AWT, a call to the setBackground(Color) method won't do the thing. Here is how-to achieve this.

Background Color for JFrame


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundColorJFrame extends JFrame
{
public BackgroundColorJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
// Get the container and set the background
getContentPane().setBackground(Color.lightGray);
}
public static void main(String args[])
{
new BackgroundColorJFrame();
}
}

Spring Hibernate Using JButton - Minimize/Maximize/Close JFrame

You can use a JButton to perform the actions on the JFrame. This is also a tutorial for JButton with ActionListener.

Use JButton to Maximize/Minimize/Close JFrame


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class JButtonWindowActions extends JFrame
{
JButton button1,button2,button3;
public JButtonWindowActions()
{
setTitle("JButtonWindowActions Demo");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setOpacity(0.7f);
button1=new JButton("Maximize/Restore");
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(getExtendedState()==NORMAL)
setExtendedState(MAXIMIZED_BOTH);
else
setExtendedState(NORMAL);
}
});
button2=new JButton("Minimize");
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
setState(ICONIFIED);
}
});
button3=new JButton("Close");
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
dispose();
}
});
// add buttons to frame
add(button1);
add(button2);
add(button3);
// pack the frame
pack();
}
public static void main(String args[])
{
new JButtonWindowActions();
}
}
setOpacity(0.7f): To just set the Opacity of the frame. It is optional.
NORMAL: Set the frame to the normal state i.e. it's original state.
MAXIMIZED_BOTH: Make the frame maximized i.e. spread it to the full screen.
ICONIFIED: Make the frame be at the task bar.
dispose(): Dispose the frame.

Spring Hibernate Create JProgressBar using Timer class in Swing

Here is a sample and easy tutorial to make a JProgressBar do its work i.e. keep loading. The javax.swing.Timer class allows you to do so.



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JProgressBarTimer extends JFrame
{
JProgressBar jp;
Timer t;
int i=0;
public JProgressBarTimer()
{
try
{
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
}catch(Exception e){}
setTitle("JProgressBar Timer Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
setLocationRelativeTo(null);
setVisible(true);
// Create a progress bar
jp=new JProgressBar();
// Paint the percent complete on progress bar
jp.setStringPainted(true);
// Set a size (optional)
jp.setPreferredSize(new Dimension(500,30));
// Start at 0
jp.setMinimum(0);
// End at 1000
jp.setMaximum(1000);
// Create a timer that executes for every 2 millisec
t=new Timer(2,new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(i==1000)
i=0;
jp.setValue(i++);
}
});
// Start the timer
t.start();
add(jp);
pack();
}
public static void main(String args[])
{
new JProgressBarTimer();
}
}
NimbusLookAndFeel: I used the NimbusLookAndFeel because it is my choice personally. Alternatively, you can just leave that if you don't want to switch from the default MetalLookAndFeel.

Spring Hibernate Create Shaped Transparent JFrames in Java Swing

Here is a sample tutorial making fun with JFrame, giving it all the shapes that you can to a frame. Make a frame look circular, ellipse, curve, rounded rectanble, some other different shape that cannot be defined and may not be seen. Here i will show how you can customize your JFrame as you wish.

Circular Shape

Cubic Curve Shape

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
class ShapedJFrame extends JFrame
{
JButton b1;
public ShapedJFrame()
{
setTitle("Transparent JFrame Demo");
setLayout(new GridBagLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setUndecorated(true);
setVisible(true);
setOpacity(0.4f);

// Try different shapes

// Normal rounded rectangle
//setShape(new RoundRectangle2D.Double(0,0,getWidth(),getHeight(),20,40));

//Ellipse shape
//setShape(new Ellipse2D.Double(0,0,400,400));

// Quad Curve
//setShape(new QuadCurve2D.Double(0,0,400,50,400,400));

// Cubic Curve. Looks funny:)
//setShape(new CubicCurve2D.Double(0,0,500,5,200,0,500,500));

// For three-fourth circle
//setShape(new Arc2D.Double(new Rectangle2D.Double(0,0,500,500),90,270,Arc2D.PIE));

// For round circle shape
setShape(new Arc2D.Double(new Rectangle2D.Double(0,0,500,500),90,360,Arc2D.PIE));

b1=new JButton("I am a button!");
add(b1);

setSize(500,500);
setLocationRelativeTo(null);
}
public static void main(String args[])
{
new ShapedJFrame();
}
}
Round Rectangle:  Mostly found. A Rectangle with rounded corners. Double is a static class in the RoundRectangle2D class located in the java.awt.geom package.
new RoundRectangle2D.Double(double x, double y, double width, double height,double cornerwidth,double cornerheight)
QuadCurve.Double(double x1,double y1,double ctrlx,double ctrly,double x2,double y2):  Another shape.

CubicCurve2D.Double(double x1,double y1, double ctrlx1,double ctrly1,double ctrlx2,double ctrly2,double x2,double y2): The cubic curve shape. Define it yourself seeing what shape you get :)

Arc2D.Double(Rectangle2D rd,double start,double end, int type): Rectangle2D is an abstract class therefore, we use Rectangle2D.Double class which is static inner class. In this we specify, the x,y coordinates and width and height. Next the type of the arc. Possible types are Arc2D.CHORD, Arc2D.PIE, Arc2D.OPEN.

Spring Hibernate How-To: Create a Transparent JFrame in Java Swing

Here is a sample tutorial, can be a swing hack to optimize your JFrame to give it a better look through transparency.



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class TransparentJFrame extends JFrame
{
JButton b1;
public TransparentJFrame()
{
setTitle("Transparent JFrame Demo");
setSize(400,400);
setLayout(new GridBagLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
//For Java 1.7 or above
setOpacity(0.4f);
//For lower java versions
//com.sun.awt.AWTUtilities.setWindowOpacity(this,0.4f);
b1=new JButton("I am a button!");
add(b1);
}
public static void main(String args[])
{
new TransparentJFrame();
}
}
GridBagLayout: To make the JButton come to center. You can use your own layout depending upon your wish.

Spring Hibernate Using Nimbus Look And Feel in JButton (Swing)

Here is how the JButton looks in the new Nimbus Look And Feel of Java 7. The following example works only in Java 7 or may be higher versions but not on Java 6 and lower.

 
import javax.swing.*;
import java.awt.*;
class NimbusButtonDemo extends JFrame
{
JButton b1,b2;
    public NimbusButtonDemo()
    {

    // set the nimbus look and feel
    try
    {
    UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
    }catch(Exception e){}


    setTitle("Nimbus Button Demonstration Swing");
    setLayout(new FlowLayout());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);

   
    // Create buttons
    b1=new JButton("I am first Nimbus button!");
    b2=new JButton("I am second Nimbus button!");
   
    // add buttons to the frame
    add(b1);
    add(b2);
       
    // pack the frame
    pack();
    }
    public static void main(String args[])
    {
    new NimbusButtonDemo();
    }
}
UIManager: Present in the javax.swing package. Capable of performing look and feel related operations.
setLookAndFeel: An overloaded method that takes the class name or the Look And Feel object and the sets the corresponding look to the components. It throws ClassNotFoundException, InstantiationException, IllegalAccessException

Spring Hibernate Creating Menu Like Buttons in Swing

Buttons acting like menus in Java. It's just like what you have seen in Windows 7 and in most software. It is like Menus without a MenuBar. It is dead simple.



import javax.swing.*;
import java.awt.*;
class MenuButton extends JFrame
{
JMenuBar menuBar;
JMenu menu;
JMenuItem newFile,open,save,saveas,exit;

    public MenuButton()   
    {
    setTitle("Menu Button");
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
   
    // Set a background for menubutton to have a visible look
    getContentPane().setBackground(Color.darkGray);

    menuBar=new JMenuBar();
    menuBar.setBorderPainted(false);
   
    menu=new JMenu("File");

    // It's my style!
    menu.setBorderPainted(false);

    newFile=new JMenuItem("New");
    open=new JMenuItem("Open");
    save=new JMenuItem("Save");
    saveas=new JMenuItem("Save As");
    exit=new JMenuItem("Exit");

    menu.add(newFile);
    menu.add(open);
    menu.add(save);
    menu.add(saveas);
    menu.add(exit);
   
    // Add menu to menubar
    menuBar.add(menu);

    // Add(don't set) menubar to frame
    add(menuBar);

    // Make frame maximized for a good look
        //setExtendedState(MAXIMIZED_BOTH);

    // or pack
    pack();   
    }
    public static void main(String args[])
    {
    new MenuButton();
    }

}
javax.swing.*: Contains JFrame, JMenuBar, JMenu, JMenuItem.
java.awt.*: Contains the layout classes. FlowLayout here.
borderPainted(): Make the border painted false. It is your wish!




Spring Hibernate Add and Remove Elements in JList Dynamically

Till now we've seen how to work with JLists, store jlist selected items using serialization also on how it looks on NimbusLookAndFeel and now it's time to look at how to dynamically add contents to JList and delete them.


Shall we go? OK. Let's go!


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class DynamicJList extends JFrame
{
JMenuBar mbar;
JMenu menu;
JTextField jf;
JButton jb;
JList<String> jl;
Vector<String> v;
public DynamicJList()
{
// Set frame properties
setTitle("Dynamic JList");
setSize(400,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

// Create a vector that can store String objects
v=new Vector<String>();

// Create a JList that is capable of storing String type items
jl=new JList<String>(v);

// Make it fat.
jl.setPreferredSize(new Dimension(200,200));

// Add key listener to JList jl
jl.addKeyListener(new KeyAdapter(){

// What to do when a key is pressed?
public void keyPressed(KeyEvent ke)
{

// If user presses Delete key,
if(ke.getKeyCode()==KeyEvent.VK_DELETE)
{

// Remove the selected item
v.remove(jl.getSelectedValue());

// Now set the updated vector (updated items)
jl.setListData(v);

}
}
});

// Create a new MenuBar
mbar=new JMenuBar();

// Create a menu with text Menu
menu=new JMenu("Menu");

// Create a JButton with text Add
jb=new JButton("Add");

// Add actionlistener to JButton jb
jb.addActionListener(new ActionListener(){

// When user does an action?
public void actionPerformed(ActionEvent ae)
{

// Add what the user types in JTextField jf, to the vector
v.add(jf.getText());

// Now set the updated vector to JList jl
jl.setListData(v);

// Make the button disabled
jb.setEnabled(false);

}

});

jf=new JTextField(20);

// Add key listener to JTextField
jf.addKeyListener(new KeyAdapter(){

// What to do when a key is pressed?
public void keyPressed(KeyEvent ke)
{
// Make the JButton enabled
jb.setEnabled(true);

// When user presses enter key, then..
if(ke.getKeyCode()==KeyEvent.VK_ENTER)
// Click on JButton, doClick() does it!
jb.doClick();

}
});

// Add JTextField jf to JMenu menu
menu.add(jf);

// Add JButton jb to JMenu menu
menu.add(jb);

// Add JMenu menu to JMenuBar mbar
mbar.add(menu);

// Add MenuBar to frame. Don't set.
add(mbar);

// Create a scrollpane for JList jl
JScrollPane js=new JScrollPane(jl);

// Add that scrollpane to JFrame. You don't need to add JList again, as you add scrollpane, it means that you are adding JList because JScrollPane is pointing JList only!
add(js);

}

public static void main(String args[])
{
new DynamicJList();
}

}

That's it. Everything is explained within the program and all that is in this paragraph for you has a link to other  swing components. Take a look.

Watch it. Before you leave!



Spring Hibernate Create Swing Buttons using JButton

Here is a tutorial illustrating javax.swing.JButton class in Java used to create buttons.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class JButtonDemo extends JFrame
{
JButton button1,button2;
    public JButtonDemo()
    {
    setTitle("JButton Demo - I am the default title!");
    setSize(400,400);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());

    button1=new JButton("Click me!");
    button1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
            setTitle("You clicked me!");
            getContentPane().setBackground(Color.red);
            }
        });
    button2=new JButton("Click me too!");
    button2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
            setTitle("You clicked me too!");
            getContentPane().setBackground(Color.blue);
            }
        });
    add(button1);
    add(button2);
    }
    public static void main(String args[])
    {
    new JButtonDemo();
    }

}

getContentPane(): By default, we cannot apply background to a JFrame so we use this method to get the container of the JFrame and paint the background on it.
ActionListener(){}: An anonymous inner class is written for ease because only we've got two buttons.
javax.swing.*: Import everything from swing package, including JFrame, JButton
java.awt.event.*: Everything to handle the events. Here ActionListener and ActionEvent
java.awt.*: For Color and FlowLayout class here.

-----------------------------------
Output
-----------------------------------

Spring Framework Set Hand Cursor for JButton

An example on setting hand cursor for JButton in Java.

Example


import javax.swing.*;

import java.awt.*;

class HandCursorButton

{

public static void main(String args[])

{

JFrame f=new JFrame();

f.setTitle("Hand Cursor for JButton");

f.setSize(400,400);

f.setLayout(new FlowLayout());

f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



JButton b=new JButton("Click me!");

b.setCursor(new Cursor(Cursor.HAND_CURSOR));

f.add(b);

}

}

Output


Hand Cursor for JButton
Hand Cursor for JButton

Spring Framework Set Background Image to JMenuBar

This illustrates setting background image to JMenuBar. For this we need to paint an background image on JMenuBar. 1 main step is far from background image.






import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class MenuBarBackground extends JFrame

{

JMenuBar mbar;

JMenu menu;

public MenuBarBackground()

{

setTitle("MenuBar Background");

setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);



mbar=new JMenuBar(){

public void paintComponent(Graphics g)

{

g.drawImage(Toolkit.getDefaultToolkit().getImage("F:/Wallpapers/violetpink.png"),0,0,this);

}

};



menu=new JMenu("Menu");

menu.setForeground(Color.white);

for(int i=1;i<=5;i++)

menu.add(new JMenuItem("MenuItem "+i));



mbar.add(menu);

setJMenuBar(mbar);

setSize(400,400);

}

public static void main(String args[])

{

new MenuBarBackground();

}

}

Output

Background Image for JMenuBar
Look at menubar background image

paintComponent(Graphics g): Takes java.awt.Graphics as parameter. This contains drawImage() method which takes java.awt.Image object, x,y axes and ImageObserver object. paint() is not used here because, if we use this, i could not see the Menu.

g.drawImage(Toolkit.getDefaultToolkit().getImage("F:/Wallpapers/violetpink.png"),0,0,this): Method of java.awt.Graphics class. java.awt.Toolkit is a class containing a static method getDefaultToolkit() which returns the object of that class only (java.awt.Toolkit). This class contains getImage() method which takes the path of the image file and returns the java.awt.Image object. My background image is located in F:\Wallpapers. You can notice / instead of \ this is because / is equal to \\ in Windows and similar operating systems. Next, 0,0 are the x,y co ordinates respectively. Try changing them, you'll notice the change. this represents current object which acts as ImageObserver.

In this way, we can set background image to JMenuBar easily in single step.

Spring Framework Set Selection Background, Foreground for JMenu

Java Tutorial
The following illustrates setting selection background, foreground for JMenu in java swing. This is simple and involves 2 lines of important code. Here we go.








import javax.swing.*;

import java.awt.*;

class SelectionBackgroundJMenu extends JFrame

{

JMenuBar mbar;

JMenu menu;

JMenuItem m1,m2,m3,m4;



public SelectionBackgroundJMenu()

{



UIManager.put("Menu.selectionBackground",new Color(245,29,29));

UIManager.put("Menu.selectionForeground",Color.white);



setTitle("Colored Menu");

setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);



mbar=new JMenuBar();

menu=new JMenu("Menu");



for(int i=1;i<=5;i++)

menu.add(new JMenuItem("Menu Item "+i));



mbar.add(menu);

setJMenuBar(mbar);



setSize(400,400);

setLocationRelativeTo(null);

}



public static void main(String args[])

{

new SelectionBackgroundJMenu();

}

}

Output

Selection Background, Foreground JMenu

The respective properties are useful for setting selection backgrounds for JMenu. The first word (before .) indicates the component (Menu here), after that the property. Note that not all components have this property.

UIManager.put("Menu.selectionBackground",new Color(245,29,29)): This sets the selection background with the given color.
UIManager.put("Menu.selectionForeground",Color.white): This sets the selection foreground with given color (white).

Spring Hibernate Random Progress Speed for JProgressBar

Random Progress in JProgressBar


Here is a sample tutorial, to randomize JProgressBar progress speed.

Randomize Progress - Example




import javax.swing.*;
import java.awt.*;
import java.util.*;
class RandomProgressbar extends JFrame implements Runnable
{
JProgressBar jb;
Thread t;
Random r;

public RandomProgressbar()
{
setTitle("Random Progress in ProgressBar");
setLayout(new GridBagLayout());
setSize(400,400);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

jb=new JProgressBar();
jb.setStringPainted(true);

r=new Random();

t=new Thread(this);
t.start();
add(jb);
}
public static void main(String args[])
{
new RandomProgressbar();
}
public void run()
{
try
{
for(int i=1;i<=jb.getMaximum();i++)
{
jb.setValue(i);

int rnum=r.nextInt(100);

Thread.sleep(rnum);

// Print random number
System.out.println("Generated number : "+rnum);

// Loop forever

if(i==jb.getMaximum())
i=1;
}
}catch(Exception e){}

}

}


javax.swing.*: JFrame, JProgressBar used.

java.awt.*: GridBagLayout used.

java.util.*: Random class used.

jb.setStringPainted(true): Let the percent complete be visible.

t.start(): Start thread execution. Run is invoked.

jb.getMaximum(): Returns maximum value. Default: 100

jb.setValue(i): Update JProgressBar value to i (declared in loop).

r.nextInt(100): Returns random number from 0 to 100

Thread.sleep(rnum): Set random sleep time, for random speed.

Runnable interface: Contains run() method.


Spring Framework Set Selection Background, Foreground for JMenuItem

Java Tutorial
The following example illustrates setting selection background, foreground for JMenuItem in java swing. This is simple and involves 2 lines of important code. Here we go.






import javax.swing.*;

import java.awt.*;

class SelectionBackgroundJMenuItem extends JFrame

{

JMenuBar mbar;

JMenu menu;

JMenuItem m1,m2,m3,m4;



public SelectionBackgroundJMenuItem()

{



UIManager.put("MenuItem.selectionBackground",new Color(245,29,29));

UIManager.put("MenuItem.selectionForeground",Color.white);



setTitle("Colored Menu Item");

setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);



mbar=new JMenuBar();

menu=new JMenu("Menu");



for(int i=1;i<=5;i++)

menu.add(new JMenuItem("Menu Item "+i));



mbar.add(menu);

setJMenuBar(mbar);



setSize(400,400);

setLocationRelativeTo(null);

}



public static void main(String args[])

{

new SelectionBackgroundJMenuItem();

}

}

Output

Selection Background, Foreground JMenuItem
Output Window


The respective properties are useful for setting backgrounds for MenuItem. The first word (before .) indicates the component (MenuItem here), after that the property. Note that not all components have this property.

UIManager.put("MenuItem.selectionBackground",new Color(245,29,29)): This sets the selection background with the given color.
UIManager.put("MenuItem.selectionForeground",Color.white): This sets the selection foreground with given color (white).

Spring Hibernate Using JTextArea in Java Swing

JTextArea


Component that stores data of multiple rows. Part of javax.swing package.

Class Structure


public class JTextArea extends javax.swing.JTextComponent


Constructors


  public JTextArea();
  public JTextArea(String text);
  public JTextArea(int rows, int columns);
  public JTextArea(String text, int rows, int columns);
  public JTextArea(Document documentobj);
  public JTextArea(Document documentobj, String text, int rows, int columns);


Methods



  public void setTabSize(int size);
  public int getTabSize();

  public void setLineWrap(boolean flag);
  public boolean getLineWrap();

  public void setWrapStyleWord(boolean flag);
  public boolean getWrapStyleWord();

  public void insert(String text, int pos);

  public void append(String text);

  public void replaceRange(String text, int start, int end);

  public int getRows();
  public void setRows(int);

  public int getColumns();
  public void setColumns(int cols);


  public void setFont(Font font);


Example




import javax.swing.*;
import java.awt.*;

class JTextAreaJava extends JFrame
{
JTextArea jt1,jt2,jt3,jt4;
JScrollPane js1,js2,js3,js4;
public JTextAreaJava()
{
setTitle("Java JTextArea");
setLayout(new GridLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

jt1=new JTextArea();

/* Methods */
jt1.setText("First TextArea");
jt1.setFont(new Font("Times New Roman",Font.PLAIN,22));
jt1.append("Appended Text.");
jt1.setTabSize(20);
jt1.setRows(100);
jt1.setColumns(100);
jt1.setLineWrap(true);
jt1.setWrapStyleWord(false);
jt1.insert(" Inserted in middle. ",10);

js1=new JScrollPane(jt1);
add(js1);


jt2=new JTextArea("Second TextArea");
jt2.setFont(new Font("Times New Roman",Font.PLAIN,22));
jt2.append(" Appended Text Second TextArea ");
jt2.setLineWrap(true);
jt2.setWrapStyleWord(true);

js2=new JScrollPane(jt2);
add(js2);

jt3=new JTextArea(100,50);
jt3.setText("Third TextArea");
jt3.setFont(new Font("Times New Roman",Font.PLAIN,22));

js3=new JScrollPane(jt3);
add(js3);

jt4=new JTextArea("Fourth TextArea",100,50);
jt4.setFont(new Font("Times New Roman",Font.PLAIN,22));
jt4.replaceRange("Forth", 0,6);

js4=new JScrollPane(jt4);
add(js4);
setExtendedState(MAXIMIZED_BOTH);
}

public static void main(String args[])
{
new JTextAreaJava();
}
}

jt1.setText("First TextArea") : Set "First TextArea" in jt1.

jt1.setFont(new Font("Times New Roman"),Font.PLAIN,22): Set font for the textarea jt1. The font, Times New Roman, style: PLAIN, size: 22.

jt1.append("Appended Text."): This text will be appended at last to jt1.

jt1.setLineWrap(true): Enable linewrap, i.e. if the text reaches end of line, then remaining text gets in new line.

jt1.setWrapStyleWord(false): Set word style to false, so that if a word reaches the end and is not completed, the whole word doesn't come in the new line. You can understand it if you are familiar with WordWrap in Notepad.

jt1.insert(" Insert in middle. ",10): Insert text at the specified position, here 10

jt4.replaceRange("Forth",0,6): Replace text with Forth with the text between 0 and 6.

Spring Hibernate JComboBox - See this example to know what's inside the box?

What is JComboBox?


Nothing, it is just son of Choice in the AWT. Son doesn't mean that it is the sub class of Choice, instead i just mean that it does the same thing as the Choice in the AWT does. It allows only one item to choose. Mostly used to check Male/Female, Date of Birth (Day-Month-Year) etc.

The Example







import javax.swing.*;
import java.awt.*;
class JComboBoxExample extends JFrame
{
JComboBox jc1,jc2;
public JComboBoxExample()
{

setTitle("I am JComboBox Example!");
setSize(400,400);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

jc1=new JComboBox();

// Add items
jc1.addItem("Google");
jc1.addItem("Yahoo!");
jc1.addItem("Bing");
jc1.addItem("iGo4iT Search");

// Set 4th item selected
jc1.setSelectedIndex(3);

// Add jc1 to JFrame
add(jc1);

jc2=new JComboBox();

// Add items
jc2.addItem("Amazon.com");
jc2.addItem("eBay");
jc2.addItem("Walmart");
jc2.addItem("Best Buy");

// Make it editable
jc2.setEditable(true);

// Add jc to JFrame
add(jc2);

}

public static void main(String args[])
{
new JComboBoxExample();
}
}

Explanation


jc1,jc2: Both are the objects for the JComboBox.

addItem(""): Method of the JComboBox used to add items to it. The parameter to it is usually java.lang.Object, as per the requirement i have used String as it is a sub class of java.lang.Object class.

jc1.setSelectedIndex(3): As we know, index usually start from 0. Setting the selected index as 3 means that select the 4th item (0 1 2 3). Therefore, iGo4iT Search is selected.

jc2.setEditable(true): You might have observed, some drop downs can be edited i.e. the user is allowed to type something in it usually in autocomplete. It is obvious now i hope so, that the by passing true to the method lets the user type something in the JComboBox.

Spring Framework Add Custom Components to JFileChooser

Let me show you how to add custom components to JFileChooser in Swing. This is very easy and even you have a method for that. In this post, i will be showing you how to use that method to use your own components and enjoy! Here we go!






import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class CustomJFileChooser extends JFrame

{

private JButton jb;

private JFileChooser jf;

private JPanel jp;

private JLabel jl;



 public CustomJFileChooser()

 {

 createAndShowGUI();

 }

 

 private void createAndShowGUI()

 {

 

 // Set frame properties

 setTitle("Custom JFileChooser");

 setSize(400,400);

 setLayout(new FlowLayout());

 setLocationRelativeTo(null);

 setDefaultCloseOperation(EXIT_ON_CLOSE);

 setVisible(true);

 

 // Create JButton

 jb=new JButton("Open JFileChooser");

 

 // Add ActionListener to JButton

 jb.addActionListener(new ActionListener(){

  public void actionPerformed(ActionEvent ae)

  {

  // Create JFileChooser

  jf=new JFileChooser();



  // Create JPanel

  jp=new JPanel();

 

  // Create JLabel

  jl=new JLabel("I am a label on custom JFileChooser");

 

  // Add JLabel to the JPanel

  jp.add(jl); 



  // This is that method, do it before showOpenDialog!

  jf.setAccessory(jp);

  

  // Show Open Dialog

  jf.showOpenDialog(null);

}

 });

 

 // Add JButton to the JFrame

 add(jb);

 }

 

 public static void main(String args[])

 {

 new CustomJFileChooser();

 }

}

Output of the CustomJFileChooser

Adding Custom Components to JFileChooser
Custom JFileChooser Screenshot

This is not a hack, it is just a feature provided. This is the way you can add your own custom components to JFileChooser. You don't actually need the JPanel, I just added it, you can directly add JLabel to it. But in order to have a layout of the components we added i added JPanel. Good to know if we can add components in a certain layout to the JFileChooser without JPanel and without disturbing the layout of the JFileChooser's by-birth components.

Spring Framework Center JDialog on Screen & JFrame in Java Swing

An example on keeping JDialog on the center of the screen and on the center of JFrame in Java.


Example


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CenterJDialog extends JFrame
{

JButton jb;
JDialog jd;
JFrame thisFrame;

public CenterJDialog()
{

// Set frame properties
setTitle("Center a JDialog");
setSize(400,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);

// Set value of thisFrame to current object
thisFrame=this;

// Create a JButton
jb=new JButton("Click me to open JDialog :)");

// Add JButton to the JFrame
add(jb);

// Add action listener for jb
jb.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae)
{
// Set dialog properties
jd=new JDialog(thisFrame);
jd.setTitle("I am a JDialog");
jd.setLayout(new FlowLayout());

// Add sample components
jd.add(new JTextField(20));
jd.add(new JButton("Button"));

jd.setVisible(true);
jd.pack();

// Set location centered for JFrame
jd.setLocationRelativeTo(thisFrame);

// Set location centered for screen
//jd.setLocationRelativeTo(null);

}
});

}

public static void main(String args[])
{

new CenterJDialog();

}

}

Output


Center JDialog on screen and JFrame in Swing
Center JDialog for JFrame [here] for screen [src]

Labels

.equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()