JButton.setIcon throws null pointer when file exists - java
OK, so I had an issue where my images weren't showing when the .jar file was run.
Fixed that by using a fix from robberman I think his tag was.
Anyways once I fixed that by getting the images from getResourceAsStream etc it worked fine. So when creating the background image, a JLabel with an image, and JButtons with images as new components, this works great!
Problem I keep running into now is I have 3 buttons that need to change their icons in certain situations. I've tested this and it works without the NullPointerException in my test class, but when I try this in my projects class I get a NullPointerException each time it tries to setIcon.
Here's the method I setup to change the Icon. (I've tried this many different ways, and thought this would be easiest to see since it happens no matter what I do. ) Here's the constructor, the createGUI and the method to change the icons. Please help me out figuring what I'm doing wrong.
public class Addons {
// Setup any variables needed for this class to run
private JPanel addonsList;
private JLabel patchNotes;
private JProgressBar progressBar;
private JTable addonsTable;
private SaveSettings sav;
private Updater util;
private JButton instructions;
private JButton installButton;
private JButton finishedButton;
private boolean finishedAll;
private boolean upAvail;
private Task task;
// Setup the tables for use in the listings
/**
* Default constructor
*
*/
public Addons(Updater util) {
// Load up the saved settings.
sav = new SaveSettings();
sav.loadSave();
this.util = util;
finishedAll = false;
upAvail = false;
createAddonsGUI();
}
/**
* This method will create the gui for use in the constructor
*
*/
private void createAddonsGUI() {
// create base panel
addonsList = new JPanel();
addonsList.setPreferredSize(new Dimension(800,435));
addonsList.setOpaque(false);
SpringLayout addonsListLO = new SpringLayout();
addonsList.setLayout(addonsListLO);
// Create and place scroll frame with patch notes panel in it.
JScrollPane patchNotesPanel = createPatchNotesPanel();
patchNotesPanel.setPreferredSize(new Dimension(370,300));
addonsList.add(patchNotesPanel);
// create and place progress bar
//JLabel progressBarBackground = new JLabel(new ImageIcon(util.PROGBACK_IMAGE_PATH));
JLabel progressBarBackground = new JLabel();
try {
Image mypBarPic = ImageIO.read(getClass().getClassLoader().getResourceAsStream("com/dynastyaddons/updater/ProgressBackground.png"));
progressBarBackground = new JLabel(new ImageIcon(mypBarPic));
} catch (IOException ignore) {
System.out.println("Error: " + ignore.getMessage());
}
addonsList.add(progressBarBackground);
SpringLayout pBarLO = new SpringLayout();
progressBarBackground.setLayout(pBarLO);
progressBarBackground.setOpaque(false);
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
progressBarBackground.add(progressBar);
pBarLO.putConstraint(SpringLayout.WEST, progressBar, 21, SpringLayout.WEST, progressBarBackground);
pBarLO.putConstraint(SpringLayout.NORTH, progressBar, 15, SpringLayout.NORTH, progressBarBackground);
pBarLO.putConstraint(SpringLayout.EAST, progressBar, -21, SpringLayout.EAST, progressBarBackground);
pBarLO.putConstraint(SpringLayout.SOUTH, progressBar, -45, SpringLayout.SOUTH, progressBarBackground);
// Create and place Finish button
//finishedButton = new JButton(new ImageIcon(util.FINOFF_IMAGE_PATH));
//public static final String FINOFF_IMAGE_PATH = "F:\\Java Programs\\Updater\\src\\com\\dynastyaddons\\updater\\images\\FinishedOff.png";
JButton finishedButton = new JButton();
try {
Image myfinishedButtonPic = ImageIO.read(getClass().getClassLoader().getResourceAsStream("com/dynastyaddons/updater/FinishedOff.png"));
finishedButton = new JButton(new ImageIcon(myfinishedButtonPic));
} catch (IOException ignore) {
System.out.println("Error: " + ignore.getMessage());
}
finishedButton.setBorderPainted(false);
finishedButton.setContentAreaFilled(false);
finishedButton.setFocusPainted(false);
finishedButton.setOpaque(false);
finishedButton.setToolTipText("<html><font size=6>When button glows blue, you're all done and you can press this to close the udpater.</font></html>");
finishedButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) { if(finishedAll) {System.exit(0);} }
});
addonsList.add(finishedButton);
// Create and place Install Addons Button
//installButton = new JButton(new ImageIcon(util.INSTOFF_IMAGE_PATH));
//public static final String INSTOFF_IMAGE_PATH = "F:\\Java Programs\\Updater\\src\\com\\dynastyaddons\\updater\\images\\InstallUpdatesOFF.png";
JButton installButton = new JButton();
try {
Image myinstallButtonPic = ImageIO.read(getClass().getClassLoader().getResourceAsStream("com/dynastyaddons/updater/InstallUpdatesOFF.png"));
installButton = new JButton(new ImageIcon(myinstallButtonPic));
} catch (IOException ignore) {
System.out.println("Error: " + ignore.getMessage());
}
installButton.setBorderPainted(false);
installButton.setContentAreaFilled(false);
installButton.setFocusPainted(false);
installButton.setOpaque(false);
installButton.setToolTipText("<html><center><font size=6>When arrows to the left of this button glow blue, you have updates to install.<br /> <br />Press this button to get the updated versions of your addons.</font></center></html>");
installButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
// This will handle installing needed updates
if(upAvail) {
JFrame root = util.getRootFrame();
root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task = new Task();
task.execute();
root.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
});
addonsList.add(installButton);
// Create and place scroll frame with the addons list table in it.
JPanel addonListPanel = new JPanel();
addonListPanel.setPreferredSize(new Dimension(388,245));
addonsTable = new JTable(new DynastyTableModel());
JTableHeader header = addonsTable.getTableHeader();
ColumnHeaderToolTips tips = new ColumnHeaderToolTips();
header.addMouseMotionListener(tips);
addonListPanel.setLayout(new BorderLayout());
addonListPanel.add(addonsTable.getTableHeader(), BorderLayout.PAGE_START);
addonListPanel.add(new JScrollPane(addonsTable), BorderLayout.CENTER);
// setup table settings
addonsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
addonsTable.setRowSelectionAllowed(true);
addonsTable.setColumnSelectionAllowed(false);
addonsTable.setBackground(Color.BLACK);
addonsTable.setForeground(Color.WHITE);
//addonsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
addonsTable.setFillsViewportHeight(true);
addonsTable.setPreferredScrollableViewportSize(addonListPanel.getPreferredSize());
addonsTable.setRowHeight(31);
// setup column width and editing
fitToContentWidth(addonsTable, 0);
fitToContentWidth(addonsTable, 1);
fitToContentWidth(addonsTable, 2);
fitToContentWidth(addonsTable, 3);
fitToContentWidth(addonsTable, 4);
// properly align text in cells
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
addonsTable.getColumn("Version").setCellRenderer( centerRenderer );
//addonsTable.getColumn("Purchase").setCellRenderer( centerRenderer );
addonsTable.getColumn("Size").setCellRenderer( centerRenderer );
//addonsTable.getColumn("Update").setCellRenderer( centerRenderer );
addonsTable.getColumn("Name").setCellRenderer( centerRenderer );
// setup list selector
ListSelectionModel listSelectionModel = addonsTable.getSelectionModel();
listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
addonsTable.setSelectionModel(listSelectionModel);
addonListPanel.setOpaque(false);
addonsList.add(addonListPanel);
// Create and place the view instructions button.
//instructions = new JButton(new ImageIcon(util.INSTRUCTIONS_BUTTON));
//public static final String INSTRUCTIONS_BUTTON = "F:\\Java Programs\\Updater\\src\\com\\dynastyaddons\\updater\\images\\instructions.png";
JButton instructions = new JButton();
try {
Image myinstructionsPic = ImageIO.read(getClass().getClassLoader().getResourceAsStream("com/dynastyaddons/updater/instructions.png"));
instructions = new JButton(new ImageIcon(myinstructionsPic));
} catch (IOException ignore) {
System.out.println("Error: " + ignore.getMessage());
}
instructions.setBorderPainted(false);
instructions.setContentAreaFilled(false);
instructions.setFocusPainted(false);
instructions.setOpaque(false);
instructions.setToolTipText("<html><center><font size=6>When this button shows purchase you can click it to go purchase the selected addon.<br /><br /> When it's showing Instructions you can click it to go see the manual for the selected addon.</font></center></html>");
// Deal with nothing selected when clciking this.
instructions.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int row = addonsTable.getSelectedRow();
String ad = "";
DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
if ( row == -1 ) { return; }
if ( row == 1 || row == 0 || row == 2 ) { ad = "Booster"; }
else {
ad = (String) tm.getValueAt(row,1);
ad = ad.replaceAll("\\s+", "");
}
boolean purchased = (Boolean) tm.getValueAt(row,3);
if (purchased) {
sendTo(ad, 1);
} else {
sendTo(ad,0);
}
}
});
addonsList.add(instructions);
// Constrain all items to the base panel
addonsListLO.putConstraint(SpringLayout.EAST, patchNotesPanel, -18, SpringLayout.EAST, addonsList);
addonsListLO.putConstraint(SpringLayout.NORTH, patchNotesPanel, 0, SpringLayout.NORTH, addonsList);
addonsListLO.putConstraint(SpringLayout.SOUTH, progressBarBackground, -20, SpringLayout.SOUTH, addonsList);
addonsListLO.putConstraint(SpringLayout.WEST, progressBarBackground, 100, SpringLayout.WEST, addonsList);
addonsListLO.putConstraint(SpringLayout.EAST, finishedButton, 0, SpringLayout.EAST, addonsList);
addonsListLO.putConstraint(SpringLayout.SOUTH, finishedButton, -20, SpringLayout.SOUTH, addonsList);
addonsListLO.putConstraint(SpringLayout.SOUTH, installButton, -10, SpringLayout.NORTH, progressBarBackground);
addonsListLO.putConstraint(SpringLayout.WEST, installButton, 190, SpringLayout.WEST, addonsList);
addonsListLO.putConstraint(SpringLayout.WEST, addonListPanel, 18, SpringLayout.WEST, addonsList);
addonsListLO.putConstraint(SpringLayout.NORTH, addonListPanel, 0, SpringLayout.NORTH, addonsList);
addonsListLO.putConstraint(SpringLayout.NORTH, instructions, -180, SpringLayout.SOUTH, addonsList);
addonsListLO.putConstraint(SpringLayout.WEST, instructions, 20, SpringLayout.WEST, addonsList);
}
/**
* This will update the table with info from the users database entry.
*
*/
public void updateTable() {
String totalIn = "";
String s = "";
String aName = "";
String aVersion = "";
String aFileSize = "";
String aInfo = "";
DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
sav.loadSave();
try {
URL serverURL = new URL(Updater.URL_CONNECT + "action=get_addons&email=" + sav.getSetting("UserName") + "&PHPSESSID=" + util.getPHPSessionID());
HttpURLConnection serverConnection = (HttpURLConnection) serverURL.openConnection();
serverConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(serverConnection.getInputStream()));
while (( totalIn = in.readLine()) != null) {
s += totalIn;
}
String[] splitOne = s.split("\\|-\\|");
for ( int a = 0; a < splitOne.length; a++) {
String[] splitTwo = splitOne[a].split("\\|");
String addonName = splitTwo[0];
for ( int b = 0; b < tm.getRowCount(); b++) {
if ( addonName.equals( (String) tm.getValueAt(b,1) ) ) { // b is the correct place to place the table info into addons[][]
tm.setValueAt(splitTwo[1],b,2);
tm.setValueAt(true,b,3);
double byteSize = Double.parseDouble(splitTwo[2]);
double kbyteSize = (byteSize/1024.0);
DecimalFormat dec = new DecimalFormat("00.00");
tm.setValueAt(dec.format(kbyteSize),b,4);
pNotes[b][0] = splitTwo[3];
}
}
}
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "Please send this entire error to support#dyanstyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 22", "Attention!",JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Please send this entire error to support#dynastyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 23" + e.getMessage(), "Attention!",JOptionPane.ERROR_MESSAGE);
}
checkLocalAddons();
}
/**
* This method checks the version numbers to see what what needs updating
* then updates the table to reflect this.
*
*/
private void needsUpdate() {
DynastyTableModel tm = (DynastyTableModel)addonsTable.getModel();
for ( int a = 0; a < tm.getRowCount(); a++) {
String ver = (String) tm.getValueAt(a,2).toString();
if(!ver.equals(localVersion[a][0])) {
boolean purch = (boolean) tm.getValueAt(a,3);
System.out.println("Set value at " + a + " 0 to: " + purch);
if(purch) {tm.setValueAt(true,a,0);}
}else{
tm.setValueAt(false,a,0);
}
}
checkUpdatesAvail();
}
/**
* This method will check if any of the udpate boxes are checked, and update the install button.
*
*
*/
private void checkUpdatesAvail() {
DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
boolean update = false;
for ( int a = 0; a < tm.getRowCount(); a++) {
boolean u = (Boolean) tm.getValueAt(a,0);
if (u) { update = u; }
}
if (update) {
setImageOnButton("instOn");
upAvail = true;
} else { finishedEverything(); }
}
/**
* This method handles what happens when you click the Install Updates button.
*
*/
private void updateNeededAddons() {
DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
boolean[] addUp = {false,false,false,false,false,false,false};
for (int a = 0; a < tm.getRowCount(); a++) {
boolean update = (Boolean) tm.getValueAt(a,0);
int getResult = 2;
if (update) {
addUp[a] = true;
try {
URL dlAddon = new URL(util.URL_CONNECT + "action=download&addon=" + tm.getValueAt(a,1) + "&email=" + sav.getSetting("UserName") + "&PHPSESSID=" + util.getPHPSessionID());
String fileName = tm.getValueAt(a,1) + ".zip";
String fileS = (String) tm.getValueAt(a,4);
double fileSize = Double.parseDouble(fileS);
getResult = getAddons(dlAddon, fileName, fileSize);
} catch(MalformedURLException e) {
JOptionPane.showMessageDialog(null, "We tried to create a query to download your addons, but got a malformedURLException. Please send this entire error to support#dyanstyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 31", "Attention!",JOptionPane.ERROR_MESSAGE);
}
if(getResult == 1) {
installAddon((String)tm.getValueAt(a,1));
}
}
}
}
/**
* This method will update the patch notes panel,
* it only allows updating from within this class.
*
* #param txt The new txt for the patch notes panel.
*
*/
private void setPatchNotes(String txt) {
patchNotes.setText(txt);
int prefSize = 370;
boolean width = true;
View view = (View) patchNotes.getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey);
view.setSize(width ? prefSize : 0, width ? 0 : prefSize);
float w = view.getPreferredSpan(View.X_AXIS);
float h = view.getPreferredSpan(View.Y_AXIS);
patchNotes.setPreferredSize(new Dimension((int) Math.ceil(w) - 17, (int) Math.ceil(h) + 100));
}
/**
* This will query the server for the updates to the addons
* that are needed and download them as needed.
*
*/
private int getAddons(URL url, String localFilename, double len) {
InputStream is = null;
FileOutputStream fos = null;
try {
URLConnection urlConn = url.openConnection();
HttpURLConnection resp = (HttpURLConnection) urlConn;
int responseCode = resp.getResponseCode();
is = urlConn.getInputStream();
fos = new FileOutputStream(System.getenv("SystemDrive") + "\\DynastyAddons\\" + localFilename);
byte[] buffer = new byte[4096];
int leng = (int) len;
while ((leng = is.read(buffer)) > 0) {
fos.write(buffer,0,leng);
}
is.close();
fos.close();
return 1;
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "We tried to download your addons, but got a malformedURLException. Please send this entire error to support#dyanstyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 32", "Attention!",JOptionPane.ERROR_MESSAGE);
return 2;
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "We tried to download your addons, but got an IOException. Please send this entire error to support#dynastyaddons.com. Also you can close the updater and re-open it and that sometimes removes this issue.\n Error # 33" + e, "Attention!",JOptionPane.ERROR_MESSAGE);
return 2;
}
}
/**
* This will update the finished button once all is done.
*
*/
private void finishedEverything() {
setImageOnButton("instOff");
setImageOnButton("finOn");
upAvail = false;
finishedAll = true;
}
public void setImageOnButton(String buttonName){
ImageIcon icon;
switch(buttonName) {
case "purchase": try {
System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/Purchase.png exists? " + new File("com/dynastyaddons/updater/Purchase.png").exists());
Image pic1 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/Purchase.png"));
icon = new ImageIcon(pic1);
instructions.setIcon(icon);
} catch (IOException e) { System.out.println("IO Exception setting icon to instructions: " + e.getMessage()); }
break;
case "instructions":try {
System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/instructions.png exists? " + new File("com/dynastyaddons/updater/instructions.png").exists());
Image pic2 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/instructions.png"));
icon = new ImageIcon(pic2);
instructions.setIcon(icon);
} catch (IOException e) { System.out.println("IO Exception setting icon to instructions2: " + e.getMessage()); }
break;
case "finOn": try {
System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/FinishedOn.png exists? " + new File("com/dynastyaddons/updater/FinishedOn.png").exists());
Image pic3 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/FinishedOn.png"));
icon = new ImageIcon(pic3);
finishedButton.setIcon(icon);
} catch (IOException e) { System.out.println("IO Exception setting icon to finished: " + e.getMessage()); }
break;
case "finOff": try {
System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/FinishedOff.png exists? " + new File("com/dynastyaddons/updater/FinishedOff.png").exists());
Image pic4 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/FinishedOff.png"));
icon = new ImageIcon(pic4);
finishedButton.setIcon(icon);
} catch (IOException e) { System.out.println("IO Exception setting icon to finished2: " + e.getMessage()); }
break;
case "instOn": try {
System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/InstallUpdatesON.png exists? " + new File("com/dynastyaddons/updater/InstallUpdatesON.png").exists());
Image pic5 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/InstallUpdatesON.png"));
icon = new ImageIcon(pic5);
installButton.setIcon(icon);
} catch (IOException e) { System.out.println("IO Exception setting icon to install: " + e.getMessage()); }
break;
case "instOff": try {
System.out.println("Trying to setIcon on Instructions Button. File: com/dynastyaddons/updater/InstallUpdatesOFF.png exists? " + new File("com/dynastyaddons/updater/InstallUpdatesOFF.png").exists());
Image pic6 = ImageIO.read(Addons.class.getClassLoader().getResourceAsStream("com/dynastyaddons/updater/InstallUpdatesOFF.png"));
icon = new ImageIcon(pic6);
installButton.setIcon(icon);
} catch (IOException e) { System.out.println("IO Exception setting icon to install2: " + e.getMessage()); }
break;
}
}
// This internal class will handle the modle for the table used to show the addon list.
class DynastyTableModel extends AbstractTableModel {
private String[] columnNames = {"Update",
"Name",
"Version",
"Purchase",
"Size"};
private Object[][] initialData = {
{new Boolean(false), "Booster", new Double(1.0), new Boolean(false), new Double(0)},
{new Boolean(false), "BoosterAlliance", new Double(1.0), new Boolean(false), new Double(0)},
{new Boolean(false), "BoosterHorde", new Double(1.0), new Boolean(false), new Double(0)},
{new Boolean(false), "Edge", new Double(1.0), new Boolean(false), new Double(0)},
{new Boolean(false), "Impulse", new Double(1.0), new Boolean(false), new Double(0)},
{new Boolean(false), "Tycoon", new Double(1.0), new Boolean(false), new Double(0)},
{new Boolean(false), "DynastyCore", new Double(1.0), new Boolean(false), new Double(0)},
};
public int getColumnCount() { return columnNames.length; }
public int getRowCount() { return initialData.length; }
public String getColumnName(int col) { return columnNames[col]; }
public Object getValueAt(int row, int col) { return initialData[row][col]; }
public Class getColumnClass(int c) { return getValueAt(0,c).getClass(); }
#Override
public void setValueAt(Object value, int row, int col) {
initialData[row][col] = value;
fireTableCellUpdated(row, col);
}
}
// This internal class will help handle when a row is selected in the table.
class SharedListSelectionHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if ( !e.getValueIsAdjusting() ) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int selected = lsm.getMinSelectionIndex();
// if purchased addon display patch notes
DynastyTableModel tm = (DynastyTableModel) addonsTable.getModel();
boolean selectedValue = (Boolean) tm.getValueAt(selected,3);
if ( selectedValue ) {
setPatchNotes(pNotes[selected][0]);
setImageOnButton("instructions");
}
else { // Otherwise update Install Instructions button to show Purchase instead.
// save currently selected addon name for use in the purchase button?
String p = "";
if (selected == 1 || selected == 2) {
p = "Booster";
} else { p = (String) tm.getValueAt(selected,1); }
setPatchNotes("<HTML>You have not purchased this addon, please go to http://dynastyaddons.com/" + p + " or click the Purchase button below the list of addons here to open the purchase page.</HTML>");
setImageOnButton("purchase");
}
}
}
}
}
As you see from the above code, the createGUI where I create the buttons using getResource() etc works fine, it's the setImagesOnButton() method at the bottom that's giving me fits.
I tried also to include the places where the method is called to make it more clear. Also the println's in the setImagesOnButton all print out that the file is found and exists, then in the next line a NullPointerException comes up saying it doesn't exist? Confusing to me.
OK, I figured out what was going on. Three things to fix this. First of all, I realized that the null problem was not the icon I was trying to put on the button, it was a misplaced JButton call at the top in the CreateGUI method. I removed that (since I had it already created in the constructor) and that went away. Second I got rid of the stupd method cause it kept confusing me. (the setImageOnButton) and finally I found that if I put the images directory in the root of the package, then called for the images using new ImageIcon(Image.read(getClass().getClassLoader().getResourceAsStream("images/imagename.png"))); I could find it since I was relating it to the package rather than the class, it worked like a charm! I compiled, jarred it up and tested on my wifes' computer and it worked perfect! Thank you all for the help, Couldn't have done it without all the great info! and to say the least, I completely understand resources and how to put them in an application and use them now. :)
Related
Java External JAR Doesn't Seem To Be Working
Using Eclipse, Mslink.jar (creates shortcuts), Java 1.8.0 The coding that fails. The JOptionPane never appears when I export this out to a .JAR public static void main(String[] args) { // create an empty combo box with items of type String JComboBox<String> systems = new JComboBox<String>(); // add items to the combo box systems.addItem("System1"); systems.addItem("System2"); systems.addItem("System5"); systems.addItem("System6"); systems.addItem("System7"); systems.addItem("System9"); systems.addItem("System10"); systems.addItem("System12"); systems.addItem("System14"); systems.addItem("System15"); systems.addItem("System16"); systems.addItem("System17"); systems.addItem("System18"); systems.addItem("System19"); systems.addItem("System20"); systems.addItem("System21"); systems.addItem("System22"); systems.addItem("System24"); systems.addItem("System30"); systems.addItem("System34"); systems.addItem("All Systems Install"); systems.setEditable(true); JPanel steps = new JPanel(); JPanel firstStep = new JPanel(); JPanel secondStep = new JPanel(); frame.setSize(1200, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setLayout(new GridLayout(3, 1)); frame.add(steps); frame.add(firstStep); frame.add(secondStep); Button go = new Button("Go"); Button go2 = new Button("Go"); Label stepInstruction = new Label( "Please do each step in order to complete the process. First step requires you install Universal desktop for your system." + " Second step requires your username to find Universal desktop install"); Label instruction = new Label("Step 1: Please select a system to download from"); Label instruction2 = new Label("Step 2: Press Go when Universal Desktop is Installed"); // Steps Explained steps.add(stepInstruction); // First Step firstStep.add(instruction); firstStep.add(systems); firstStep.add(go); // Second Step secondStep.add(instruction2); secondStep.add(go2); go.addActionListener(new ActionListener() { #Override public void actionPerformed(ActionEvent event) { String selectedSystem = (String) systems.getSelectedItem(); System.out.println(selectedSystem); try { if (!selectedSystem.equalsIgnoreCase("All Systems Install")) { // Open UD install page in Internet explorer Runtime.getRuntime().exec("C:\\Program Files\\Internet Explorer\\iexplore.exe " + "https://" + selectedSystem + ".pos.infogenesisasp.com/infogenesis/install/universaldesktop/UniversalDesktop.application"); // Runtime.getRuntime().exec("C:\\Program Files\\Internet Explorer\\iexplore.exe // " // + "https://" + selectedSystem + // ".pos.infogenesisasp.com/infogenesis/install/universaldesktop/"); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(frame, e); } frame.validate(); } }); go2.addActionListener(new ActionListener() { #Override public void actionPerformed(ActionEvent event) { String selectedSystem = (String) systems.getSelectedItem(); String Username = System.getProperty("user.name"); if (selectedSystem.equalsIgnoreCase("All Systems Install")) { String[] systems = { "System1", "System2", "System5", "System6", "System7", "System9", "System10", "System12", "System14", "System15", "System16", "System17", "System18", "System19", "System20", "System21", "System22", "System24", "System30", "System34" }; for (int count = 0; count < systems.length; count++) { try { // Need to figure out a way to ensure the person installs UD before we can // proceed Runtime.getRuntime().exec("C:\\Program Files\\Internet Explorer\\iexplore.exe " + "https://" + systems[count] + ".pos.infogenesisasp.com/infogenesis/install/universaldesktop/UniversalDesktop.application"); count = systems.length; } catch (IOException e) { JOptionPane.showMessageDialog(frame, e); e.printStackTrace(); } } } else { // Single System installer Installer(Username, selectedSystem); JOptionPane.showMessageDialog(frame, "Installion Completed!"); } } }); } import mslinks.ShellLink; public static void createShortcut(String folder, String system) throws IOException { ShellLink.createLink(folder, system); JOptionPane.showMessageDialog(frame, "Created Shortcut!"); } File system: This code works fine in Eclipse, but exporting to a JAR causes it to fail. Is there something missing preventing the Referenced Libaries Mslinks.jar from loading? I've tried everything in Eclipse's export
An UI that slides through images
I am trying to change what image is shown in the JLabels of my User Interfaces. The following class is a very simple test of the concept. The UI takes a folder full of images (the field imageFolderPath) and displays the first image, resized, in the only JLabel; clicking on the image prompts the UI to display the following image in the folder. At least, it should. In reality, no image is shown. The fault is obviously of the method reloadImage(), either while rescaling the image or while repainting the JLabel, but I have not managed to find or correct the problem. Any idea? public class Test extends JFrame { private JPanel contentPane; private JLabel boardImage; private ImageIcon icon; public String imageFolderPath = "C:\\modify\\it\\to\\suit\\your\\needs\\"; public File[] files; public int indexImage = 0; public int imageResolution = 450; // ========================================================= // TODO | Constructors /** * Create the frame. */ public Test() { if( !new File(imageFolderPath).exists() ) new File(imageFolderPath).mkdir(); this.files = new File(imageFolderPath).listFiles(); System.out.println("Can show:"); for( File file : files ) System.out.println("\t"+file.getName()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, imageResolution, imageResolution); contentPane = new JPanel(); contentPane.addMouseListener(new MouseAdapter() { #Override public void mouseClicked(MouseEvent arg0) { // Every time the image is clicked, another one is shown indexImage++; reloadImage(); } }); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); boardImage = new JLabel(); boardImage.setBounds(0, 0, imageResolution, imageResolution); reloadImage(); contentPane.add(boardImage); } // ========================================================= // TODO | Support methods /** Reloads the image of the {#link ChessBoard} at its current state. */ public void reloadImage() { if( files[indexImage % files.length].exists() ) System.out.println("The file " + files[indexImage % files.length].getName() + " exists"); else System.out.println("The file " + files[indexImage % files.length].getName() + " doesnt exists"); // Reload the image - resized BufferedImage buffer = null; try { buffer = ImageIO.read( files[indexImage % files.length] ); } catch (IOException e) { e.printStackTrace(); } Image rescaledImage = buffer.getScaledInstance(imageResolution, imageResolution, Image.SCALE_SMOOTH); icon = new ImageIcon(rescaledImage); boardImage = new JLabel(icon); // boardImage.setText( files[indexImage % files.length].getName() ); System.out.println("Is now showing " + files[indexImage % files.length].getName() ); boardImage.repaint(); } /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Test frame = new Test(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }
In reality, no image is shown. boardImage = new JLabel(icon); Don't create a new JLabel. The instance of that JLabel hasn't been added to the frame. Instead just change the Icon of the existing JLabel: //boardImage = new JLabel(icon); boardImage.setIcon( icon ); The label will automatically repaint itself with the new Icon.
Java applet play multiple .wav files
Hello I am trying to create a simple game, and right now I am trying to add a couple songs to play in the background during the game, which can be stopped and skipped as the player wishes. It seems everywhere I look I can't seem to make the example code work. and the only example that does work can only play one file either in a loop or not. public void loadmedia () { song1 = getAudioClip (getCodeBase (), "song1.au"); song1.play (); song2 = getAudioClip (getCodeBase (), "song2.au"); song2.play (); } song1 will play normally but song2 will do nothing, even if I tell song 1 to stop with a button and play song2.
When you need change your background song? Or after song 1 finished, song 2 start? Sorry I can add it as a comment because my reputation < 50 This code for you to choose a couple of songs in a combobox. Give it a try. If it is not suitable for you. Give me the question again :) Hope you like it! import java.applet.AudioClip; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.URL; import java.net.MalformedURLException; import java.awt.GridBagLayout; public class SoundApplication extends JPanel implements ActionListener, ItemListener { SoundList soundList; String auFile = "spacemusic.au"; String aiffFile = "flute+hrn+mrmba.aif"; String midiFile = "trippygaia1.mid"; String rmfFile = "jungle.rmf"; String wavFile = "bottle-open.wav"; String chosenFile; AudioClip onceClip, loopClip; URL codeBase; JComboBox formats; JButton playButton, loopButton, stopButton; JLabel status; boolean looping = false; public SoundApplication() { String [] fileTypes = {auFile, aiffFile, midiFile, rmfFile, wavFile}; formats = new JComboBox(fileTypes); formats.setSelectedIndex(0); chosenFile = (String)formats.getSelectedItem(); formats.addItemListener(this); playButton = new JButton("Play"); playButton.addActionListener(this); loopButton = new JButton("Loop"); loopButton.addActionListener(this); stopButton = new JButton("Stop"); stopButton.addActionListener(this); stopButton.setEnabled(false); status = new JLabel( "Click Play or Loop to play the selected sound file."); JPanel controlPanel = new JPanel(); controlPanel.add(formats); controlPanel.add(playButton); controlPanel.add(loopButton); controlPanel.add(stopButton); JPanel statusPanel = new JPanel(); statusPanel.add(status); add(controlPanel); add(statusPanel); startLoadingSounds(); } public void itemStateChanged(ItemEvent e){ chosenFile = (String)formats.getSelectedItem(); soundList.startLoading(chosenFile); } void startLoadingSounds() { //Start asynchronous sound loading. try { codeBase = new URL("file:" + System.getProperty("user.dir") + "/"); } catch (MalformedURLException e) { System.err.println(e.getMessage()); } soundList = new SoundList(codeBase); soundList.startLoading(auFile); soundList.startLoading(aiffFile); soundList.startLoading(midiFile); soundList.startLoading(rmfFile); soundList.startLoading(wavFile); } public void stop() { onceClip.stop(); //Cut short the one-time sound. if (looping) { loopClip.stop(); //Stop the sound loop. } } public void start() { if (looping) { loopClip.loop(); //Restart the sound loop. } } public void actionPerformed(ActionEvent event) { //PLAY BUTTON Object source = event.getSource(); if (source == playButton) { //Try to get the AudioClip. onceClip = soundList.getClip(chosenFile); stopButton.setEnabled(true); onceClip.play(); //Play it once. status.setText("Playing sound " + chosenFile + "."); if (onceClip == null) { status.setText("Sound " + chosenFile + " not loaded yet."); } return; } //START LOOP BUTTON if (source == loopButton) { loopClip = soundList.getClip(chosenFile); looping = true; loopClip.loop(); //Start the sound loop. loopButton.setEnabled(false); //Disable start button. stopButton.setEnabled(true); status.setText("Playing sound " + chosenFile + " continuously."); if (loopClip == null) { status.setText("Sound " + chosenFile + " not loaded yet."); } return; } //STOP LOOP BUTTON if (source == stopButton) { if (looping) { looping = false; loopClip.stop(); //Stop the sound loop. loopButton.setEnabled(true); //Enable start button. } else if (onceClip != null) { onceClip.stop(); } stopButton.setEnabled(false); status.setText("Stopped playing " + chosenFile + "."); return; } } public static void main(String s[]) { WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }; JFrame f = new JFrame("SoundApplication"); f.addWindowListener(l); f.getContentPane().add(new SoundApplication()); f.setSize(new Dimension(400,100)); f.show(); } }
I found a working answer, thanks a lot for all those who tried to help me out, i ended up using Audio Stream and Input stream. defining my input stream: private AudioStream as; method called to change songs, when the app starts, and when the next song button is pressed public void musicconfig () { try { if (mutestate == false) { AudioPlayer.player.stop (as); InputStream in = new FileInputStream (filename [count]); as = new AudioStream (in); AudioPlayer.player.start (as); } } catch (IOException b) { b.printStackTrace (); } count++; if (count == 12) { count = 1; } } setup my song list array when app first runs public void mediaload () { filename [1] = "song1.wav"; filename [2] = "song2.wav"; filename [3] = "song3.wav"; filename [4] = "song4.wav"; filename [5] = "song5.wav"; filename [6] = "song6.wav"; filename [7] = "song7.wav"; filename [8] = "song8.wav"; filename [9] = "song9.wav"; filename [10] = "song10.wav"; filename [11] = "song11.wav"; }
Java SWT Button Image Not Refreshing
I am displaying an image in a button and when the button is clicked it opens a composite that allows me to select another picture to use for the button. Upon the save action the the code below resizes the picture and saves it to a directory. Then it loads the reloads the composite. When the composite loads the button pulls its image from a default location based on the id of the record the user is viewing. The problem I am having is that the image on the button remains the same unless I close and reload the application. An interesting thing to note is that when the default button image is loaded (i.e. there is no picture saved for its id) the button image changes as it should but only the first time. Hope I have described my problem clear enough if you need me to clarify please comment. --- Code For Save Button -- Button btnSave = new Button(this, SWT.NONE); btnSave.addSelectionListener(new SelectionAdapter() { #Override public void widgetSelected(SelectionEvent e) { String path = txtPhotoPath.getText(); if (CC_Files.fileExists(path)) { ArrayList<String> picTypes = new ArrayList<String>(); picTypes.add(".jpg"); picTypes.add(".png"); picTypes.add(".gif"); int t = 0; for(int i = 0; i < picTypes.size(); i++){ String s = picTypes.get(i); if(path.contains(s.toUpperCase())){ t++; } if(path.contains(s.toLowerCase())){ t++; } } if (t > 0) { Image image = (Image) SWTResourceManager.getImage(path); ImageData imgData = image.getImageData(); int intH = image.getBounds().height; int intW = image.getBounds().width; int h = (150 * intH) / intW; int w = 150; if (h > 150){ h = 150; w = (150 * intW) / intH; } imgData = imgData.scaledTo(w, h); ImageLoader imageLoader = new ImageLoader(); imageLoader.data = new ImageData[] { imgData }; imageLoader.save(Variables.getStrResources() + "Pics\\" + a.getHerd_id() + ".jpg", SWT.IMAGE_JPEG); try { Frm_Animal.setAnimalEditSC(Frm_Animal .createAnimalComp(a)); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } }); GridData gd_btnSave = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnSave.widthHint = 60; btnSave.setLayoutData(gd_btnSave); btnSave.setText("Save"); ---Code That Creates Button In Composite--- Button btnPic = new Button(composite, SWT.CENTER); btnPic.addSelectionListener(new SelectionAdapter() { #Override public void widgetSelected(SelectionEvent e) { try { Comp_Add_Photo photo = new Comp_Add_Photo( scrolledComposite, SWT.FILL, a); setAnimalEditSC(photo); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); Image image = null; String strPic = Variables.getStrResources() + "Pics\\" + a.getHerd_id() +".jpg"; if(CC_Files.fileExists(strPic)){ image = (Image) SWTResourceManager .getImage(strPic); }else { image = (Image) SWTResourceManager .getImage(Variables.getStrResources() + "black_cow.png"); } btnPic.setImage(image); btnPic.setToolTipText("Click Here To Add Photo"); GridData gd_btnPic = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 7); gd_btnPic.heightHint = 160; gd_btnPic.widthHint = 160; btnPic.setLayoutData(gd_btnPic);
I think it is probably because you are using SWTResourceManager and it must have a cache of some kind. Since the path of the image remains same so it returns the older image. Which API does SWTResourceManager belong to? Can it dispose a single image before you reload the new image? Perhaps call something like SWTResourceManager#dipose(). I am hoping there would be some way to just clear the cache for specific images.
Wrap Extended Frame View in a Window
I have an assignment from my university to continue a JAVA card project from the students from last semester, which happens to be sucked. Because we have to carry on with someones work instead ours.. So my first step is to make an window image icon and tray icon for the application`s window. The thing is, this code below is based on extended FrameView instead of JWindow. My idea is to wrap the extended FrameView up into a Window. Can someone help me with that? Thanks much I would appreciate that. CODE: public class DesktopApplication1View extends FrameView implements IProgressDialogObserver { //============================================================ // Fields // =========================================================== private Connection connection = new Connection(); private ProgressDialogUpdater pbu = ProgressDialogUpdater.getInstance(); private Vector<CourseFromCard> courseListFromCard = new Vector<CourseFromCard>(); private Vector<School> schoolList = new Vector<School>(); private Vector<CourseFromFile> courseList = new Vector<CourseFromFile>(); private int cardReaderRefreshHelper = 0; private Student student = null; JLabel jLabelBilkaImage = null; final String ICON = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_32.png"; final String PIC = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_128.png"; private JLabel getJLabelBilkaImage() { if (jLabelBilkaImage == null) { Icon image = new ImageIcon(PIC); jLabelBilkaImage = new JLabel(image); jLabelBilkaImage.setName("jLabelBilkaImage"); } return jLabelBilkaImage; } //============================================================ // Constructors // =========================================================== public DesktopApplication1View(SingleFrameApplication app) { super(app); pbu.registriere(this); app.getMainFrame().setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png")); initComponents(); refreshConnectionState(); readFilesFromLocalHDD(); ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String) (evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer) (evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); } .........
SingleFrameApplication provides the method getMainFrame(), which returns the JFrame used to display a particular view. The code you listed in your question is one such view. If you need to operate on the frame, it's probably better to do it in code subclassing SingleFrameApplication than the code you posted. There's a tutorial on using the Swing Application Framework, which might provide more help.