Java Swing Samples

Download a file in Worker(Background) Thread:

 

public static class DownloadResource extends SwingWorker<Void, Void> {
	
	@Override
	public Void doInBackground() {
		
				
		SearchResultModel model = resultList;			
		ListSelectionModel selectionModel = checkListManager.getSelectionModel();			
		
		for(int i=0; i<model.getSize(); i++) {
			
			if(selectionModel.isSelectedIndex(i) == true) {					
				
				String downloadURL = model.getElementAt(i).address;				    
				if(downloadURL.contains("abc")) {
					downloadFile(model.getElementAt(i).address);
				} else {
					System.out.println("Download url does not contain abc");
				}
			}
		}
		return null;
	}
}

public static void downloadFile(String downloadURL){
	try {
		
		URL url=new URL(downloadURL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		int filesize = connection.getContentLength();
		float totalDataRead=0;
		java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
		java.io.FileOutputStream fos = new java.io.FileOutputStream("C:/Users/Public/Downloads"+getFileName(downloadURL));
		java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
		byte[] data = new byte[1024];
		int i=0;
		while( (i=in.read(data,0,1024) ) >= 0 )
		{
			//totalDataRead=totalDataRead+i;
			bout.write(data,0,i);
			//float Percent=(totalDataRead*100)/filesize;
			//current.setValue((int)Percent);
		}	
		bout.close();
		in.close();
	}
	catch(Exception e) {
		 javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null,e.getMessage(), "Error",
				 javax.swing.JOptionPane.DEFAULT_OPTION);
	}
}

Java Swing custom list with checkbox

public class CheckListCellRenderer extends JPanel implements ListCellRenderer { 
	
    private ListCellRenderer delegate; 
    private ListSelectionModel selectionModel; 
    private JCheckBox checkBox = new JCheckBox(); 
 
    public CheckListCellRenderer(ListCellRenderer renderer, ListSelectionModel selectionModel){ 
        this.delegate = renderer; 
        this.selectionModel = selectionModel; 
        setLayout(new BorderLayout()); 
        setOpaque(false); 
        checkBox.setOpaque(false); 
    } 
 
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
    	
        Component renderer = delegate.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 
        checkBox.setSelected(selectionModel.isSelectedIndex(index)); 
        removeAll(); 
        add(checkBox, BorderLayout.WEST); 
        add(renderer, BorderLayout.CENTER); 
        return this;
    } 
}


public class CheckListManager extends MouseAdapter implements ListSelectionListener, ActionListener{ 
    
	private ListSelectionModel selectionModel = new DefaultListSelectionModel(); 
    private JList list = new JList(); 
    int hotspot = new JCheckBox().getPreferredSize().width; 
 
    public CheckListManager(JList list){ 
        this.list = list; 
        
        list.setCellRenderer(new CheckListCellRenderer(list.getCellRenderer(), selectionModel)); 
        
        list.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_FOCUSED); 
        list.addMouseListener(this); 
        selectionModel.addListSelectionListener(this); 
    } 
 
    public ListSelectionModel getSelectionModel(){ 
        return selectionModel; 
    } 
 
    private void toggleSelection(int index){ 
        if(index<0) 
            return; 
 
        if(selectionModel.isSelectedIndex(index)) 
            selectionModel.removeSelectionInterval(index, index); 
        else 
            selectionModel.addSelectionInterval(index, index); 
    } 
 
    public void mouseClicked(MouseEvent me){ 
        int index = list.locationToIndex(me.getPoint()); 
        if(indexlist.getCellBounds(index, index).x+hotspot) 
            return; 
        toggleSelection(index); 
    } 
 
    public void valueChanged(ListSelectionEvent e){ 
        list.repaint(list.getCellBounds(e.getFirstIndex(), e.getLastIndex())); 
        System.out.println("list selected index->"+e.getFirstIndex());
        System.out.println("value selected -->"+list.getSelectedValue());
        
        System.out.println("value selected -->"+list.getSelectedValuesList());
        
    } 
 
    public void actionPerformed(ActionEvent e){ 
        toggleSelection(list.getSelectedIndex()); 
    } 
} 

Usage:

CheckListManager checkListManager;
checkListManager = new CheckListManager(list);
ListSelectionModel selectionModel = checkListManager.getSelectionModel();

if(selectionModel.isSelectedIndex(i) == true)

Java Swing Musings

To prevent window from resizing:

frame.setResizable(false)

 

Manage two radio buttons so that only 1 is selectable at a time:

Use ButtonGroup
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);

 

In my application I have move the user from one screen to next on button click. I am wondering how to do it in Swing. There are couple of good posts I have come across for this Post1, Post2.

97kgp

 

Adding Border around a container: Set an EmptyBorder around your JPanel.

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));

OR

JPanel containerPanel = new JPanel();
containerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
containerPanel.setLayout(new BorderLayout());

 

Setting a background color same as container color

list.setBackground(panel.getBackground());

 

Anytime we modify the GUI in Swing we need to call:

frame.revalidate()
frame.repaint()


Why use of multiple JFrames in a Swing Application is a bad practice: Post

 

Right now I am searching how to update a JList with some contents, I wud be fetching from remote server.

 

 

 

Java Swing getting started with Eclipse (WindowBuilder)

I have to design a user interface for CKAN search, for desktop application. I am planning to use Java Swing for it.

To get started I would be using Eclipse IDE, I have installed WindowBuilder Eclipse Plugin for designing my user interface (https://eclipse.org/windowbuilder/).

Steps to install WindowBuilder on Eclipse (I am on version Mars 4.5).

Help -> Install new software -> Work with : Mars- http://download.eclipse.org/releases/mars -> General Purpose Tools

Here I have installed :
Swing Designer
SWT Designer
SWT Designer Core
WindowBuilder Core
WindowBuilder Core UI
WindowBuilder Java Core
WindowBuilder XML Core

 

To get started with WindowBuilder I found this post on stackoverflow

1) How can I make and run a simple window with WindowBuilder?

Go to File -> New -> Other. The "select a wizard" window pops up.

Double click in WindowBuilder folder and then to Swing Designer subfolder.

Click to the Application Window and then click Next.

Give a Name for your new window and then click Finish. The Source code of the new Window pops up.

Press Run (the "Play" icon of the toolbar) to run your newly created window.

2) How can I access the WindowBuilder Core from my Eclipse and show up the toolbar with buttons and textboxes e.t.c.?

To access the core WindowBuilder you have to switch to the Design View of your newly created window. To do that, just press the Design tab at the end of the window tab. You will see the core WindowBuilder Toolbar (or "Palette") and you will be able from here to drag-n-drop the controls you want into you window.

Links:
WindowBuilder: http://help.eclipse.org/kepler/index.jsp?topic=%2Forg.eclipse.wb.doc.user%2Fhtml%2Findex.html,