JComboBox displaying invisible drop-down menu - java

This is my first question on stackoverflow and I'm in need of some help.
As part of a grander java application, I would like to bring up a JDialog with a couple of JComboBoxes querying the user to select a printer to use and then select the association resolution at which to print.
However, if I select a printer and the resolution which I pick is shared amongst several printers, then when I pick a printer which contains the same resolution, the drop down menu which gets displayed for the resolution combo box is invisible. The size of the drop down menu is correct, it just doesn't get populated. Try my code out and you'll see what I mean.
For example, two of my printing options are Win32 Printer : Kyocera FS-1035MFP KX and Win32 Printer : Adobe PDF (print to pdf). They both share the resolution 300x300, so if I select this resolution for the Kyocera and then select the Adobe PDF printer, the drop down menu will be the correct size, but will be empty.
I'm not really sure what is going on. Hopefully someone can help me. Thank you for your time.
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Vector;
import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.PrinterResolution;
import javax.swing.*;
public final class ComboDemo extends JDialog {
private JComboBox selectPrinterBox;
private JLabel selectPrinterLabel;
private JComboBox selectResolutionBox;
private JLabel selectResolutionLabel;
private PrintService printService;
private Resolution resolution;
private DocFlavor flavor;
private PrintRequestAttributeSet aset;
private Vector<Resolution> resolutionVector;
private double xDPI = 300.0;
private double yDPI = 300.0;
public PrintService[] getPrintServices() {
this.flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
this.aset = new HashPrintRequestAttributeSet();
return PrintServiceLookup.lookupPrintServices(flavor, aset);
}
public Vector<Resolution> getVectorOfResolutions(PrintService service) {
PrinterResolution[] supportedResolutions =
(PrinterResolution[]) service.getSupportedAttributeValues(
javax.print.attribute.standard.PrinterResolution.class,
flavor, aset);
Vector<Resolution> resolutions = new Vector<Resolution>();
for (PrinterResolution supportedResolution : supportedResolutions) {
Resolution res = new Resolution();
res.setxDPI(supportedResolution.getResolution(PrinterResolution.DPI)[0]);
res.setyDPI(supportedResolution.getResolution(PrinterResolution.DPI)[1]);
resolutions.add(res);
}
return resolutions;
}
public ComboDemo() {
super();
initComponents();
setContent();
setItemListeners();
}
public void initComponents() {
this.selectPrinterLabel = new JLabel("Select Printer: ");
PrintService[] services = this.getPrintServices();
this.selectPrinterBox = new JComboBox(services);
this.printService = (PrintService) this.selectPrinterBox.getSelectedItem();
this.resolutionVector = this.getVectorOfResolutions(printService);
this.resolution = new Resolution();
this.selectResolutionLabel = new JLabel("Select Resolution: ");
this.selectResolutionBox = new JComboBox(this.resolutionVector);
}
public void setContent() {
JPanel selectPrinterPanel = new JPanel();
selectPrinterPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
selectPrinterPanel.add(selectPrinterLabel);
selectPrinterPanel.add(selectPrinterBox);
JPanel selectResolutionPanel = new JPanel();
selectResolutionPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
selectResolutionPanel.add(selectResolutionLabel);
selectResolutionPanel.add(selectResolutionBox);
JPanel mainPanel = new JPanel();
BoxLayout fP = new BoxLayout(mainPanel, BoxLayout.Y_AXIS);
mainPanel.setLayout(fP);
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
mainPanel.add(selectPrinterPanel);
mainPanel.add(selectResolutionPanel);
this.setContentPane(mainPanel);
this.setTitle("ComboDemo");
this.setLocation(85, 79);
this.pack();
}
public void setItemListeners() {
selectPrinterBox.addItemListener(
new ItemListener() {
#Override
public void itemStateChanged(ItemEvent evt) {
if (evt.getSource().equals(selectPrinterBox)) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
System.out.println("in printerBox itemListener");
printService = (PrintService) selectPrinterBox.getSelectedItem();
resolution = (Resolution) selectResolutionBox.getSelectedItem();
System.out.println("resolution (PrinterBox) : " + resolution.toString());
resolutionVector.clear();
resolutionVector.addAll(getVectorOfResolutions(printService));
if (resolutionVector == null) {
System.out.println("resVec is null");
}
if (resolutionVector.contains(resolution)) {
selectResolutionBox.setSelectedIndex(resolutionVector.lastIndexOf(resolution));
} else {
selectResolutionBox.setSelectedIndex(0);
}
}
}
}
});
selectResolutionBox.addItemListener(
new ItemListener() {
#Override
public void itemStateChanged(ItemEvent evt) {
if (evt.getSource().equals(selectResolutionBox)) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
System.out.println("in resolutionBox itemListener");
resolution = (Resolution) selectResolutionBox.getSelectedItem();
System.out.println("resolution (ResolutionBox) : " + resolution.toString());
xDPI = (double) resolution.getxDPI();
yDPI = (double) resolution.getyDPI();
}
}
}
});
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboDemo cd = new ComboDemo();
cd.setVisible(true);
}
});
}
}
class Resolution {
private int xDPI;
private int yDPI;
public int getxDPI() {
return xDPI;
}
public void setxDPI(int xDPI) {
this.xDPI = xDPI;
}
public int getyDPI() {
return yDPI;
}
public void setyDPI(int yDPI) {
this.yDPI = yDPI;
}
#Override
public String toString() {
return (this.getxDPI() + "x" + this.getyDPI());
}
#Override
public boolean equals(Object obj) {
if ( obj instanceof Resolution ) {
Resolution r = (Resolution) obj;
return (this.xDPI == r.xDPI) && (this.yDPI == r.yDPI);
}
return false;
}
#Override
public int hashCode() {
return (this.getxDPI()*1000)+ this.getyDPI();
}
}

