Showing posts with label swing. Show all posts
Showing posts with label swing. Show all posts

combobox key value pair using java

          key value pair combobox example

step 1: Create a class with two variables , key and value

public class customcombo {
String key;
int value;
public customcombo(String key, int value) {
this.key= key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key= key;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString(){
return key;
}
}


Step2: set combobox model(static or dynamic)


case 1: static data ,do the following way

Object[] items=new Object[]{new customcombo("INDIA",1),new customcombo("UAE",2),new customcombo("USA",3)};
javax.swing.JComboBox jComboBox1 = new javax.swing.JComboBox();
DefaultComboBoxModel mod=new DefaultComboBoxModel(items);
jComboBox1.setModel(mod);

case 2: dynamic(database) value , do the following way

Object[] items = null;
ResultSet rs = st.executeQuery("select id,country from tb");
if (rs.next()) {
rs.last();
items = new customcombo[rs.getRow()];
rs.beforeFirst();
}
int i = 0;
while (rs.next()) {
items[i++] = new customcombo(Integer.parseInt(rs.getString(1)), rs.getString(2));
}


step 3: When program run ,combobox display name(key). To get value of the display name, use the following code


customcombo ob=(customcombo) jComboBox1.getSelectedItem();
Now you get both value
int val=ob.value;
String country=ob.key;

disabling table cell in java

Here when user enter value 3 for a cell in a table, then that cell becomes uneditable


class Testing
{
public void buildGUI()
{
JTable table = new JTable(5,3){
public boolean isCellEditable(int row,int column){
Object o = getValueAt(row,column);
if(o != null && o.equals("3")) return false;
return true;
}
};
JFrame f = new JFrame();
f.getContentPane().add(new JScrollPane(table));
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
}
});
}
}

Round double value using java

You can round a double using the setScale() method of BigDecimal class.

public double round(double d, int decimalPlace) {

BigDecimal bd = new BigDecimal(Double.toString(d));

bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);

return bd.doubleValue();

}

java panel with background image in swing

Following code show how to display background image on a JPanel

public class ImageTest {
public static void main(String[] args) {
ImagePanel panel = new ImagePanel(new ImageIcon("images/img.png").getImage());
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

class ImagePanel extends JPanel {

private Image img;

public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}

public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}

public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}

}

sorting vector contains vector elements

Sort java vector which contain another vector as its elements, here sorting is based on last element of the vector(element of main vecotor)

Vector result = new Vector();
Object[] o = result.toArray();

Arrays.sort(o, new Comparator() {

public int compare(Object o1, Object o2) {
Vector v1 = (Vector) o1;
Vector v2 = (Vector) o2;
Object[] res1 = v1.toArray();
Object[] res2 = v2.toArray();
int len = res1.length;
if (Double.parseDouble(res1[len - 1].toString()) == Double.parseDouble(res2[len - 1].toString())) {

return 0;
} else if (Double.parseDouble(res1[len - 1].toString()) > Double.parseDouble(res2[len - 1].toString())) {
return -1;
} else {
return 1;
}

}
});
// create new vector ie sorted vector
Vector new=new Vector(Arrays.asList(o));

Background Image for MDI Form using java

Step 1: Create a class that inherit(extends) JDesktopPane class

class JDesktopBackground extends JDesktopPane {

private Image image;
private BufferedImage scaledImage;
private int cachedHeight = -1;
private int cachedWidth = -1;
public JDesktopBackground(Image image) {
super();
this.image = image;
}

protected void paintComponent(Graphics g) {
if (cachedHeight != getHeight() && cachedWidth != getWidth())
createScaledImage();
g.drawImage(scaledImage, 0, 0, this);
}

private void createScaledImage() {
cachedWidth = getWidth();
cachedHeight = getHeight();
if (cachedWidth > 0 && cachedHeight > 0) {
scaledImage = new BufferedImage(cachedWidth, cachedHeight,
BufferedImage.TYPE_INT_RGB);
scaledImage.createGraphics().drawImage(
image,
AffineTransform.getScaleInstance(((float) cachedWidth)
/ image.getWidth(this), ((float) cachedHeight)
/ image.getHeight(this)), null);
} else
scaledImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
}

}
Step 2: Create MDI Form
Here i create MDI Form named addpicinmdi and do the following (see statement written in italic forms)

public class addpicinmdi extends javax.swing.JFrame {

JDesktopPane desktopPane;
BufferedImage bf=null;
public addpicinmdi() throws IOException {
bf=ImageIO.read(getClass().getResourceAsStream("/test/r.jpg"));
//initialize variable
desktopPane = new JDesktopBackground(bf);

}

keyboard shortcut for a button using java

Here it show how to install a keyboard shortcut to a Swing JButton so the button behaves as though it was clicked when the key is pressed.

JButton jButton1 = new JButton();
jButton1.setText("Save");

int key=2 ;
//key=1->shift, key =2 -> ctrl
InputMap inputMap = jButton1.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW);
KeyStroke sav = KeyStroke.getKeyStroke(KeyEvent.VK_S, key);
inputMap.put(sav, "Save");
jButton1.getActionMap().put("Save", new ClickAction(jButton1));

jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("Save Operation");
}
});

------------------
------------------

class ClickAction1 extends AbstractAction {
private JButton button;

public ClickAction1(JButton button) {
this.button = button;
}

public void actionPerformed(ActionEvent e) {
button.doClick();
}
}