An UI that slides through images - java

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.

Related

How to change default style of Java Swing application in NetBeans?

There are few styles in the preview mode but can't find where I can set the preferred design. Is there any option?
Check screen
Examples:
Programmatically:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
Command line:
java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp
You can find more info about this on the Oracle docs.
A complete demo (from the docs):
public class LookAndFeelDemo implements ActionListener {
private static String labelPrefix = "Number of button clicks: ";
private int numClicks = 0;
final JLabel label = new JLabel(labelPrefix + "0 ");
// Specify the look and feel to use by defining the LOOKANDFEEL constant
// Valid values are: null (use the default), "Metal", "System", "Motif",
// and "GTK"
final static String LOOKANDFEEL = "Metal";
// If you choose the Metal L&F, you can also choose a theme.
// Specify the theme to use by defining the THEME constant
// Valid values are: "DefaultMetal", "Ocean", and "Test"
final static String THEME = "Test";
public Component createComponents() {
JButton button = new JButton("I'm a Swing button!");
button.setMnemonic(KeyEvent.VK_I);
button.addActionListener(this);
label.setLabelFor(button);
JPanel pane = new JPanel(new GridLayout(0, 1));
pane.add(button);
pane.add(label);
pane.setBorder(BorderFactory.createEmptyBorder(
30, //top
30, //left
10, //bottom
30) //right
);
return pane;
}
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText(labelPrefix + numClicks);
}
private static void initLookAndFeel() {
String lookAndFeel = null;
if (LOOKANDFEEL != null) {
if (LOOKANDFEEL.equals("Metal")) {
lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
// an alternative way to set the Metal L&F is to replace the
// previous line with:
// lookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel";
}
else if (LOOKANDFEEL.equals("System")) {
lookAndFeel = UIManager.getSystemLookAndFeelClassName();
}
else if (LOOKANDFEEL.equals("Motif")) {
lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
}
else if (LOOKANDFEEL.equals("GTK")) {
lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
}
else {
System.err.println("Unexpected value of LOOKANDFEEL specified: "
+ LOOKANDFEEL);
lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
}
try {
UIManager.setLookAndFeel(lookAndFeel);
// If L&F = "Metal", set the theme
if (LOOKANDFEEL.equals("Metal")) {
if (THEME.equals("DefaultMetal"))
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
else if (THEME.equals("Ocean"))
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
else
MetalLookAndFeel.setCurrentTheme(new TestTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
}
}
catch (ClassNotFoundException e) {
System.err.println("Couldn't find class for specified look and feel:"
+ lookAndFeel);
System.err.println("Did you include the library in the class path?");
System.err.println("Using the default look and feel.");
}
catch (UnsupportedLookAndFeelException e) {
System.err.println("Can't use the specified look and feel ("
+ lookAndFeel
+ ") on this platform.");
System.err.println("Using the default look and feel.");
}
catch (Exception e) {
System.err.println("Couldn't get specified look and feel ("
+ lookAndFeel
+ "), for some reason.");
System.err.println("Using the default look and feel.");
e.printStackTrace();
}
}
}
private static void createAndShowGUI() {
//Set the look and feel.
initLookAndFeel();
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("SwingApplication");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LookAndFeelDemo app = new LookAndFeelDemo();
Component contents = app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

JButton.setIcon throws null pointer when file exists

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. :)

uk.co.mmscomputing twain scanner

I am using this mmscomputing library as java applet to scan an image or document.
Using swings,awt i created one scan button which is acquiring scanner by calling scanner.acquire() method of mmscomputing jar..
and then placing that scanned image into jpanel for displaying.
Problem is, first time when i start my applet and hitting my scan button..scanning works fine..Twain states it goes into are: 3,4,5,6,7,5,4,3
then second time,hitting my scan button again ..
Twain states it goes into are: 3,4,5,4,3
It's not going into image transfer ready and transferring state and thus not into below CODE IF loop
if (type.equals(ScannerIOMetadata.ACQUIRED))
so i am not able to see the new scanned image into my jpanel second time...
then third time, hitting my scan button .. again it works fine.. getting into all states.
So i mean, For alternatively turns or restarting the java applet again ..it works.
what would be the issue.. ?
I want, every time when i hit scan button it should get me a new image into Jpanel.. but it's doing alternative times.
can i forcefully explicitly set or change twain states to come into 6th and 7th states..
or is there some twain source initialisation problem occurs second time?
because restarting applet is doing fine every time.. or some way to reinitialise applet objects everytime on clicking scan button..as it would feel like I am restarting applet everytime on clicking scan button...
I am not getting it..
Below is the sample code:
import uk.co.mmscomputing.device.twain.TwainConstants;
import uk.co.mmscomputing.device.twain.TwainIOMetadata;
import uk.co.mmscomputing.device.twain.TwainSource;
import uk.co.mmscomputing.device.twain.TwainSourceManager;
public class XXCrop extends JApplet implements PlugIn, ScannerListener
{
private JToolBar jtoolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
ImagePanel ipanel;
Image im =null;
BufferedImage imageforCrop;
ImagePlus imp=null;
int imageWidth;
int imageHeight;
private static final long serialVersionUID = 1L;
Container content = null;
private JPanel jContentPane = null;
private JButton jButton = null;
private JButton jButton1 = null;
JCheckBox clipBox = null;
JPanel crpdpanel=null;
JPanel cpanel=null;
private Scanner scanner=null;
private TwainSource ts ;
private boolean is20;
ImagePanel imagePanel,imagePanel2 ;
public static void main(String[] args) {
new XXCrop().setVisible(true);
}
public void run(String arg0) {
new XXCrop().setVisible(false);
repaint();
}
/**
* This is the default constructor
*/
public XXCrop() {
super();
init();
try {
scanner = Scanner.getDevice();
if(scanner!=null)
{
scanner.addListener(this);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* This method initializes this
*
* #return void
*/
public void init()
{
this.setSize(1200, 600);
this.setLayout(null);
//this.revalidate();
this.setContentPane(getJContentPane());
}
private JToolBar getJToolBar()
{
jtoolbar.add(getJButton1());
jtoolbar.add(getJButton());
jtoolbar.setName("My Toolbar");
jtoolbar.addSeparator();
Rectangle r=new Rectangle(0, 0,1024, 30 );
jtoolbar.setBounds(r);
return jtoolbar;
}
private JPanel getJContentPane()
{
if (jContentPane == null)
{
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToolBar());
}
return jContentPane;
}
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(new Rectangle(4, 16, 131, 42));
jButton.setText("Select Device");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (scanner.isBusy() == false) {
selectDevice();
}
}
});
}
return jButton;
}
/* Select the twain source! */
public void selectDevice() {
try {
scanner.select();
} catch (ScannerIOException e1) {
IJ.error(e1.toString());
}
}
private JButton getJButton1()
{
if (jButton1 == null) {
jButton1 = new JButton();
jButton1.setBounds(new Rectangle(35,0, 30, 30));
jButton1.setText("Scan");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e)
{//jContentPane.remove(crpdpanel);
//jContentPane.removeAll();
//jContentPane.repaint();
//jContentPane.revalidate();
getScan();
}
});
}
return jButton1;
}
public void getScan()
{
try
{
//scanner = Scanner.getDevice();
//scanner.addListener(this);
scanner.acquire();
}
catch (ScannerIOException e1)
{
IJ.showMessage("Access denied! \nTwain dialog maybe already opened!");
e1.printStackTrace();
}
}
public Image getImage()
{
Image image = imp.getImage();
return image;
}
/*Image cimg;
public Image getCimg()
{
return cimg;
}*/
public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata) {
if (type.equals(ScannerIOMetadata.ACQUIRED))
{
//imagePanel.revalidate();
//imagePanel.repaint();
//imagePanel.invalidate();
//jContentPane.remove(ipanel);
//ipanel.repaint();
if(imp!=null)
{
jContentPane.remove(ipanel);
jContentPane.remove(cpanel);
jContentPane.remove(crpdpanel);
}
imp = new ImagePlus("Scan", metadata.getImage());
//imp.show();
im = imp.getImage();
//imagePanel = new ImagePanel(im,imageWidth,imageHeight);
imagePanel = new ImagePanel(im);
imagePanel.updateUI();
imagePanel.repaint();
imagePanel.revalidate();
ClipMover mover = new ClipMover(imagePanel);
imagePanel.addMouseListener(mover);
imagePanel.addMouseMotionListener(mover);
ipanel = imagePanel.getPanel();
ipanel.setBorder(new LineBorder(Color.blue,1));
ipanel.setBorder(BorderFactory.createTitledBorder("Scanned Image"));
ipanel.setBounds(0, 30,600, 600);
ipanel.repaint();
ipanel.revalidate();
ipanel.updateUI();
jContentPane.add(ipanel);
jContentPane.getRootPane().revalidate();
jContentPane.updateUI();
//jContentPane.repaint();
// cimg=imagePanel.getCimg();
// ImagePanel cpanel = (ImagePanel) imagePanel.getUIPanel();
/*
cpanel.setBounds(700, 30,600, 800);
jContentPane.add(imagePanel.getUIPanel());
*/
cpanel = imagePanel.getUIPanel();
cpanel.setBounds(700, 30,300, 150);
cpanel.repaint();
cpanel.setBorder(new LineBorder(Color.blue,1));
cpanel.setBorder(BorderFactory.createTitledBorder("Cropping Image"));
jContentPane.add(cpanel);
jContentPane.repaint();
jContentPane.revalidate();
metadata.setImage(null);
try {
new uk.co.mmscomputing.concurrent.Semaphore(0, true).tryAcquire(2000, null);
} catch (InterruptedException e) {
IJ.error(e.getMessage());
}
}
else if (type.equals(ScannerIOMetadata.NEGOTIATE)) {
ScannerDevice device = metadata.getDevice();
try {
device.setResolution(100);
} catch (ScannerIOException e) {
IJ.error(e.getMessage());
}
try{
device.setShowUserInterface(false);
// device.setShowProgressBar(true);
// device.setRegionOfInterest(0,0,210.0,300.0);
device.setResolution(100); }catch(Exception e){
e.printStackTrace(); }
}
else if (type.equals(ScannerIOMetadata.STATECHANGE)) {
System.out.println("Scanner State "+metadata.getStateStr());
System.out.println("Scanner State "+metadata.getState());
//switch (metadata.ACQUIRED){};
ts = ((TwainIOMetadata)metadata).getSource();
//ts.setCancel(false);
//ts.getState()
//TwainConstants.STATE_TRANSFERREADY
((TwainIOMetadata)metadata).setState(6);
if ((metadata.getLastState() == 3) && (metadata.getState() == 4)){}
// IJ.error(metadata.getStateStr());
}
else if (type.equals(ScannerIOMetadata.EXCEPTION)) {
IJ.error(metadata.getException().toString());
}
}
public void stop(){ // execute before System.exit
if(scanner!=null){ // make sure user waits for scanner to finish!
scanner.waitToExit();
ts.setCancel(true);
try {
scanner.setCancel(true);
} catch (ScannerIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm not an expert, but when ScannerIOMetadata.STATECHANGE shouldn't you check if the scanning is complete?
And if it is you should initialize the scanner again.
Something like that:
if (metadata.isFinished())
{
twainScanner = (TwainScanner) Scanner.getDevice();
}

Updating an image contained in a JLabel - problems

The part of the application that I am currently having trouble getting to work is being able to scroll through and display a list of images, one at a time. I'm getting a directory from the user, spooling through all of the files in that directory, and then loading an array of just the jpegs and pngs. Next, I want to update a JLabel with the first image, and provide previous and next buttons to scroll through and display each image in turn. When I try to display the second image, it doesn't get updated... Here's what I've got so far:
public class CreateGallery
{
private JLabel swingImage;
The method that I'm using to update the image:
protected void updateImage(String name)
{
BufferedImage image = null;
Image scaledImage = null;
JLabel tempImage;
try
{
image = ImageIO.read(new File(name));
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// getScaledImage returns an Image that's been resized proportionally to my thumbnail constraints
scaledImage = getScaledImage(image, THUMB_SIZE_X, THUMB_SIZE_Y);
tempImage = new JLabel(new ImageIcon(scaledImage));
swingImage = tempImage;
}
Then in my createAndShowGUI method that puts the swingImage on...
private void createAndShowGUI()
{
//Create and set up the window.
final JFrame frame = new JFrame();
// Miscellaneous code in here - removed for brevity
// Create the Image Thumbnail swingImage and start up with a default image
swingImage = new JLabel();
String rootPath = new java.io.File("").getAbsolutePath();
updateImage(rootPath + "/images/default.jpg");
// Miscellaneous code in here - removed for brevity
rightPane.add(swingImage, BorderLayout.PAGE_START);
frame.add(rightPane, BorderLayout.LINE_END);
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
UIManager.put("swing.boldMetal", Boolean.FALSE);
new CreateGalleryXML().createAndShowGUI();
}
});
}
If you've gotten this far, the first image is my default.jpg, and once I get the directory and identify the first image in that directory, that's where it fails when I try to update the swingImage. Now, I've tried to swingImage.setVisible() and swingImage.revalidate() to try to force it to reload. I'm guessing it's my tempImage = new JLabel that's the root cause. But I'm not sure how to convert my BufferedImage or Image to a JLabel in order to just update swingImage.
Instead of creating a New Instance of the JLabel for each Image, simply use JLabel#setIcon(...) method of the JLabel to change the image.
A small sample program :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SlideShow extends JPanel
{
private int i = 0;
private Timer timer;
private JLabel images = new JLabel();
private Icon[] icons = {UIManager.getIcon("OptionPane.informationIcon"),
UIManager.getIcon("OptionPane.errorIcon"),
UIManager.getIcon("OptionPane.warningIcon")};
private ImageIcon pictures1, pictures2, pictures3, pictures4;
private ActionListener action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
i++;
System.out.println(i);
if(i == 1)
{
pictures1 = new ImageIcon("image/caIcon.png");
images.setIcon(icons[i - 1]);
System.out.println("picture 1 should be displayed here");
}
if(i == 2)
{
pictures2 = new ImageIcon("image/Keyboard.png");
images.setIcon(icons[i - 1]);
System.out.println("picture 2 should be displayed here");
}
if(i == 3)
{
pictures3 = new ImageIcon("image/ukIcon.png");
images.setIcon(icons[i - 1]);
System.out.println("picture 3 should be displayed here");
}
if(i == 4)
{
pictures4 = new ImageIcon("image/Mouse.png");
images.setIcon(icons[0]);
System.out.println("picture 4 should be displayed here");
}
if(i == 5)
{
timer.stop();
System.exit(0);
}
revalidate();
repaint();
}
};
public SlideShow()
{
JFrame frame = new JFrame("SLIDE SHOW");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.getContentPane().add(this);
add(images);
frame.setSize(300, 300);
frame.setVisible(true);
timer = new Timer(2000, action);
timer.start();
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SlideShow();
}
});
}
}
Since you doing it with ImageIO, here is a good example related to that JLabel using ImageIO
Information relating to your case, as to what is happening :
Inside your createAndShowGUI() method you initializing your JLabel (swingImage), and you added that to your JPanel by virtue of which indirectly to the JFrame.
But now inside your updateImage() method, you are initializing a new JLabel, now it resides in some another memory location, by writing tempImage = new JLabel(new ImageIcon(scaledImage)); and after this you pointing your swingImage(JLabel) to point to this newly created JLabel, but this newly created JLabel was never added to the JPanel, at any point. Hence it will not be visible, even if you try revalidate()/repaint()/setVisible(...). Hence either you change the code for your updateImage(...) method to this :
protected void updateImage(String name)
{
BufferedImage image = null;
Image scaledImage = null;
JLabel tempImage;
try
{
image = ImageIO.read(new File(name));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// getScaledImage returns an Image that's been resized
// proportionally to my thumbnail constraints
scaledImage = getScaledImage(image, THUMB_SIZE_X, THUMB_SIZE_Y);
tempImage = new JLabel(new ImageIcon(scaledImage));
rightPane.remove(swingImage);
swingImage = tempImage;
rightPane.add(swingImage, BorderLayout.PAGE_START);
rightPane.revalidate();
rightPane.repaint(); // required sometimes
}
Or else use JLabel.setIcon(...) as mentioned earlier :-)
UPDATED THE ANSWER
Here see how a New JLabel is placed at the position of the old one,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SlideShow extends JPanel
{
private int i = 0;
private Timer timer;
private JLabel images = new JLabel();
private Icon[] icons = {UIManager.getIcon("OptionPane.informationIcon"),
UIManager.getIcon("OptionPane.errorIcon"),
UIManager.getIcon("OptionPane.warningIcon")};
private ActionListener action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
i++;
System.out.println(i);
if(i == 4)
{
timer.stop();
System.exit(0);
}
remove(images);
JLabel temp = new JLabel(icons[i - 1]);
images = temp;
add(images);
revalidate();
repaint();
}
};
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("SLIDE SHOW");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
add(images);
frame.getContentPane().add(this, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
timer = new Timer(2000, action);
timer.start();
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SlideShow().createAndDisplayGUI();
}
});
}
}
And for your Question : Of the two options that I have tried, is one better than the other?
setIcon(...) has an edge over the other way, in the sense, you doesn't have to bother about revalidate()/repaint() thingy after adding/remove JLabel. Moreover, you don't need to remember the placement of your JLabel everytime, you add it. It remains at it's position, and you simply call the one method to change the image, with no strings attached and the work is done, without any headaches.
And for Question 2 : I had a bit of doubt, as to what is Array of Records ?