The problem is that you are manipulating the Vector that backs up the implicit ComboBoxModel you are using, behind the back of that ComboBoxModel. If the resolution is not contained, you call setSelectedIndex(0) which eventually triggers a refresh of the items of the combo box (because of some twisted internals of JComboBox/DefaultComboBoxModel.
So:
Either use a ComboBoxModel and when you want to modify the content of the JComboBox, do it with the ComboBoxModel (take a look at the DefaultComboBoxModel)
Or use the JComboBox API (removeAllItems, addItem)
Use an ActionListener on the comboboxes. instead of ItemListener You will only be notified of "selection-change" events

Related

How to change the icon of a dynamically generated JButton

I have this java swing program, and im trying to figure out how can i create a button that upon clicking it will clear the text areas & change the icon of the person to put their hand down.
The buttons are dynamically generated using a for loop
And this
// To create buttons
for(int i=0 ; i < list.length; i++){
Participant pa = list[i];
JButton b = new JButton(pa.getNameButton(),participant);
b.addActionListener(e ->
{
String s = pa.toString() + questionPane.getText();
final ImageIcon raise = resizeIcon(new ImageIcon("src/raise.png"),30,30);
b.setIcon(raise);
JOptionPane.showMessageDialog(null,s,"Welcome to Chat Room",JOptionPane.INFORMATION_MESSAGE,pa.getImage());
});
p.add(b);
}
// Clear button logic
clearButton.addActionListener(e ->{
questionPane.setText("");
hostPane.setText("");
});
Okay, this is going to be a bit of fun.
The following example decouples much of the concept and makes use of a basic "observer pattern" to notify interested parties that the state has changed (ie, the chat's been cleared).
This is a basic concept where by you decouple the "what" from the "how", ie, "what" it is you want done (update the model) from the "how" it gets done (ie, button push). This makes it easier to adapt to more complex systems.
The example contains a ChatService, which has a single listener, which, for this example, simple tells interested parties that the chat has been cleared.
A more complex solution might have the ChatService generating events for when a user "raises" their hand, which allows the interested parties to deal with it in what ever way is relevant to them.
The example makes use of the Action API to decouple the work performed by each action from the UI itself. This helps create a single unit of work which is easier to deal with when you have a dynamic data set.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
ChatService chatService = new ChatService();
JPanel panel = new JPanel();
String[] names = new String[] {"Bryan", "Alan", "George", "Henry"};
List<PeopleAction> actions = new ArrayList<>(names.length);
for (String name : names) {
PeopleAction action = new PeopleAction(chatService, name, false);
actions.add(action);
}
Random rnd = new Random();
actions.get(rnd.nextInt(names.length)).setRaised(true);
for (Action action : actions) {
JButton btn = new JButton(action);
panel.add(btn);
}
setLayout(new GridLayout(2, 1));
add(panel);
JPanel hostPane = new JPanel();
JButton clearButton = new JButton(new ClearAction(chatService));
hostPane.add(clearButton);
add(hostPane);
}
}
public class ChatService {
private List<ChatListener> listeners = new ArrayList<>(25);
public void addChatListeners(ChatListener listener) {
listeners.add(listener);
}
public void removeChatListener(ChatListener listener) {
listeners.remove(listener);
}
protected void fireChatCleared() {
if (listeners.isEmpty()) {
return;
}
for (ChatListener listener : listeners) {
listener.chatCleared();
}
}
public void clear() {
// Do what's required
fireChatCleared();
}
}
public interface ChatListener {
public void chatCleared();
}
public class PeopleAction extends AbstractAction implements ChatListener {
private String name;
private boolean raised;
public PeopleAction(ChatService chatService, String name, boolean raised) {
// You can use either LARGE_ICON_KEY or SMALL_ICON to set the icon
this.name = name;
if (raised) {
putValue(NAME, "* " + name);
} else {
putValue(NAME, name);
}
chatService.addChatListeners(this);
}
public void setRaised(boolean raised) {
if (raised) {
putValue(NAME, "* " + name);
} else {
putValue(NAME, name);
}
}
public boolean isRaised() {
return raised;
}
#Override
public void actionPerformed(ActionEvent evt) {
// Do what ever needs to be done
setRaised(!isRaised());
}
#Override
public void chatCleared() {
setRaised(false);
}
}
public class ClearAction extends AbstractAction {
private ChatService chatService;
public ClearAction(ChatService chatService) {
this.chatService = chatService;
putValue(NAME, "Clear");
}
#Override
public void actionPerformed(ActionEvent evt) {
chatService.clear();
}
}
}

JDialog loses opacity after deiconify

Creating a transparent and undercoated JDialog with a JFrame as its parent
will lose transparency upon an iconify/deiconify sequence.
Example:
final JFrame f = new JFrame();
f.setSize(200, 200);
final JDialog d = new JDialog(f, false);
d.setSize(200, 200);
d.setUndecorated(true);
d.setOpacity(.8f);
f.setLocationRelativeTo(null);
d.setLocation(f.getLocation().x + 210, f.getLocation().y);
f.setVisible(true);
d.setVisible(true);
Before iconify, the JDialog is created fine. Here is a screenshot.
After an iconify/deiconify sequence, the JDialog is 100% opaque.
I'm looking for solution to this problem and thinking I'm doing something
incorrect or missing some code.
My environment is Java(TM) SE Runtime Environment (build 1.8.0_11-b12)
running on Microsoft Windows [Version 6.1.7601].
2014-11-13: There is an open JDK bug for this problem
JDK-8062946 Transparent JDialog will lose transparency upon iconify/deiconify sequence.
https://bugs.openjdk.java.net/browse/JDK-8062946
Seems like a bit of a bug to me.
The following seems to work using JDK7 on Windows 7:
f.addWindowListener( new WindowAdapter()
{
#Override
public void windowDeiconified(WindowEvent e)
{
d.setVisible(false);
d.setVisible(true);
}
});
Try the following. I've had various problems with the undecorated JDialog and when I find a
bypass to a new symptom I add it to this method. This is a trimmed example. Add error checking, exception handling and modify as necessary to suit your needs ( ie add listener removal code if your app creates and destroys passed parentWindow objects).
package trimmed.stackoverflow.example;
import java.awt.Color;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
public class Helper_Swing {
private static Helper_Swing instance;
private Helper_Swing() {
instance = this;
}
public static Helper_Swing getInstance() {
return instance == null ? new Helper_Swing() : instance;
}
private static class J42WindowAdapter extends WindowAdapter {
final private Window window;
final private JDialog dialog;
private Color colorBG = null;
private float opacity = 0.0f;
private J42WindowAdapter(final Window window, final JDialog dialog) {
super();
this.window = window;
this.dialog = dialog;
this.colorBG = window.getBackground();
this.opacity = window.getOpacity();
}
#Override
public void windowIconified(final WindowEvent e) {
colorBG = dialog.getBackground();
opacity = dialog.getOpacity();
dialog.setOpacity(1.0f); // Must call 1st
dialog.setBackground(Color.BLACK); // Must call 2nd
}
#Override
public void windowDeiconified(final WindowEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setBackground(colorBG);
dialog.setOpacity(opacity);
dialog.setVisible(true);
dialog.repaint();
}
});
}
}
public void bugFix_transparentJDialog(final Window parentWindow, JDialog childWindow) {
if (parentWindow != null && childWindow != null && childWindow.isUndecorated()) {
final WindowListener[] listeners = parentWindow.getWindowListeners();
for (int x = 0; x != listeners.length; x++) {
if (listeners[x] instanceof J42WindowAdapter) {
final J42WindowAdapter adapter = (J42WindowAdapter) listeners[x];
if (adapter.window == parentWindow && adapter.dialog == childWindow) {
childWindow = null;
break;
}
}
}
if (childWindow != null) {
parentWindow.addWindowListener(new J42WindowAdapter(parentWindow, childWindow));
}
}
}
}
Usage example:
Helper_Swing.getInstance().bugFix_transparentJDialog(parentWindow, dialog);

