Java Swing GUI Button Image

Hi, I really need help with this one, I have tried many things and looked at many pages for this but to no avail as of yet.
I have a Swing GUI in which I want to display an image. The way I am displaying it at the moment is as a button icon as I do not need to be able to alter the images. I can also use the button functionality as displaying something when the image is clicked. So I have an array of image paths which are accesed to load an image into the button and a "Next" button to change the image as required.
My problem is that when I load an image into the button it moves from it's original location. When there is no image displayed the button is where I want it to be, but when I load an image it moves, this cannot happen. Any ideas.
Also, when I am trying to click thru the array of images, it starts at the 1st image in the array but then skips to the last image in the array. Here is the code for that.
// Handle events that arise from the "Next" button being clicked
private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {
if (jComboBox1.getSelectedIndex() == 1)
     for (int i = 1; i < juniorImageIndex.length; i++)
     jButton8.setIcon(new javax.swing.ImageIcon(juniorImageIndex));
else if (jComboBox1.getSelectedIndex() == 2)
     for (int i = 1; i < seniorImageIndex.length; i++)
     jButton8.setIcon(new javax.swing.ImageIcon(seniorImageIndex[i]));
juniorImageIndex and seniorImageIndex are obviuosly the arrrays with the file paths for the images. The reason I start at index 1 is that I use the 0 index image as the starting image for each part.
Any help gratefully appreciated, I really hope someone can help, Thanks.

// Handle events that arise from the "Next" button
being clicked
private void
jButton5MouseClicked(java.awt.event.MouseEvent evt) {
  myImageIndex =(myImageIndex + 1) % imageArray.size();
  resetButtonImage();
private void resetButtonImage() {
if (jComboBox1.getSelectedIndex() == 1)
{//take this out
//> for (int i = 1; i < juniorImageIndex.length; i++)
//> {
jButton8.setIcon(new//> javax.swing.ImageIcon(array[myImageIndex]));
//> }
else if (jComboBox1.getSelectedIndex() == 2)
{//this too
//> for (int i = 1; i < seniorImageIndex.length; i++)
//> {
jButton8.setIcon(new
javax.swing.ImageIcon(array2[myImageIndex]));//> }

Similar Messages

  • How to run Java Swing GUI on embedded ARM Linux platform?

    The object is:
    A touch panel, running Java Swing GUI, with a 25 fps 320x320 mono JPEG image animation and other control buttons.
    What I have now:
    A Developing Board with: ARM926 CPU at 266MHz, 128M RAM, 64M ROM, ported with arm-linux and MiniGUI.
    My plan is:
    1. installing a X-window system to the platform, discarding the MiniGUI.
    2. install j2re-1.3.1-RC1-linux-arm.tar.bz2 to the platform.
    3. run my program developed on a PC.
    My concerns are:
    1. Both X and Java is resource consuming, can a 266MHz ARM CPU meet my requirement?
    2. Is the X a must to run Java Swing GUI? If yes, how can I configure it to minimize the footprint, I mean, install only necessary modules.
    3. Can J2RE 1.3.1, the only port for arm linux, support Swing classes?
    4. Are there other options, such as CDC + PP(AGUI?), how to do it?
    Thanks alot!

    3. Can J2RE 1.3.1, the only port for arm linux, support Swing classes?I'm not entirely sure from your post: is this a J2SE port? If so it will support Swing, but probably needs Qt.

  • Loading large files in Java Swing GUI

    Hello Everyone!
    I am trying to load large files(more then 70 MB of xml text) in a Java Swing GUI. I tried several approaches,
    1)Byte based loading whith a loop similar to
    pane.setText("");
                 InputStream file_reader = new BufferedInputStream(new FileInputStream
                           (file));
                 int BUFFER_SIZE = 4096;
                 byte[] buffer = new byte[BUFFER_SIZE];
                 int bytesRead;
                 String line;
                 while ((bytesRead = file_reader.read(buffer, 0, BUFFER_SIZE)) != -1)
                      line = new String(buffer, 0, bytesRead);
                      pane.append(line);
                 }But this is gives me unacceptable response times for large files and runs out of Java Heap memory.
    2) I read in several places that I could load only small chunks of the file at a time and when the user scrolls upwards or downwards the next/previous chunk is loaded , to achieve this I am guessing extensive manipulation for the ScrollBar in the JScrollPane will be needed or adding an external JScrollBar perhaps? Can anyone provide sample code for that approach? (Putting in mind that I am writting code for an editor so I will be needing to interact via clicks and mouse wheel roatation and keyboard buttons and so on...)
    If anyone can help me, post sample code or point me to useful links that deal with this issue or with writting code for editors in general I would be very grateful.
    Thank you in advance.

    Hi,
    I'm replying to your question from another thread.
    To handle large files I used the new IO libary. I'm trying to remember off the top of my head but the classes involved were the RandomAccessFile, FileChannel and MappedByteBuffer. The MappedByteBuffer was the best way for me to read and write to the file.
    When opening the file I had to scan through the contents of the file using a swing worker thread and progress monitor. Whilst doing this I indexed the file into managable chunks. I also created a cache to further optimise file access.
    In all it worked really well and I was suprised by the performance of the new IO libraries. I remember loading 1GB files and whilst having to wait a few seconds to perform the indexing you wouldn't know that the data for the JList was being retrieved from a file whilst the application was running.
    Good Luck,
    Martin.

  • New help on java swing GUI.....

    k, im new to java. Just started learning a month ago. Anyway, I was wondering how one can link gui together using buttons. For example, when i press enter on a registration gui, it'll take me to the confirmation gui. What's the best way to do this? anyone has any idea or can point me to a website with info. Thanks A lots folks.

    Well, bascially you would add a Button (e.g. "Next" or "Submit") to your Window/Panel (whatever you prefer). This add has an ActionListener assigned which will open up the next Window/Panel.
    Then you define this button to be your default button on that window (check JRootPane.setDefaultButton() for this) so that Enter will fire the button.
    Check the Swing online tutorial for an introduction to Swing and how Buttons (and their associated ActionListener) work.
    Thomas

  • Skins in java swing/gui

    hi!!! i just wanna ask you guys and gals if there is a way for Java GUI to implement a skin, you know, those what we can see in Winamp. That's all. Thanks a lot!!! Have a nice day!!! :-)

    //first make sure you define the image in the class, then override the method
    //defining image
    ImageIcon imageIcon = new ImageIcon("images/background.jpg");
    Image image = imageIcon.getImage();
    //overriding the method that paints the background of the JPanel
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    if (image != null) { //there is a picture: draw it
    int height = this.getSize().height;
    int width = this.getSize().width;
    g.drawImage(image,0,0, width, height, this);
    //g.drawImage(image, 0, 0, this); //original image size
    } //end if
    } //end paint

  • Using extends in Java SWING GUI

    i have designed this login page and this other page for checking marks.
    The idea is, if the person who logs on is the particular unique user, he will be able to check the marks of that subject, If other person who logs on and try to check the mark, he will be given a message instead.
    So in order to retrieve the person's username n check to see if he can be authorized, i have to retrieve the textfield results from the login page and then implemented it into my method in the mark's page. so i just extends the Login page.
    I did the dispose method n everything, and now
    a) when i logged on as that user, my marks page dioesn't come out as planned, instead a login page comes out
    b) when i run the marks page , the login page and my mark's page come out at the same time ?
    why is this so ?

    The reason your login page is showing up on your next panel is because you extend it. When you extend a class you inherit everything about that class including the gui. You should just make 2 seperate classes and pass in the values you want either through the constructor or make some methods to pass in the value. So what you should do is make your login class take the username and password then validate it. If the user has entered a valid username/password then pass the next class the username.Here is some suedo code I'm not going to write out everything because it would take too long.class Login extends JDialog
       private String userName;
       private String passWord;
       public Login()
           // add your textfields and other gui components
          // take in the username and password
          // verify them in some other method
          if(this.validateUser() == true)
              MarksPanel markPanel = new MarksPanel(username);
       public boolean validateUser()
            // some code to check username and password
    class MarksPanel extends JPanel
       public MarksPanel(String Username)
           // now you have the username in a seprate class and
           // since you don't extend Login here you won't see the same
          // Login panel on top of this

  • Java Swing Help

    Hi, I am currently using a program called JPadPro for my java source codes. I am just beginning to learn java and I have just started on Java Swing GUI codings. My problem is that the program compiles, but it doesn't run. It always give me an error saying
    "Cannot find main method, Program will exit". there is nothing wrong with my source code because I can run somewhere else. I think I didn't configure my Jpadpro correctly. (but anything without GUI does work)
    Thank You for your help :)

    Even though you are running a swing application, you still need a main method just as in non-GUI applications. The main should create an instance of the JFrame at the base of you swing app. A simple example is as follows:
    public class mySwingApp extends JFrame {
    public mySwingApp(String title) {
    super(title);
    // GUI components, layouts, possible listeners here
    public static void main(String[] args) {
    JFrame mainFrame = new mySwingApp("My first swing app");
    mainFrame.setSize(200, 200);
    mainFrame.setVisible(true);
    }Hope this helps some!
    -JBoeing

  • Launching Swing GUI from Oracle Forms Web Based

    Hi there,
    I have oracle forms which call a shell script which initiates the java swing gui. I am using host command to run this script. When I am doing it on unix server everything works fine. Now we want same application on web now i am getting problem. The host command is not working in this case. It can not launch the java gui. Can anybody tell me what will be the nice approach to do it.
    Thanks
    Ranjan

    Hi,
    you'll have to create a Java Bean in Forms that calls the runtime. You can also use webutil, available on otn to call a client side host command.
    Frank

  • Problem with java swing button and loop

    Problem with java swing button and loop
    I�m using VAJ 4.0. and I�m doing normal GUI application. I have next problem.
    I have in the same class two jswing buttons named start (ivjGStart) and stop (ivjGStop) and private static int field named Status where initial value is 0. This buttons should work something like this:
    When I click on start button it must do next:
    Start button must set disenabled and Stop button must set enabled and selected. Field status is set to 1, because this is a condition in next procedure in some loop. And then procedure named IzvajajNeprekinjeno() is invoked.
    And when I click on stop button it must do next:
    Start button must set enabled and selected and Stop button must set disenabled.
    Field status is set to 0.
    This works everything fine without loop �do .. while� inside the procedure IzvajajNeprekinjeno(). But when used this loop the start button all the time stay (like) pressed. And this means that a can�t stop my loop.
    There is java code, so you can get better picture:
    /** start button */
    public void gStart_ActionEvents() {
    try {
    ivjGStart.setEnabled(false);
    ivjGStop.setEnabled(true);
    ivjGStop.setSelected(true);
    getJTextPane1().setText("Program is running ...");
    Status = 1;
    } catch (Exception e) {}
    /** stop button */
    public void gStop_ActionEvents() {
    try {
    ivjGStart.setEnabled(true);
    ivjGStart.setSelected(true);
    ivjGStop.setEnabled(false);
    getJTextPane1().setText("Program is NOT running ...");
    Status = 0;
    } catch (Exception e) {
    /** procedure IzvajajNeprekinjeno() */
    public void IzvajajNeprekinjeno() {  //RunLoop
    try {
    int zamik = 2000; //delay
    do {
    Thread.sleep(zamik);
    PreberiDat(); //procedure
    } while (Status == 1);
    } catch (Exception e) {
    So, I'm asking what I have to do, that start button will not all the time stay pressed? Or some other aspect of solving this problem.
    Any help will be appreciated.
    Best regards,
    Tomi

    This is a multi thread problem. When you start the gui, it is running in one thread. Lets call that GUI_Thread so we know what we are talking about.
    Since java is task-based this will happen if you do like this:
    1. Button "Start" is pressed. Thread running: GUI_Thread
    2. Event gStart_ActionEvents() called. Thread running: GUI_Thread
    3. Method IzvajajNeprekinjeno() called. Thread running: GUI_Thread
    4. Sleep in method IzvajajNeprekinjeno() on thread GUI_Thread
    5. Call PreberiDat(). Thread running: GUI_Thread
    6. Check status. If == 1, go tho 4. Thread running: GUI_Thread.
    Since the method IzvajajNeprekinjeno() (what does that mean?) and the GUI is running in the same thread and the event that the Start button has thrown isn't done yet, the program will go on in the IzvajajNeprekinjeno() method forever and never let you press the Stop-button.
    What you have to do is do put either the GUI in a thread of its own or start a new thread that will do the task of the IzvajajNeprekinjeno() method.
    http://java.sun.com/docs/books/tutorial/uiswing/index.html
    This tutorial explains how to build a multi threaded gui.
    /Lime

  • Running a Java application from a Swing GUI

    Hi,
    I was wondering if there is a simple way to run a Java application from a GUI built with Swing. I would presume there would be, because the Swing GUI is a Java application itself, technically.
    So, I want a user to click a button on my GUI, and then have another Java application, which is in the same package with the same classpaths and stuff, run.
    Is there a simple way to do this? Do any tutorials exist on this? If someone could give me any advice, or even a simple "yes this is possible, and it is simple" or "this is possible, but difficult" or "no this is not possible" answer, I would appreciate it. If anyone needs more information, I'll be happy to provide it.
    Thanks,
    Dan

    I don't know if it is possible to run the main method from another Java app by simply calling it...
    But you could just copy and paste the stuff from your main method into a new static method called something like runDBQuery and have all the execution run from there.
    How does that sound? Is it possible?
    What I'm suggeting is:
    Original
    public class DBQuery{
    public static void methodA(){
    public static void doQuery(){
    methodA();
    public static void main(String[] args){
    // Your method calls
    //Your initializing
    doQuery();
    }Revised:
    public class DBQuery{
    public static void methodA(){
    public static void doQuery(){
    methodA();
    public static void doMyQuery(){
    // Your method calls
    //Your initializing
    doQuery();
    // No main needed!!
    //public static void main(String[] args){
    // Your method calls
    //doQuery();
    //}

  • Help with implementing Swing GUI within jpg image

    Dear Java Experts,
    I have a question, is there a way to implement java swing objects (ie jbutton, jcombobox, etc) within an imageicon. Basically, i am trying to juggle between ways of getting JSwing GUI into a background jpg image. Please help me. I thank you all in advance.

    You've it back to front.
    Create an transparent extension of JPanel that paints an image on it's
    background before running it's super class paint method.
    You'll need to extend this example to stretch, center or tile the image
    but otheriwse it's complete.
    BTW - you have to pass an argument to this example that is the path of
    the image you want on the background of the panel, like:
    java -cp <whatever> MyJavaProject1 images/something.gif
    Enjoy.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class MyJavaProject1
         static class BackgroundPanel
              extends JPanel
              private ImageIcon mIcon;
              public BackgroundPanel(ImageIcon icon) {
                   mIcon= icon;
                   super.setOpaque(false);
              public void setOpaque(boolean flag) { }
              public void paint(Graphics g)
                   g.drawImage(mIcon.getImage(), 0, 0, null);
                   super.paint(g);
         public static void main(String[] argv)
              JFrame frame= new JFrame(argv[0]);
              BackgroundPanel panel= new BackgroundPanel(new ImageIcon(argv[0]));
              panel.setLayout(new GridLayout(0,2,4,4));
              panel.setBorder(new EmptyBorder(4,4,4,4));
              panel.add(new JLabel("Name"));
              panel.add(new JTextField());
              panel.add(new JLabel("Address"));
              panel.add(new JTextField());
              panel.add(new JLabel("Phone"));
              panel.add(new JTextField());
              frame.getContentPane().add(panel, BorderLayout.CENTER);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setResizable(false);
              frame.setVisible(true);
    }

  • Java Swing/AWT and FX is so old school! Give me HTML and CSS for GUI!

    Dear Java,
    I am a seasoned programmer and I feel it's time JAVA implements a GUI system where it uses HTML and CSS for the GUI. For the love of god just look at the interfaces you can make using HTML and CSS alone. I am a big fan of Java Swing and the recent GUI designer for FX is quite cool. But they are just not as simple as HTML and CSS. And JavaFX has some interesting requirements for the graphics.
    I know it is possible to use JavaFX and implement the WebView/WebDriver and make it load a HTML page, etc... but why go through all the trouble?
    Just imagine... if you make Java where it has powerful back-end to do what it does best and the HTML/CSS powered GUI on the front-end. It will make the lives of many developers much much easier.
    I am not sure whether a Swing designed GUI will be faster than a HTML designed GUI... but if you look at a traditional browser and how fast it renders HTML/CSS, I am sure if Java had a native Form where it uses HTML and CSS to render the GUI, Java will make the dreams of many programmers a reality.
    Make it happen!!!!

    Check this i solve problem just now using this
    https://wiki.archlinux.org/index.php/Ja … ow_Manager

  • Transparent Buttons in Java Swing?

    Hi!
    I want to create transparent Buttons using java swing for my desktop application. Can any one tell me how to do it?

    I can help, but it depends on what you mean by "transparent".
    Do you mean TOTALLY transparent, or slightly transparent, or merely translucent? Do you want the text on the button to be in any way transparent? You really need to be more specific.
    Basically, though, the concept is pretty simple. All swing components have several methods that can be overridden by somebody who knows what they are doing, in order to customize their appearances.
    Some of these are: paint(), paintComponent(), ComponentUI.paint(), etc.
    You need to determine the right place to put the new code. Then you extend the class, and change the transparency of the graphics object passed into the method in question, and then pass control to the super implementation of that method.
    There are some traps you need to make sure you avoid, though:
    1. If you want transparent components, you MUST have the opaque property of the component set to false. Otherwise, the components beneath your transparent button will never update.
    2. When you start messing with a graphics object to create transparency, you need to make sure that you revert your changes to the graphics object when you are finished, because all painting uses the same graphics object -> so if you set your button transparent, and then forget to remove the transparency, all objects drawn after the button will also be drawn transparent.
    A word of caution:
    This sort of manipulation is not hard, but you NEED to understand the painting model for SWING. There are a few articles hosted by sun that can help you in this respect.
    Good Luck!
    - Adam

  • Draggable buttons in Java Swing

    Hi,
    I want to develop an application in Java Swing. The application I am going to develop is an application for developing other applications. I want my application to include a button which also acts as a drag and drop UI element. For example, I want my application to include a button for adding a picture. There are 4 buttons of different pictures. If a user wants to add a picture he can either click on one of these buttons and that picture will be added somewhere on the screen or dragging this button and drop it and that picture will be added where he dropped that button.
    Could anyone please tell me…
    1. If I can develop an application which includes Drag and Drop UI element if I develop it in Java Swing
    2. If a button (or other UI element) can act as both a button and a drag and drop element if I develop my application in Java Swing
    3.
    Could you please tell me where I can find some screenshots of applications which has been developed in Java Swing? I am not familiar with this program and I am not that good at programming, so I would like to get some impression of how it might look like.
    Thanks in advanced

    1. the good thing about Swing is that it is very flexible and with clever programming you can do just about anything. The problem is that depending on your requirements, this could require a great deal of programming that can be very hard to implement such that it works properly on all popular platforms (windows, linux, mac).
    2. see 1.
    3. Swing applications are "skinnable", you can give them a great number of different appearances. The default is to give the application a system look and feel, so they look pretty much like any other application for that platform. This means that when you run your application on Windows, it will look like a Windows application, if you run it on a Mac it will look like a Mac application, etc.
    I am not familiar with this program and I am not that good at programmingThat is quite a problem, because Swing is not the easiest API around. It requires a solid knowledge of Java and Object Oriented Programming in general as the entire API is based heavily on OOP concepts. To get a better idea of Swing, read through the Swing tutorial here:
    http://java.sun.com/docs/books/tutorial/uiswing/

  • Creating file browser GUI using java swing tree

    Hi all,
    I have some questions which i wish to clarify asap. I am working on a file browser project using java swing. I need to create 2 separate buttons. 1 of them will add a 'folder' while the other button will add a 'file' to the tree when the buttons are clicked once. The sample source code known as 'DynamicTreeDemo' which is found in the java website only has 1 add button which is not what i want. Please help if you know how the program should be written. Thx a lot.
    Regards,

    Sorry, don't know 'DynamicTreeDemo'import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.io.File;
    public class Test extends JFrame {
      JTree jt = new JTree();
      DefaultTreeModel dtm = (DefaultTreeModel)jt.getModel();
      JButton newDir = new JButton("new Dir"), newFile = new JButton("new File");
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        newDir.setEnabled(false);
        newFile.setEnabled(false);
        jt.setShowsRootHandles(true);
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        File c = new File("C:\\temp");
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(c);
        dtm.setRoot(root);
        addChildren(root);
        jt.addTreeSelectionListener(new TreeSelectionListener() {
          public void valueChanged(TreeSelectionEvent tse) { select(tse) ; }
        JPanel jp = new JPanel();
        content.add(jp, BorderLayout.SOUTH);
        jp.add(newDir);
        jp.add(newFile);
        newDir.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            TreePath tp = jt.getSelectionPath();
            if (tp!=null) {
              DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
              File newFile = new File((File)dmtn.getUserObject(),"foo");
              if (newFile.mkdir()) {
                dmtn.add(new DefaultMutableTreeNode(newFile));
                dtm.nodeStructureChanged(dmtn);
              } else System.out.println("No Dir");
        newFile.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            TreePath tp = jt.getSelectionPath();
            if (tp!=null) {
              DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
              File newFile = new File((File)dmtn.getUserObject(),"foo.txt");
              try {
                if (newFile.createNewFile()) {
                  dmtn.add(new DefaultMutableTreeNode(newFile));
                  dtm.nodeStructureChanged(dmtn);
                } else System.out.println("No File");
              catch (java.io.IOException ioe) { ioe.printStackTrace(); }
        setSize(300, 300);
        setVisible(true);
      void select(TreeSelectionEvent tse) {
        TreePath tp = jt.getSelectionPath();
        newDir.setEnabled(false);
        newFile.setEnabled(false);
        if (tp!=null) {
          DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
          File f = (File)dmtn.getUserObject();
          if (f.isDirectory()) {
            newDir.setEnabled(true);
            newFile.setEnabled(true);
      void addChildren(DefaultMutableTreeNode parent) {
        File parentFile = (File)parent.getUserObject();
        File[] children = parentFile.listFiles();
        for (int i=0; i<children.length; i++) {
          DefaultMutableTreeNode child = new DefaultMutableTreeNode(children);
    parent.add(child);
    if (children[i].isDirectory()) addChildren(child);
    public static void main(String[] args) { new Test(); }

Maybe you are looking for