Smart JScrollPane autoscrolling

I am attempting to implmement smart autoscrolling on a JScrollPane containing a JTextPane. The JTextPane is used for logging my app in color. However I'm running into a wall trying to do smart autoscrolling. By smart autoscrolling I don't mean blindly autoscrolling every time something changes, I mean checking to see if your scrolled all the way down, then autoscroll. However no matter what I do it either always autoscrolls or doesn't at all
As a test script, here's the setup (the JFrame has been left out)
final JTextPane textPane = new JTextPane();
textPane.setEditable(false);
final JScrollPane contentPane = new JScrollPane(textPane);
contentPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
And here's the ugly auto add test loop
while (true)
try {
Thread.sleep(1000);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
JScrollBar scrollBar = scroll;
boolean preCheck = ((scrollBar.getVisibleAmount() != scrollBar.getMaximum()) && (scrollBar.getValue() + scrollBar.getVisibleAmount() == scrollBar.getMaximum()));
System.out.println("Value: " + scroll.getValue()
+ " | Visible: " + scrollBar.getVisibleAmount()
+ " | Maximum: " + scrollBar.getMaximum()
+ " | Combined: " + (scrollBar.getValue() + scrollBar.getVisibleAmount())
+ " | Vis!=Max : " + (scrollBar.getVisibleAmount() != scrollBar.getMaximum())
+ " | Comb=Max: " + (scrollBar.getValue() + scrollBar.getVisibleAmount() == scrollBar.getMaximum())
+ " | Eval: " + preCheck);
StyledDocument doc = textPane.getStyledDocument();
doc.insertString(doc.getLength(), "FAGAHSIDFNJASDKFJSD\n", doc.getStyle(""));
if (!preCheck)
textPane.setCaretPosition(doc.getLength());
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
Its not pretty, but it gets the job done.
Here's though the relevant check
boolean preCheck = ((scrollBar.getVisibleAmount() != scrollBar.getMaximum()) && (scrollBar.getValue() + scrollBar.getVisibleAmount() == scrollBar.getMaximum()));
if (preCheck)
textPane.setCaretPosition(doc.getLength());
Thats the part thats been giving me trouble. There is first a check to see if the bar is visible but unusable (not enough text, making the bar the full length), then if the bottom of the bar is equal to the maximum. In theory, that should work. However nothing, including moving the check around, has gotten the results I would like.
Any suggestions?
NOT A DUPLICATE of this or this, as they are wanting it to always scroll, not just sometimes.
Edit:
I replaced the following code with a more flexible version that will work on any component in a JScrollPane. Check out: Smart Scrolling.
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.text.*;
public class ScrollControl implements AdjustmentListener
{
private JScrollBar scrollBar;
private JTextComponent textComponent;
private int previousExtent = -1;
public ScrollControl(JScrollPane scrollPane)
{
Component view = scrollPane.getViewport().getView();
if (! (view instanceof JTextComponent))
throw new IllegalArgumentException("Scrollpane must contain a JTextComponent");
textComponent = (JTextComponent)view;
scrollBar = scrollPane.getVerticalScrollBar();
scrollBar.addAdjustmentListener( this );
}
#Override
public void adjustmentValueChanged(final AdjustmentEvent e)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
checkScrollBar(e);
}
});
}
private void checkScrollBar(AdjustmentEvent e)
{
// The scroll bar model contains information needed to determine the
// caret update policy.
JScrollBar scrollBar = (JScrollBar)e.getSource();
BoundedRangeModel model = scrollBar.getModel();
int value = model.getValue();
int extent = model.getExtent();
int maximum = model.getMaximum();
DefaultCaret caret = (DefaultCaret)textComponent.getCaret();
// When the size of the viewport changes there is no need to change the
// caret update policy.
if (previousExtent != extent)
{
// When the height of a scrollpane is decreased the scrollbar is
// moved up from the bottom for some reason. Reposition the
// scrollbar at the bottom
if (extent < previousExtent
&& caret.getUpdatePolicy() == DefaultCaret.UPDATE_WHEN_ON_EDT)
{
scrollBar.setValue( maximum );
}
previousExtent = extent;
return;
}
// Text components will not scroll to the bottom of a scroll pane when
// a bottom inset is used. Therefore the location of the scrollbar,
// the height of the viewport, and the bottom inset value must be
// considered when determining if the scrollbar is at the bottom.
int bottom = textComponent.getInsets().bottom;
if (value + extent + bottom < maximum)
{
if (caret.getUpdatePolicy() != DefaultCaret.NEVER_UPDATE)
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
else
{
if (caret.getUpdatePolicy() != DefaultCaret.UPDATE_WHEN_ON_EDT)
{
caret.setDot(textComponent.getDocument().getLength());
caret.setUpdatePolicy(DefaultCaret.UPDATE_WHEN_ON_EDT);
}
}
}
private static void createAndShowUI()
{
JPanel center = new JPanel( new GridLayout(1, 2) );
String text = "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n";
final JTextArea textArea = new JTextArea();
textArea.setText( text );
textArea.setEditable( false );
center.add( createScrollPane( textArea ) );
System.out.println(textArea.getInsets());
final JTextPane textPane = new JTextPane();
textPane.setText( text );
textPane.setEditable( false );
center.add( createScrollPane( textPane ) );
textPane.setMargin( new Insets(5, 3, 7, 3) );
System.out.println(textPane.getInsets());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(center, BorderLayout.CENTER);
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(2000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Date now = new Date();
textArea.getDocument().insertString(textArea.getDocument().getLength(), "\n" + now.toString(), null);
textPane.getDocument().insertString(textPane.getDocument().getLength(), "\n" + now.toString(), null);
}
catch (BadLocationException e1) {}
}
});
timer.start();
}
private static JComponent createScrollPane(JComponent component)
{
JScrollPane scrollPane = new JScrollPane(component);
new ScrollControl( scrollPane );
return scrollPane;
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Categories