How to show the Dynamic update on JTree?/how to refresh or reload a JTree?

Application is simple with two panels in one frame
First panel, retrieve from database all student s, use multiple hashmap get parent and child arrangement and show it on tree.
Second panel, when you click on a student all details of that student (selectionlistener) shown in textboxes.
Now when I alter the name of the student on the 2nd panel, the database updates it properly but the tree shows the old value.
I have tried treepanel.reload(), I have tried treemodellistener.
Can anyone help me out here. Going through a lot of solutions online, all are partial which i could not apply to my code.
Thanks in advance.
Main frame.java
/**
* #author Suraj Baliga
*
* Returns a JFrame with two Panels one having the Jtree and other
* having the details of the selected tree component.It also has dynamic tree and
* dynamic textbox where updation of text in the textbox will change the value in
* databse on click of save button.The JDBC localhost url may change with each machine
* as the database location and port number may vary.
*/
package Student_Details;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.commons.collections.MultiHashMap;
public final class Main_frame extends JPanel
{
String sname,sschool;
ArrayList StudName_arrylst = new ArrayList();
ArrayList SchlName_arrylst = new ArrayList();
ArrayList StudDetailTxtFld_arrylst = new ArrayList();
static public Connection connect,connect_update;
public ResultSet resultSet;
public static ResultSet resultset2;
MultiHashMap SchlStud_hashmap = new MultiHashMap();
int i,j,k,k2,z;
DefaultMutableTreeNode tree_parent;
int SchlName_arylist_length, StudNamearrylst_length;
private tree_generation treePanel;
static JButton save_button = new JButton("Save");
static JButton cancel_button = new JButton("Cancel");
static JTextField studName_txtbox= new JTextField();
static JTextField studAddress_txtbox = new JTextField();
static JTextField studOthr_txtbox = new JTextField();
static public String user_name;
static public String user_add;
static public String user_other;
static JLabel name_label = new JLabel("Name : ");
static JLabel address_label = new JLabel("Adress : ");
static JLabel other_label = new JLabel("Other Deatils : ");
static String studDetailsTxtbox_disp[] = new String[10];
static String studDetailsTxtbx_disp_db[] = new String[10];
static String studDetailsTxtbxchange[] = new String[10];
public JPanel panel;
static JPanel panel_boxes = new JPanel();
public Main_frame()
{
super(new BorderLayout());
//Create the components.
treePanel = new tree_generation();
populateTree(treePanel);
//Lay everything out.
treePanel.setPreferredSize(new Dimension(300, 150));
add(treePanel, BorderLayout.WEST);
panel = new JPanel(new GridLayout(1, 2));
add(panel, BorderLayout.CENTER);
}
public void populateTree(tree_generation treePanel)
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement AllStuddetails = connect.prepareStatement("SELECT * from student_details");
resultSet = AllStuddetails.executeQuery();
while (resultSet.next())
{
sname = resultSet.getString(1);
sschool = resultSet.getString(3);
SchlStud_hashmap.put(sschool, sname);
}
}
catch (Exception e)
{
}
Set keySet = SchlStud_hashmap.keySet();
Iterator keyIterator = keySet.iterator();
while (keyIterator.hasNext())
{
Object key = keyIterator.next();
SchlName_arrylst.add(key);
Collection values = (Collection) SchlStud_hashmap.get(key);
Iterator valuesIterator = values.iterator();
while (valuesIterator.hasNext())
{
StudName_arrylst.add(valuesIterator.next());
}
SchlName_arylist_length = SchlName_arrylst.size();
StudNamearrylst_length = StudName_arrylst.size();
String schlname_tree[] = new String[SchlName_arylist_length];
String studname_tree[] = new String[StudNamearrylst_length];
Iterator SchlName_iterator = SchlName_arrylst.iterator();
i = 0;
while (SchlName_iterator.hasNext())
{
schlname_tree[i] = SchlName_iterator.next().toString();
}
Iterator StudName_iterator = StudName_arrylst.iterator();
j = 0;
while (StudName_iterator.hasNext())
{
studname_tree[j] = StudName_iterator.next().toString();
j++;
}
for (k = 0; k < schlname_tree.length; k++)
{
tree_parent = treePanel.addObject(null, schlname_tree[k]);
for (k2 = 0; k2 < studname_tree.length; k2++)
{
treePanel.addObject(tree_parent, studname_tree[k2]);
}
}
StudName_arrylst.clear();
SchlName_arrylst.clear();
}
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame = new JFrame("Student Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Main_frame newContentPane = new Main_frame();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
panel_boxes.setLayout(null);
name_label.setBounds(55,90,150,100);
studName_txtbox.setBounds(225,130, 155, 25);
panel_boxes.add(name_label);
panel_boxes.add(studName_txtbox);
address_label.setBounds(55,160, 150, 100);
studAddress_txtbox.setBounds(225,200, 155, 25);
panel_boxes.add(address_label);
panel_boxes.add(studAddress_txtbox);
other_label.setBounds(55,220, 150, 100);
studOthr_txtbox.setBounds(225,270, 155, 25);
panel_boxes.add(other_label);
panel_boxes.add(studOthr_txtbox);
save_button.setBounds(150,350, 100, 50);
cancel_button.setBounds(350,350, 100, 50);
panel_boxes.add(save_button);
panel_boxes.add(cancel_button);
frame.add(panel_boxes);
//Display the window.
frame.pack();
frame.setSize(1000,700);
frame.setVisible(true);
save_button.setEnabled(false);
cancel_button.setEnabled(false);
studName_txtbox.addFocusListener(new FocusListener()
{
#Override //since some additional functionality is added by the user to
//the inbuilt function #override notation is used
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
System.out.println("out of focus textbox");
}
});
studAddress_txtbox.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
save_button.setEnabled(false);
cancel_button.setEnabled(false);
}
});
studOthr_txtbox.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
save_button.setEnabled(false);
cancel_button.setEnabled(false);
}
});
cancel_button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== cancel_button )
{
clear_textboxes();
}
}
} );
save_button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== save_button )
{
selectionButtonPressed();
}
}
} );
}
public void fill_textboxes(ArrayList a1)
{
Iterator alldetails = a1.iterator();
z=0;
while (alldetails.hasNext())
{
studDetailsTxtbx_disp_db[z]= (String) alldetails.next();
System.out.println("this is the Detail : "+studDetailsTxtbx_disp_db[z]);
z++;
}
studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
}
public static void selectionButtonPressed()
{
studDetailsTxtbxchange[0]=studName_txtbox.getText();
studDetailsTxtbxchange[1]=studAddress_txtbox.getText();
studDetailsTxtbxchange[2]=studOthr_txtbox.getText();
try
{
if((studDetailsTxtbxchange[0].equals(""))||(studDetailsTxtbxchange[0] == null)||(studDetailsTxtbxchange[1].equals(""))||(studDetailsTxtbxchange[1] == null)||(studDetailsTxtbxchange[2].equals(""))||(studDetailsTxtbxchange[2] == null))
{
JOptionPane.showMessageDialog(null,"One of the Fields is Blank","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
System.out.println("control here inside else baby..that has : : "+studDetailsTxtbxchange[0]);
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement execqry = connect.prepareStatement("select * from student_details where student_name='"+studDetailsTxtbxchange[0]+"'");
resultset2=execqry.executeQuery();
System.out.println("control at end if else");
if(resultset2.next())
{
JOptionPane.showMessageDialog(null,"Sorry This name already exists","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
System.out.println("control here");
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
updateQry.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
tree_generation.loadit();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void clear_textboxes()
{
studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
}
void dbaction(String string)
{
studDetailsTxtbox_disp[0]= string;
System.out.println("This is the stuff :" + studDetailsTxtbox_disp[0]);
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2","suraj","suraj");
PreparedStatement statement4 = connect.prepareStatement("SELECT * from student_details where student_name ='"+studDetailsTxtbox_disp[0]+"'");
resultSet = statement4.executeQuery();
while(resultSet.next())
{
user_name = resultSet.getString("student_name");
StudDetailTxtFld_arrylst.add(user_name);
System.out.println("name :"+user_name);
user_add = resultSet.getString("student_address");
StudDetailTxtFld_arrylst.add(user_add);
System.out.println("address : "+ user_add);
user_other = resultSet.getString("student_school");
StudDetailTxtFld_arrylst.add(user_other);
System.out.println("school : "+user_other);
}
}
catch (Exception e1)
{
e1.printStackTrace();
}
fill_textboxes(StudDetailTxtFld_arrylst);
}
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createAndShowGUI();
}
});
}
}
tree_generation.java
/**
* #author Suraj
*
* Tree generation and actions such as adding new parent or child takes place here
* Section Listeners for displaying relavent details of the selected student.
*/
package Student_Details;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
public class tree_generation extends JPanel
{
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
protected JTree tree;
public String studDetailsTxtbox_disp[] = new String[10];
public tree_generation()
{
super(new GridLayout(1,0));
rootNode = new DefaultMutableTreeNode("Click for Student Details");
treeModel = new DefaultTreeModel(rootNode);
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeSelectionListener()
{
#Override
public void valueChanged(TreeSelectionEvent e)
{
studDetailsTxtbox_disp[0]= tree.getLastSelectedPathComponent().toString();
Main_frame db = new Main_frame();
db.dbaction(studDetailsTxtbox_disp[0]);
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane);
}
/** Add child to the currently selected node. */
public DefaultMutableTreeNode addObject(Object child)
{
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null) {
parentNode = rootNode;
}
else
{
parentNode = (DefaultMutableTreeNode)
(parentPath.getLastPathComponent());
}
return addObject(parentNode, child, true);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child)
{
return addObject(parent, child, false);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child,
boolean shouldBeVisible)
{
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(child);
if (parent == null)
{
parent = rootNode;
}
//It is key to invoke this on the TreeModel
treeModel.insertNodeInto(childNode, parent,
parent.getChildCount());
//Make sure the user can see the new node.
if (shouldBeVisible)
{
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
}
return childNode;
}
static void loadit()
{
tree_generation.treeModel.reload();
//i tried this too//
//treePanel = new tree_generation();
// populateTree(treePanel);
}
class MyTreeModelListener implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) {
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
node.setUserObject("HELLO WORLD");
/*
* If the event lists children, then the changed
* node is the child of the node we've already
* gotten. Otherwise, the changed node and the
* specified node are the same.
*/
int index = e.getChildIndices()[0];
node = (DefaultMutableTreeNode)(node.getChildAt(index));
System.out.println("The user has finished editing the node.");
System.out.println("New value: " + node.getUserObject());
}
public void treeNodesInserted(TreeModelEvent e) {
}
public void treeNodesRemoved(TreeModelEvent e) {
}
#Override
public void treeStructureChanged(TreeModelEvent e)
{
System.out.println("tree sturct changed") ;
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
node.setUserObject("HELLO WORLD");
tree.updateUI();
e.getTreePath();
}
}
}
Queries - DATABASE NAME : treedata2
create table student_details(student_name varchar(20),student_address varchar(30),student_school varchar(20));
insert into student_details values('suraj','mangalore','dps');
insert into student_details values('prassana','Bangalore lalbagh 23/16 2nd main road','dps');
insert into student_details values('deepika','Mangalore kadri park , 177b','dav');
insert into student_details values('sujith','delhi , rajinder nagar, d black','dav');
insert into student_details values('sanjay','bombay marina drive, 12/34','dav');
insert into student_details values('suresh','jaipur , lalbagh cjhowki','kv');
insert into student_details values('manu','surat, pune warior house','kv');
insert into student_details values('tarun','chennai, glof club','salwan');
insert into student_details values('vinay','haryana, indutrial area','hindu senior');
insert into student_details values('veeru','trivendrum, kottayam 12/77','canara')
Ok, I think I found what's not working in your code, but you should probably try it yourself and confirm.
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
updateQry.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
tree_generation.loadit();
In this code, you indeed update the database but you don't update the model of the tree. You are calling the static method loadit() but that method does not contain any code. In order to worker you should probably refresh/reload your TreeModel. There are different ways to do that. One would be to directly spot the TreeNode to refresh and update it with the new values. Another would be to recreate your entire TreeModel (but this can be costly if your tree is big). Using an object-mapping model (for instance JPA/Hibernate) you could have something much cleaner with an appropriate MVC-pattern and a model notifying the views of the updated values, but it requires extra-effort to set up.
For what it is worth, you should consider dropping those static keywords as they are not necessary nor appropriately used. Whenever possible, you should try to avoid using that keyword (unless it is used in conjunction with finalto describe a constant value).
One more thing, try to use appropriate LayoutManager's instead of using absolute-positionning. Using appropriate layout manager makes your code easier to maintain and more portable across different platforms/look and feels.

Vertical scrollbar in jTable swing does not appear

I am a bit new to swings, And i was trying to cough up some code involving Jtable.
I find that even though i have added the scrollbar policy the vertical scrollbar does not seem to appear. THe code is pretty shabby.(warning u before hand). But could you please indicate where I need to put in the scrollbar policy. I have tried adding it at a lot of places and it just does not seem to appear.
the other question is how do i make an empty table. As in every time the process button is clicked, i would like to refresh the table. Could u point me in this direction as well.
The directions for usage: just enter a number in the regular nodes textfield like 5 or 10
and click on the process button.
My code :
package ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import utils.ThroughputUtility;
/**
* #author Nathan
*
*/
public class EntryPoint extends JPanel{
public boolean isProcesed =false;
static JFrame frame;
JTabbedPane jTabbedPane = new JTabbedPane();
private static final long serialVersionUID = -6490905886388876629L;
public String messageTobeSent = null;
public int regularNodeCount =0;
public static final String MESSAGE_TO_BE_SENT =" Please Enter the message to be sent. ";
protected static final String ONE = "1";
Map<String,Double> regNodeThroughputMap ;
static JTable tableOfValues;
Object columnNames[] = { "<html><b>Regular Node Name</b></htm>", "<html><b>Throughput Value Obtained</b></html>"};
Object rowData[][] = null;
public EntryPoint() {
jTabbedPane.setTabPlacement(JTabbedPane.NORTH);
Font font = new Font("Verdana", Font.BOLD, 12);
jTabbedPane.setFont(font);
//Server Side Panel.
JPanel serverPanel = getServerPanel();
jTabbedPane.addTab("Server", serverPanel);
//Client side Panel.
JPanel clientPanel = getClientPanel();
jTabbedPane.addTab("Client", clientPanel);
}
private JPanel getClientPanel() {
//Heading Label
JPanel clientPanel = new JPanel();
JLabel RegularNodeLabel = new JLabel("<html><u>Throughput Optimization For Mobile BackBone Networks</u></html>");
RegularNodeLabel.setFont(new Font("Algerian",Font.BOLD,20));
RegularNodeLabel.setForeground(new Color(176,23,31));
clientPanel.add(RegularNodeLabel);
return clientPanel;
}
/**Server Side Code
* #return
*/
private JPanel getServerPanel() {
//Heading Label
JPanel serverPanel = new JPanel(new FlowLayout());
final Box verticalBox1 = Box.createVerticalBox();
Box horozontalBox1 = Box.createHorizontalBox();
Box verticalBox2forsep = Box.createVerticalBox();
Box horozontalBox2 = Box.createHorizontalBox();
JPanel heading = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel backBoneNodeLabel = new JLabel("<html><u>Throughput Optimization For Mobile BackBone Networks</u></html>");
backBoneNodeLabel.setFont(new Font("Algerian",Font.BOLD,20));
backBoneNodeLabel.setForeground(new Color(176,23,31));
backBoneNodeLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//Indication of BackBone Node
JPanel body = new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel backBoneNodeID = new JLabel("Fixed BackBone Node");
backBoneNodeID.setFont(new Font("Algerian",Font.BOLD,16));
backBoneNodeID.setForeground(new Color(176,23,31));
backBoneNodeID.setAlignmentX(Component.CENTER_ALIGNMENT);
//Seperator
JLabel seperator = new JLabel(" ");
seperator.setFont(new Font("Algerian",Font.BOLD,20));
seperator.setForeground(new Color(176,23,31));
verticalBox2forsep.add(seperator);
//Message label
JLabel messageLabel = new JLabel("Please enter the Message to be sent: ");
messageLabel.setFont(new Font("Algerian",Font.BOLD,16));
messageLabel.setForeground(new Color(176,23,31));
messageLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
//Message Text
final JTextField messageText = new JTextField(MESSAGE_TO_BE_SENT,25);
messageText.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent arg0) {
if(messageText.getText().trim().equalsIgnoreCase(MESSAGE_TO_BE_SENT.trim())){
messageText.setText("");
}
}
});
horozontalBox1.add(messageLabel);
horozontalBox1.add(messageText);
//Regular node attached to backbone nodes.
JLabel regularNodelabel = new JLabel("Number of Regular nodes to be attached to the backbone node. ");
regularNodelabel.setFont(new Font("Algerian",Font.BOLD,16));
regularNodelabel.setForeground(new Color(176,23,31));
regularNodelabel.setAlignmentX(Component.LEFT_ALIGNMENT);
//Regular Node text
final JTextField regularNodeText = new JTextField(ONE,5);
regularNodeText.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
if(regularNodeText.getText().trim().equalsIgnoreCase(ONE.trim())){
regularNodeText.setText("");
tableOfValues = new JTable(0,0);
}
}
});
horozontalBox2.add(regularNodelabel);
horozontalBox2.add(regularNodeText);
//Button for Processing.
JButton processbutton = new JButton("Process");
processbutton.setFont(new Font("Algerian",Font.BOLD,16));
processbutton.setForeground(new Color(176,23,31));
processbutton.setAlignmentX(Component.CENTER_ALIGNMENT);
//Processing on clciking process button
processbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
isProcesed=false;
Runnable runThread = new Runnable() {
#Override
public void run() {
while(!isProcesed){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
verticalBox1.add(tableOfValues);
isProcesed =false;
}
};
Thread processThread= new Thread(runThread);
processThread.start();
regularNodeCount = Integer.parseInt(regularNodeText.getText().trim());
regNodeThroughputMap = getThroughPutValues(regularNodeText.getText().trim());
System.out.println("Map obtained = "+regNodeThroughputMap);
tableOfValues = populateTable(regNodeThroughputMap);
isProcesed=true;
JScrollPane scrollPane = new JScrollPane(tableOfValues);
scrollPane.add(tableOfValues);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
verticalBox1.add(scrollPane,BorderLayout.CENTER);
// verticalBox1.add(scrollPane);
}
});
verticalBox1.add(backBoneNodeID);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(horozontalBox1);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(horozontalBox2);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(processbutton);
heading.add(backBoneNodeLabel);
//body.add(backBoneNodeID);
body.add(verticalBox1);
serverPanel.add(heading);
serverPanel.add(body);
return serverPanel;
}
protected JTable populateTable(Map<String,Double> regNodeThroughputMap) {
/*{ { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
{ "Row2-Column1", "Row2-Column2", "Row2-Column3" } }*/
rowData = new Object[regularNodeCount+1][2];
Set<Map.Entry<String, Double>> set = regNodeThroughputMap.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.println("key ="+me.getKey());
System.out.println("Value ="+me.getValue());
}
String[] keys = new String[regularNodeCount+2];
String[] values = new String[regularNodeCount+2];
List<String> keyList = new LinkedList<String>();
List<String> valueList = new LinkedList<String>();
keyList.add("");
valueList.add("");
for(String key:regNodeThroughputMap.keySet()){
keyList.add(key);
}
for(double value:regNodeThroughputMap.values()){
System.out.println(value);
valueList.add(Double.toString(value));
}
keyList.toArray(keys);
valueList.toArray(values);
System.out.println(Arrays.asList(keys));
System.out.println(Arrays.asList(values));
rowData[0][0] =columnNames[0];
rowData[0][1] =columnNames[1];
for(int i=1;i<=regularNodeCount;i++){
for(int j=0;j<2;j++){
if(j==0)
rowData[i][j]=keys[i];
if(j==1)
rowData[i][j]=values[i];
}
}
return new JTable(rowData, columnNames);
//Printing the array
/* for (int i =0; i < regularNodeCount; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(" " + rowData[i][j]);
}
System.out.println("");
}
*/
}
protected Map<String, Double> getThroughPutValues(String regularNodeInput) {
return ThroughputUtility.generateMapofNodeAndThroughput(regularNodeInput);
}
protected static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Throughput Optimization for Mobile BackBone Networks");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EntryPoint splitPaneDemo = new EntryPoint();
frame.getContentPane().add(splitPaneDemo.jTabbedPane);
JScrollPane sp = new JScrollPane(tableOfValues);
sp.setBorder(BorderFactory.createEmptyBorder());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(JScrollPane .HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.setResizable(false);
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setSize(800,600);
}
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Adding ThroughputUtility.java
package utils;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* #author Nathan
*
*/
public class ThroughputUtility {
public static double MIN =5000;
public static double MAX =10000;
public static final double e =Math.E;
public static final double epsilon = 8.854187 *Math.pow(10,-12);
static int regularNodeCount;
static int counter ;
/**Generates the map of Node and ThroughPut values
* #param regularNodeInput
*/
public static Map<String,Double> generateMapofNodeAndThroughput(String regularNodeInput){
regularNodeCount = Integer.parseInt(regularNodeInput);
List<Double> randNodeDistances =getRandDistanceOfNodes(regularNodeCount);
Map<String,Double> nodeAndThroughputmap = getThroughputValuesForNodes(randNodeDistances);
System.out.println(nodeAndThroughputmap);
return nodeAndThroughputmap;
}
/** Obtains the throughput value based on the distances between
* the regular nodes and the backend Nodes.
* #param randNodeDistances
* #return
*/
private static Map<String, Double> getThroughputValuesForNodes(
List<Double> randNodeDistances) {
Map<String,Double> nodeAndThroughputmap = new LinkedHashMap<String, Double>();
for(double i : randNodeDistances){
double throughputValue = calculateThroughPut(i);
nodeAndThroughputmap.put("RegularNode :"+counter, throughputValue);
counter++;
}
return nodeAndThroughputmap;
}
private static double calculateThroughPut(double distanceij) {
double throughput = 1 /(e*regularNodeCount*distanceij*epsilon);
return throughput;
}
/**Generates the distance dij .
* #param regularNodeCount
* #return
*/
private static List<Double> getRandDistanceOfNodes(int regularNodeCount) {
List<Double> distnodeNumbers = new LinkedList<Double>();
for(int i=0;i<regularNodeCount;i++){
double randnodeNumber = MIN + (double)(Math.random() * ((MAX - MIN) + 1));
distnodeNumbers.add(randnodeNumber);
}
return distnodeNumbers;
}
public static void main(String[] args) {
ThroughputUtility.generateMapofNodeAndThroughput("5");
/*System.out.println(e);
System.out.println(epsilon);*/
}
}
The main problem why you can't see the scroll bar is that you add the table to multiple containers.
when clicking the button, you recreate a lot of swing objects (why?), then you start a thread to add the table to the box (why?? be careful with swing and multithreading if you don't know what you are doing). after that (or before, depending on how long the thread is running) you add the table to the scrollpane.
the scrollpane does not contain your table, because you can only use it once.
A quick fix would be something like this:
create all you GUI stuff once, leave it out of any action listeners and stuff. if you start the application, it should just show an empty table. don't add the same object into multiple containers! you can control the size of your table and scrollpane by using
table.setPreferredSize(new Dimension(width, height));
if you click the button (that is in your action listener), get all the new data and add it it to the table. e.g. by using something like this.
tableOfValues.getModel().setValueAt(value, row, column);
or create a new table model if you have to:
tableOfValues.setModel(new DefaultTableModel(rowData, columnNames));
That's all I can tell you for now by looking at the code...
edit:
in the method populateTable(...) don't create a new table! use the above code to set a new model instead if you have to, or use an existing one and modify its values.
You never at the scroll pane to the JFrame as far as I could tell on
a quick look
You change the data in the TableModel (or replace the TableModel of
the JTable)
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
I had the same problem, just set JTable preferredsize to null and the scrollbar will show up.
Hope it helps

How do I create an event handler for a JLabel?

I want to make it so that if I click on the JLabel, the label becomes a new label with another image attached to it.
So far my code looks like:
public class Picture extends JFrame {
private ImageIcon _image1;
private ImageIcon _image2;
private JLabel _mainLabel;
private JLabel _mainLabel2;
public Picture(){
_image1 = new ImageIcon("src/classes/picture1.jpg");
_image2 = new ImageIcon("src/classes/picture2.jpg");
_mainLabel = new JLabel(_image1);
_mainLabel2 = new JLabel(_image2);
add(_mainLabel);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Add mouseListener to your JLable and in mouseClicked(mouseEvent) method change icon of JLabel.
A sample code may be:
jLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
jLabel.setIcon(newIcon);
}
});
Try using a JToggleButton instead. No need for a MouseListener, and responds to keyboard input.
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
import java.awt.Image;
class ToggleImage {
public static void main(String[] args) throws Exception {
URL url1 = new URL("http://pscode.org/media/stromlo1.jpg");
URL url2 = new URL("http://pscode.org/media/stromlo2.jpg");
final Image image1 = ImageIO.read(url1);
final Image image2 = ImageIO.read(url2);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JToggleButton button = new JToggleButton();
button.setIcon(new ImageIcon(image1));
button.setSelectedIcon(new ImageIcon(image2));
button.setBorderPainted(false);
button.setContentAreaFilled(false);
JOptionPane.showMessageDialog(null, button);
}
});
}
}
Old Code - before I realized this was about images
I want to make it so that if I click on the JLabel
What about for people who are 'mouse challenged? Use a JTextField instead. Tab to any link and hit Enter to activate.
import java.awt.Desktop;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.border.MatteBorder;
import javax.swing.border.Border;
import java.net.URI;
import java.io.File;
/**
A Java 1.6+ LinkLabel that uses the Desktop class for opening
the document of interest.
The Desktop.browse(URI) method can be invoked from applications,
applets and apps. launched using Java Webstart. In the latter
two cases, the usual fall-back methods are used for sandboxed apps
(see the JavaDocs for further details).
While called a 'label', this class actually extends JTextField,
to easily allow the component to become focusable using keyboard
navigation.
To successfully browse to a URI for a local File, the file name
must be constructed using a canonical path.
#author Andrew Thompson
#version 2008/08/23
*/
public class LinkLabel
// we extend a JTextField, to get a focusable component
extends JTextField
implements MouseListener, FocusListener, ActionListener {
/** The target or href of this link. */
private URI target;
public Color standardColor = new Color(0,0,255);
public Color hoverColor = new Color(255,0,0);
public Color activeColor = new Color(128,0,128);
public Color transparent = new Color(0,0,0,0);
public boolean underlineVisible = true;
private Border activeBorder;
private Border hoverBorder;
private Border standardBorder;
/** Construct a LinkLabel that points to the given target.
The URI will be used as the link text.*/
public LinkLabel(URI target) {
this( target, target.toString() );
}
/** Construct a LinkLabel that points to the given target,
and displays the text to the user. */
public LinkLabel(URI target, String text) {
super(text);
this.target = target;
}
/* Set the active color for this link (default is purple). */
public void setActiveColor(Color active) {
activeColor = active;
}
/* Set the hover/focused color for this link (default is red). */
public void setHoverColor(Color hover) {
hoverColor = hover;
}
/* Set the standard (non-focused, non-active) color for this
link (default is blue). */
public void setStandardColor(Color standard) {
standardColor = standard;
}
/** Determines whether the */
public void setUnderlineVisible(boolean underlineVisible) {
this.underlineVisible = underlineVisible;
}
/* Add the listeners, configure the field to look and act
like a link. */
public void init() {
this.addMouseListener(this);
this.addFocusListener(this);
this.addActionListener(this);
setToolTipText(target.toString());
if (underlineVisible) {
activeBorder = new MatteBorder(0,0,1,0,activeColor);
hoverBorder = new MatteBorder(0,0,1,0,hoverColor);
standardBorder = new MatteBorder(0,0,1,0,transparent);
} else {
activeBorder = new MatteBorder(0,0,0,0,activeColor);
hoverBorder = new MatteBorder(0,0,0,0,hoverColor);
standardBorder = new MatteBorder(0,0,0,0,transparent);
}
// make it appear like a label/link
setEditable(false);
setForeground(standardColor);
setBorder(standardBorder);
setCursor( new Cursor(Cursor.HAND_CURSOR) );
}
/** Browse to the target URI using the Desktop.browse(URI)
method. For visual indication, change to the active color
at method start, and return to the standard color once complete.
This is usually so fast that the active color does not appear,
but it will take longer if there is a problem finding/loading
the browser or URI (e.g. for a File). */
public void browse() {
setForeground(activeColor);
setBorder(activeBorder);
try {
Desktop.getDesktop().browse(target);
} catch(Exception e) {
e.printStackTrace();
}
setForeground(standardColor);
setBorder(standardBorder);
}
/** Browse to the target. */
public void actionPerformed(ActionEvent ae) {
browse();
}
/** Browse to the target. */
public void mouseClicked(MouseEvent me) {
browse();
}
/** Set the color to the hover color. */
public void mouseEntered(MouseEvent me) {
setForeground(hoverColor);
setBorder(hoverBorder);
}
/** Set the color to the standard color. */
public void mouseExited(MouseEvent me) {
setForeground(standardColor);
setBorder(standardBorder);
}
public void mouseReleased(MouseEvent me) {}
public void mousePressed(MouseEvent me) {}
/** Set the color to the standard color. */
public void focusLost(FocusEvent fe) {
setForeground(standardColor);
setBorder(standardBorder);
}
/** Set the color to the hover color. */
public void focusGained(FocusEvent fe) {
setForeground(hoverColor);
setBorder(hoverBorder);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
File f = new File(".","LinkLabel.java");
/* Filename must be constructed with a canonical path in
order to successfully use Desktop.browse(URI)! */
f = new File(f.getCanonicalPath());
JPanel p = new JPanel(new GridLayout(0,1));
URI uriFile = f.toURI();
LinkLabel linkLabelFile = new LinkLabel(uriFile);
linkLabelFile.init();
p.add(linkLabelFile);
LinkLabel linkLabelWeb = new LinkLabel(
new URI("http://pscode.org/sscce.html"),
"SSCCE");
linkLabelWeb.setStandardColor(new Color(0,128,0));
linkLabelWeb.setHoverColor(new Color(222,128,0));
linkLabelWeb.init();
/* This shows a quirk of the LinkLabel class, the
size of the text field needs to be constrained to
get the underline to appear properly. */
p.add(linkLabelWeb);
LinkLabel linkLabelConstrain = new LinkLabel(
new URI("http://stackoverflow.com/"),
"Stack Overflow");
linkLabelConstrain.init();
/* ..and this shows one way to constrain the size
(appropriate for this layout).
Similar tricks can be used to ensure the underline does
not drop too far *below* the link (think BorderLayout
NORTH/SOUTH).
The same technique can also be nested further to produce
a NORTH+EAST packing (for example). */
JPanel labelConstrain = new JPanel(new BorderLayout());
labelConstrain.add( linkLabelConstrain, BorderLayout.EAST );
p.add(labelConstrain);
LinkLabel linkLabelNoUnderline = new LinkLabel(
new URI("http://java.net/"),
"java.net");
// another way to deal with the underline is to remove it
linkLabelNoUnderline.setUnderlineVisible(false);
// we can use the methods inherited from JTextField
linkLabelNoUnderline.
setHorizontalAlignment(JTextField.CENTER);
linkLabelNoUnderline.init();
p.add(linkLabelNoUnderline);
JOptionPane.showMessageDialog( null, p );
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
}
You cannot simply add an actionListener, you need to implement MouseListener, something like this.
If you are looking for Customized JLable with different font and size and mouse action listeners just go through this.
This is fully tested with following tasks
1.JLabel with Image and Text.
2.Jlabel with Mouse Listners.
3.On hover action with image and text replacement.
public class CustomJLabel extends JLabel implements MouseListener
{
private Color color;
private int width=0;
private int height=0;
private ImageIcon normal_icon;
private ImageIcon hover_icon;
private ImageIcon icon_Label;
JLabel label;
private boolean isMatch;
public CustomJLabel(ImageIcon icon,ImageIcon icon1, String text, int i, int j) {
this.normal_icon=icon;
this.hover_icon=icon1;
this.icon_Label=normal_icon;
setFont(new Font("Tw Cen MT", Font.TYPE1_FONT, 16));
setForeground(Color.WHITE);
setOpaque(false);
setHorizontalAlignment( SwingConstants.CENTER );
setText(text);
addMouseListener(this) ;
}
public CustomJLabel(ImageIcon icon,ImageIcon icon1, int i, int j) {
this.normal_icon=icon;
this.hover_icon=icon1;
this.icon_Label=normal_icon;
setText("");
setVerticalAlignment( SwingConstants.CENTER);
setForeground(Color.WHITE);
setOpaque(false);
addMouseListener(this) ;
}
public CustomJLabel(ImageIcon icon,ImageIcon icon1, String text, int i, int j,Font f) {
this.normal_icon=icon;
this.hover_icon=icon1;
this.icon_Label=normal_icon;
this.width=i;
this.height=j;
setFont(f);
setForeground(Color.WHITE);
setOpaque(false);
setText(text);
setVerticalAlignment( SwingConstants.TOP);
addMouseListener(this) ;
}
public int getIconWidth(){
return width;
}
public int getIconHeight(){
return height;
}
#Override
public void paintComponent(Graphics g) {
if(this.width !=0 && this.height!=0){
super.paintComponent(g);
icon_Label.paintIcon(this, g, this.width, this.height);
}
else{
g.drawImage(icon_Label.getImage(),0,0, null);
super.paintComponent(g);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent me) {
// TODO Auto-generated method stub
if(hover_icon!=null){
this.icon_Label=hover_icon;
this.repaint();
this.revalidate();
}
else{
this.icon_Label=normal_icon;
this.repaint();
this.revalidate();
}
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
if(normal_icon!=null){
this.icon_Label=normal_icon;
this.repaint();
this.revalidate();
}
else{
this.icon_Label=hover_icon;
this.repaint();
this.revalidate();
}
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
//Here Usage of custom JLabel
JLabel customLabel;
customLabel=new CustomLabel(imageicon1,imageicon2,text,0,0)
//Here
Imageiocn1= Initial icon for JLabel.
Imageicon2= Onhover image for JLabel.
Text = Some String for setting name for JLabel.

Categories