Help in swing components

Hai,
There are 9 buttons as a square in a Gui.
When I click on a button its label should change to "W"
How do I do it?
This is very important to me! Kindly help me in this!
Thankyou.

Hi,
Use setText on the button.
/Kaj

Similar Messages

  • Need help with using graphics in swing components

    Hi. I'm new to Java and trying to learn it while also developing an application for class this semester. I've been following online tutorials for about 2 months now, though, and so I'm not sure my question counts as a "new to Java" question any more as the code is quite long.
    Here is the basic problem. I started coding the application as a basic awt Applet (starting at "Hello World") and about a month in realized that Swing components offer better buttons, panels, layouts, etc. So I converted the application, called BsfAp, to a new JApplet and started adding JPanels and JComponents with layout managers. My problem is, none of the buffered graphics run in any kind of JPanel, only the buttons do. I assume the buffered graphics are written straight to the JApplet top level container instead but I'm not entirely sure.
    So as to not inundate the forum with code, the JApplet runs online at:
    http://mason.gmu.edu/~dho2/files/sensor.html
    The source code is also online at:
    http://mason.gmu.edu/~dho2/files/BsfAp.java
    What I would like to do is this - take everything in the GUI left of the tabbed button pane and put it into a JScrollPane so that I can use a larger grid size with map display I can scroll around. The grid size I would like to use is more like 700x1000 pixels, but I only want to display about 400x400 pixels of it at a time in the JScrollPane. Then I could also move this JScrollPane around with layout manager. I think this is possible, but I don't know how to do it.
    I'm sure the code is not organized or optimized appropriately to those of you who use Java every day, but again I'm trying to learn it. ;-)
    Thanks for any help or insight you could provide in this.
    Matt

    Couple of recs:
    * Don't override paint and paint directly on the JApplet. Paint on a JPanel and override paintComponent.
    * The simplest way to display a graphic is to put an image into an ImageIcon and show this in a JLabel. This can then easily go inside of the JScrollPane.
    * You can also create a graphics JPanel that overrides the paintComponent, draw the image in that and show that inside of the JScrollPane.
    * don't call paint() directly. Call repaint if you want the graphic to repaint.
    Here's a trivial example quickly put together:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import java.awt.RenderingHints;
    import java.awt.geom.Ellipse2D;
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class BsfCrap extends JApplet
        private JPanel mainPanel = new JPanel();
        private JScrollPane scrollPane;
        private JPanel graphicsPanel = new JPanel()
            @Override
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g;
                RenderingHints rh = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setRenderingHints(rh);
                Paint gPaint = new GradientPaint(0, 0, Color.blue,
                    40, 40, Color.magenta, true);
                g2d.setPaint(gPaint);
                g2d.fill(new Ellipse2D.Double(0, 0, 800, 800));
        public BsfCrap()
            mainPanel.setPreferredSize(new Dimension(400, 400));
            mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            graphicsPanel.setPreferredSize(new Dimension(800, 800));
            graphicsPanel.setBackground(Color.white);
            scrollPane = new JScrollPane(graphicsPanel);
            scrollPane.setPreferredSize(new Dimension(300, 300));
            mainPanel.add(scrollPane);
        public JPanel getMainPanel()
            return mainPanel;
        @Override
        public void init()
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        setSize(new Dimension(400, 400));
                        getContentPane().add(new BsfCrap().getMainPanel());
            catch (InterruptedException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }

  • Printing Swing components doesn't work on all printers? Please Help!

    I have a really serious problem. I try to print Swing components with the so called PrintUtilities class. The source code can be found here: http://archive.corewebprogramming.com/Chapter15/printing/PrintUtilities.java).
    My Swing components are panels (JPanel) including more panels and/or other components like text fields, text areas, combo boxes, radio buttons, check boxes and so on.
    On one of my printers (Kyocera mita FS 1010) it works fine. But on other printers (Panasonic DP-2000, HP Deskjet 890 C) the results are weird: Only the first component (independent of the component depth) is printed (and it is every time the same result!).
    I don't know whether this is important or not, but all printers I use are installed as network printers.
    I have already searched the forum but couldn't find a similar problem.
    Can anyone tell me what the problem is and what I can do to solve it?
    Thank you for any response in advance!

    try this:
    package ayto;
    import java.awt.*;
    import java.awt.print.*;
    import javax.swing.JComponent;
    public class ComponenteParaImprimir
    implements Printable {
    private Component mComponent;
    boolean isBook;
    final static boolean PARA_BOOK = true;
    final static boolean HARDCOPY = false;
    public ComponenteParaImprimir(Component c, boolean book) {
    mComponent = c;
    isBook = book;
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0 && !isBook) {
    return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    boolean wasBuffered = disableDoubleBuffering(mComponent);
    mComponent.paint(g2);
    restoreDoubleBuffering(mComponent, wasBuffered);
    return PAGE_EXISTS;
    private boolean disableDoubleBuffering(Component c) {
    if (c instanceof JComponent == false) {
    return false;
    JComponent jc = (JComponent) c;
    boolean wasBuffered = jc.isDoubleBuffered();
    jc.setDoubleBuffered(false);
    return wasBuffered;
    private void restoreDoubleBuffering(Component c, boolean wasBuffered) {
    if (c instanceof JComponent) {
    ( (JComponent) c).setDoubleBuffered(wasBuffered);
    }

  • Swing components in applet not working in web browser

    Hi Guys,
    I've created an applet which makes use of some swing components, but unfortunately, not all of them function properly in my web browser (internet explorer or Mozilla Firefox). Its mainly the buttons; the last buttons works and displays the correct file within the broswer, but the first 5 buttons do not work...
    any help please on how I can sort this problem out?
    Heres the code for my applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.applet.*;
    public class MainAppWindow extends JApplet
    int gapBetweenButtons = 5;
    final JPanel displayPanel = new JPanel(new BorderLayout());
    public void init()
       //Panel for overall display in applet window.
       JPanel mainPanel = new JPanel(new BorderLayout());
       mainPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/smalllogo2.gif"))),BorderLayout.NORTH);
       //sub mainPanel which holds all mainPanels together.
       JPanel holdingPanel = new JPanel(new BorderLayout());
       //Panel for displaying all slide show and applications in.
       displayPanel.setBackground(Color.white);
       displayPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/IntroPage.jpg"))),BorderLayout.CENTER);
       displayPanel.setPreferredSize(new Dimension(590,400));
       JPanel buttonPanel = new JPanel(new GridLayout(6,1,0,gapBetweenButtons));
       buttonPanel.setBackground(Color.white);
       JButton button1 = new JButton("User guide");
       button1.addActionListener(
         new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll(); // If there are any components in the mainPanel, remove them and then add label
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/UserGuide.jpg")));
                   displayPanel.revalidate(); // Validates displayPanel to allow changes to occur onto it, allowing to add different number images/applicaions to it.
       JButton button2 = new JButton("What is a Stack?");
       button2.addActionListener(
       new ActionListener() {
               public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/WhatIsAStack.jpg")));
                   displayPanel.revalidate();
       JButton button3 = new JButton("STACK(ADT)");
       button3.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/StackADT.jpg")));
                   displayPanel.revalidate();
       JButton button4 = new JButton("Stacks in the Real World");
       button4.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/StacksInTheRealWorld.jpg")));
                   displayPanel.revalidate();
       JButton button5 = new JButton("DEMONSTRATION");
       button5.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                 if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                 Demonstration app = new Demonstration();
                 JPanel appPanel = app.createComponents();//gets the created components from Demonstration application.
                 appPanel.setBackground(Color.pink);
               displayPanel.add(appPanel);
               displayPanel.revalidate();
       JButton button6 = new JButton("Towers Of Hanoi");
       button6.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                     if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                     TowerOfHanoi app = new TowerOfHanoi();
                     JPanel appPanel = app.createComponents();//gets the created components from Towers of Hanoi
                     JPanel mainPanel = new JPanel();//panel used to centralise the application in center
                     mainPanel.add(appPanel);
                     mainPanel.setBackground(Color.pink); //sets mainPanel's background color for 'Towers Of Hanoi'
                     displayPanel.add(mainPanel);
                     displayPanel.revalidate();
       //adding buttons to the buttonPanel.
       buttonPanel.add(button1);
       buttonPanel.add(button2);
       buttonPanel.add(button3);
       buttonPanel.add(button4);
       buttonPanel.add(button5);
       buttonPanel.add(button6);
       JPanel p = new JPanel(); // Used so that the buttons maintain their default shape
       p.setBackground(Color.white);
       p.add(buttonPanel);
       holdingPanel.add(p,BorderLayout.WEST);
       holdingPanel.add(displayPanel,BorderLayout.CENTER);
       //Positioning of holdingPanel in mainPanel.
       mainPanel.add(holdingPanel,BorderLayout.CENTER);
       //indent mainPanel so that its not touching the applet window frame.
       mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
       mainPanel.setBackground(Color.white);
       mainPanel.setPreferredSize(new Dimension(850,600)); //size of applet window
       mainPanel.setOpaque(false); // Needed for Applet
       this.setContentPane(mainPanel);
    }

    Thanks for the response. I don't quite understand what you're talking about though. I have, in my humble knowledge, done nothing with packages. I have put the applet class (WiaRekenToolActiz.class is the applet class) in the jar file wia_actiz_archive.jar. From what I read on the tutorial, java looks for the applet class in all the jar files specified. Since I put my CODEBASE as the main url, I thought it baiscally didn't matter where you out the html file.
    I shall include the complete html page complete with applet tag to perhaps illuminate a bit more what I mean...
    <html>
    <head>
    <title>Wia Rekenmodule hello!</title>
    </head>
    <body bgcolor="#C0C0C0">
    <applet
    CODEBASE= "http://www.creativemathsolutions.nl/test"
    ARCHIVE= "Actiz/wia_actiz_archive.jar, Generic/wia_archive.jar"
    CODE="WiaRekenToolActiz.class" 
    WIDTH=915 HEIGHT=555
    >
    <PARAM NAME = naam VALUE = "Piet Janssen">
    <PARAM NAME = gebdag VALUE = "01">
    <PARAM NAME = gebmaand VALUE = "06">
    <PARAM NAME = gebjaar VALUE = "1970">
    <PARAM NAME = geslacht VALUE = "man">
    <PARAM NAME = dienstjaren VALUE = "10">
    <PARAM NAME = salaris VALUE = "56500">
    <PARAM NAME = deeltijdpercentage VALUE = "100">
    <PARAM NAME = accountnaam VALUE = "Zorginstelling 'De Zonnebloem'">
    </applet>
    </body>
    </html>

  • I'd like to make a list of interactive Swing components....

    EDIT: I've been doing more research about Layout Managers and it appears that BoxLayout may provide me with the solution I need. I'll mess around with it for awhile and report back if I still need help. Thanks pals!+
    I would like to make a list of JPanels laid out in basically a column. One on top of the other. That's not so difficult, but I need to make it able able to add and remove panels in response to user-driven events (in other words, I can't just hard-code them all, and the panels are generated on the fly, so I don't even know how many I'll need to be displaying until I need to display them.
    Here's a simple mockup of the window I'm talking about.
    |      - o x |
    |____________|
    |            |
    |            |
    |   Panel1   |
    |   Panel2   |
    |   Panel3   |
    |   Panel4   |
    |____________|At first, I thought a JList would serve my purpose, but you can't add interactive Swing components to JLists (or JTables)... they'll render, but that's all. My panels will contain a button and a checkbox, so this is a no-go.
    I was also thinking I could just manage the placement with GridBagLayout and just keep indexes for the current y position, but if there's an easier way, I'd rather not go this route. It has me writing a lot of extra code and manipulating a lot of fields of GridBagConstraints, which opens me to less-understandable code and more error-prone code, on account of I'm great at making little mistakes when I'm setting craploads of constraints.
    Does anyone have any ideas? It'd be ideal if there was just some sort of container I could plop them in with add and remove methods (a la JTabbedPane or something).
    I'm pretty new to Swing, so maybe I'm missing something obvious.
    Edited by: Caryy on Sep 30, 2010 4:15 PM

    I would recommend using BoxLayout or Box.createVerticalBox(). As mKorbel already mentioned, you need to call revalidate() after adding any component to an already realized/visible container, and additionally call repaint() after removing a component. To resize the top level window to accommodate its new content, you would call pack(). Or, again as suggested by mKorbel, wrap your panel/Box in a JScrollPane.
    db

  • Showing swing components in the palette og jdeveloper

    hello, I have found a problem with jdeveloper, as a user uses jdeveloper since 2 years I have never found a problem like this. (IDE problem).
    like habitude I created a simple java project which contains a jframe and an entry class (main class), but when I try to drag and drop from the component palette somes swing components I didn't find
    the page of swing components ( I found in the components palette just "my components" page in the jcombobox selection category). this problem will delay a big project and causes big problems
    please any person who know some things help me as soon as possible.
    Best Regards.

    Check this post -
    showing palette containing JButton,JLabel,JPanel ... components

  • Multifont output in Swing components

    Hi there,
    though I'm not new to Java but I'm new to displaying different fonts in Swing components.
    I have an Swing-based application which is running on a Terminal Server. It works fine for Central, Western und Northern Europe. The next
    country to roll out is Greece. So what does a greek user see on his monitor when he uses his greek keyboard?
    I am writing a test app where I type german text into a JTextField and want to get e.g. the greek representation in another JTextField. How can I achieve this? Converting the bytearray with Cp1253 did not work
    Can anybody give me a hint?
    Thanks
    Dierk.

    as I wrote, it is a test app to learn how I get greek
    fonts on the screen. Of course the real app is used by
    greek users who put greek text into the system. In the
    system we do not use resource bundles as the GUI texts
    are stored in the database. It is a CMS for product
    information in different languages.Ah, I see... mind you, I don't think your German text would have a great deal of Cyrillic characters in them, right? Still, it's only a test! ;-)
    Now what I'm doing to get my german text in greek
    letters is this:
    utf8Bytes =
    = getorigTextField().getText().getBytes("UTF16");
    isr = new InputStreamReader(new
    w ByteArrayInputStream
    (utf8Bytes), "Cp1253");
    As far as I understand, the InputStreamReader gives
    the translation
    of my german letters in the encoding of CP1253
    (Windows Greek). That
    means the unicode characters change into the ones of
    the greek language
    so I should be able to show them in a Swing component.This is where your problem is. Java's Strings will always be in UTF-16 when they are held internally. So anything within a textfield is going to be UTF-16 no matter what you do with it.
    The line you think is converting to Cp1253 is actually trying to convert from Cp1253 to UTF-16.
    Hopefully this is the reason your characters aren't appearing - the unneeded conversion above could be mashing them. Instead, you need expect everything to always be in UTF-16, and to expect to display in it (don't worry, it handles any character you can throw at it, let alone Greek). So then it all comes down to the font you're using.
    I'm not too sure of the name of the Windows default Cyrillic font, but that would be a logical starting point.
    Hope that helps!
    Martin Hughes

  • Hindi Numerals and Hejri calender in swing components

    Hi
    Are Hindi numerals and Hejri calender supported in JDK 1.4 swing components or not?
    Please I need this as soon as possible.
    Thanks in advance
    Marwa Aboulfadl

    hello!
    I am developing an arabic editor but i am unable to display the arbic numeric in swing text .Plz help me on this topic and send some code example on this topic.
    I have another problem about events i.e how can i handle the beckspace event, enter event, and spaceevent?
    plz send me mail .
    Thanx for advance.

  • Swing components not displaying correctly in JApplet

    Hello everyone,
    I have experienced some strange problems using Swing components on JApplets. Maybe I missed some documentation somewhere and someone can help me out.
    The problem is that when I add components like JButtons,
    JCheckboxes, JRadioButtons, JTextFields, JPasswordFields,
    and JComboBoxes to JApplets, when I view the applet, the
    component does not become visible until I move the mouse
    pointer over it in the case of buttons. For the JComboBox I have
    to hit the mouse key many times on the component to see the list. Has anyone experienced problems like these? Thanks.
    Keith

    check what is in ur paint(Graphic g) method. if it does nothing, remove the paint(Graphic g) method. if it has some codes, double check ur codes.

  • How to list/access swing components?

    hi all,
    Can anyone give me a clue, how can I access or simply list swing components I have on a frame, long after I created them. E.g. I'd like to change their setEnabled() attribute at a later time, not at creation time, but I don't know how to access them.
    Does Swing/AWT/JFC provides a component hierarchy? can someone share some code on this issue?
    Thanks for any help.
    Thomas

    I guess, you are saying the use of getComponent(int n)?
    Since I'm a beginner in Swing see my short code below:
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTextArea;
    public class EasyFrame {
        public EasyFrame() {
            super();
            startHere();
        public void startHere() {
            JFrame frame = new JFrame("SwingApplication");
            JButton button = new JButton("click here");
            JTextArea area = new JTextArea();
            frame.setSize(300, 200);
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(area, BorderLayout.CENTER);
            frame.getContentPane().add(button, BorderLayout.SOUTH);
            area.setText("Hello World");
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("A Menu");
            menuBar.add(menu);
            JMenuItem menuItem = new JMenuItem("A text item");
            menu.add(menuItem);
            menu.addSeparator();
            menuItem = new JMenuItem("hello");
            menu.add(menuItem);
            JMenu subMenu = new JMenu("submenu");
            menuItem = new JMenuItem("sub1");
            subMenu.add(menuItem);
            menuItem = new JMenuItem("sub2");
            subMenu.add(menuItem);
            menu.add(subMenu);
            frame.getContentPane().add(menuBar, BorderLayout.NORTH);
            frame.show();
         public static void main(String[] args) {
         EasyFrame ef = new EasyFrame();
    }If I make a System.out.println(frame.getContentPane().getComponentCount());I get 3. But I should dig deeper (with getComponent(2)) to access JMenuBar. But this way I receive a AWT Component / not a JMenuBar Swing component to get its JMenu / and its JMenuItems. And I cannot make it cast to JMenuBar since this walk-through routine should be a universal while(isThereMoreCompenent){} procedure, I don't know when to cast to what (JMenu, JMenuItem, Button and so on).
    My problem is that how can I access the JMenuItems one by one, and change e.g. the setEnabled attribute of the "hello" menu?
    I hope you can make it clear to me.
    Please help if so.

  • How to use Swing Components in  JavaFX

    Hi All,
    I am new to JavaFx. I am trying to use java swing components in javafx.
    I found a sample program in net and tried it. But it shows compile time error.
    Code:
    MySwingComponent .fx
    import javafx.ext.swing.SwingComponent;
    import javax.swing.JComponent;
    import javax.swing.JButton;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    * @author nandha
    class MySwingComponent extends SwingComponent{
    var button: JButton;
    public var text: String on replace {
    button.setText(text);
    public var action: function();
    override protected function createJComponent () : JComponent {
    button = new JButton();
    button.addActionListener(ActionListener {
    public override function actionPerformed(e:ActionEvent){
    action();
    return button;
    The above code shows no error.
    Test SwingButton.fx
    import javafx.stage.Stage;
    import javafx.scene.Scene;
    import swingcomponents.MySwingButton;
    * @author nandha
    Stage {
    title: "Swing Button Example"
    scene: Scene {
    width: 250
    height: 80
    content: [
    MySwingButton{  // error message: imcompatible type. found MySwingButton. Required javafx.scene.Node[]
    text: "Click Me!"
    action: function(){
    println("Hello World!");
    This code which used the MySwingButton shows error: imcompatible type. found MySwingButton. Required javafx.scene.Node[] - where i have added the MySwingButton.
    Please help me to fix the error.
    Thanks &Regards,
    Nandha K

    Hi Sasa,
    First thanks for your reply.
    I found the problem and have fixed.
    Problem:
    There is no class MySwingButton in the package swingcomponents. Its MySwingComponent that i should have used, which is a big mistake that i have done. To my surprise i don't know NetBeans didn't show any error message at that line.
    Thanks & Regards,
    Nandha K

  • Embedding Swing Components within Javafx Scene (on a Mac)

    Currently I trying to embed swing components into javafx through steps located here: SwingNode The Myth not the reality | In-SideFX
    Was able to get it working on a PC, however when the packaged jar is run on a mac, I end up with the "Headless exception"
    "Process manager already initialized: can't fully enable headless mode." (error attached below)
    Currently using java 7 update 51, using java 8 is not an option unfortunately.
    Does anyone know of a work around to get this working in mac or possibly point me in the right direction?
    Please let me know if providing other things would help. Thank you in advanced!

    Currently I trying to embed swing components into javafx through steps located here: SwingNode The Myth not the reality | In-SideFX
    Was able to get it working on a PC, however when the packaged jar is run on a mac, I end up with the "Headless exception"
    "Process manager already initialized: can't fully enable headless mode." (error attached below)
    Currently using java 7 update 51, using java 8 is not an option unfortunately.
    Does anyone know of a work around to get this working in mac or possibly point me in the right direction?
    Please let me know if providing other things would help. Thank you in advanced!

  • How to add swing components in an applet

    hello friends;
    I encounterd one problem that is I created one applet which I derived from JApplet and now I want to add some swing components to that applet. I added them properly and when I am testing my applet in Appletviewer it is working fine but when I tested it in internet explorer it is not working. Please help me overcome this problem
    Thanks in advance.
    Amit

    IE does not support swing if you do not have the java-plugin installed. Either install that, then IE can display Swing components - or use AWT which can be displayed by IE.
    cheers,
    kelysar

  • JDBC-ODBC Bridge, Swing Components

    This program displays information from the Access database Autos.mdb.
    Uses the JDBC-ODBC Bridge.
    Requires a DSN called Autos pointing to Auto.mdb
    I am using the swing components and can't seem to set up my combobox to pull the right data which doesn't display any of the data from the database. I am able to do it using AWT but would like a sleeker look so I am trying to convert. I have made the text bold where I am having the problem. Any insight would be greatful! I am very new to JDBC-ODBC so please go easy on me...
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class JDBCApp extends Frame implements ItemListener
         //Declare database variables
         Connection conVehicle;
         Statement cmdVehicle;
         ResultSet rsVehicle;
         boolean blnSuccessfulOpen = false;
         //Declare components
         JComboBox lstManuf   = new JComboBox();
         JLabel lblModel  = new JLabel("                          ");
         JLabel lblYear        = new JLabel("                          ");
         JLabel lblCost      = new JLabel("                          ");
         JLabel lblID      = new JLabel("                              ");
         JLabel lblInstructions = new JLabel("Select Manufacturer to Display Record");
         public static void main(String args[])
              //Declare an instance of this application
              JDBCApp thisApp = new JDBCApp();
              thisApp.createInterface();
         public void createInterface()
              //Load the database and set up the frame
              loadDatabase();
              if (blnSuccessfulOpen)
                   setTitle("Display Auto's Database");
                   addWindowListener(new WindowAdapter()
                             public void windowClosing(WindowEvent event)
                                  stop();
                                  System.exit(0);
                   setLayout(new FlowLayout());
                   add(new JLabel("Manufacturer"));
                   add(lstManuf);
                   lstManuf.addItemListener(this);
                   add(lblInstructions);
                   add(new JLabel("Model"));
                   add(lblModel);
                   add(new JLabel("Year"));
                   add(lblYear);
                   add(new JLabel("Cost"));
                   add(lblCost);
                   add(new JLabel("Vehicle Identification"));
                   add(lblID);
                   setSize(300,300);
                   setVisible(true);
              else
                   stop();             //Close any open connection
                   System.exit(-1);    //Exit with error status
              public void loadDatabase()
                   try
                        //Load the MicroSoft drivers
                        Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
                   catch (ClassNotFoundException err)
                             //No drivers found
                             System.err.println("Driver did not load properly");
                   try
                        //Connect to the database
                        conVehicle = DriverManager.getConnection("jdbc:odbc:Auto");
                        //Create a ResultSet
                        cmdVehicle = conVehicle.createStatement();
                        rsVehicle = cmdVehicle.executeQuery(
                                            "Select * from Vehicle;");
                        loadNames(rsVehicle);
                        blnSuccessfulOpen = true;
                   catch(SQLException error)
                        System.err.println("Error: " + error.toString());
         public void loadNames(ResultSet rsVehicle)
              try
                   //Fill last name list box
                   while(rsVehicle.next())
                   lstManuf.addItem(rsVehicle.getString("Manufacturer"));
              catch (SQLException error)
                   System.err.println("Error in display record");
         public void itemStateChanged(ItemEvent event)
              //Display the selected record
              lblInstructions.setText("");          String strManufName = lstManuf.getText();
              try
                   Statement cmdVehicle = conVehicle.createStatement();
                   ResultSet rsVehicle = cmdVehicle.executeQuery(
                        "Select * from Vehicle where [Manufacturer] = '" + strManufName + "';");
                   DisplayRecord(rsVehicle);
              catch(SQLException error)
                   System.err.println("Error in recordset");
          public void DisplayRecord(ResultSet rsVehicle)
               try
                   //Display information
                   if(rsVehicle.next()) //If more records remain
                        lblModel.setText(rsVehicle.getString("ModelName"));
                        lblYear.setText(rsVehicle.getString("Year"));
                        lblCost.setText(rsVehicle.getString("CostValue"));
                        lblID.setText(rsVehicle.getString("VehicleID"));
                   else
                        System.err.println("No more records");
              catch (SQLException error)
                   System.err.println("Error in display record");
         public void stop()
              try
                   //Terminate the connection
                   if (conVehicle != null)
                        conVehicle.close();
              catch(SQLException error)
                   System.err.println("Unable to disconnect");
    }

    I am going to help you out but first I would like to advise you not to do this.
    Mixing JDBC and Swing (or any GUI for that matter) like this is not the preferred way to proceed. If you want to learn JDBC then command line/shell is fine. If you want to learn Swing learn Swing. When you want to use the two together learn about MVC first.
    I am advising you to do this because nobody writes code like this (mixing GUI and database and business logic all in one class). So if you want real world training MVC should be what you look at next.
    See http://en.wikipedia.org/wiki/Model-view-controller for more
    As near as I can tell your problem is mostly just because you aren't using the combo box correctly. Try
    String strManufName = lstManuf.getSelectedItem().toString();it's a bit of a hack but will work for your purposes. What you need in the eend is to use the methods JComboxBox has like getSelectedItem() or getSelectedIndex().
    See http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html for more.
    Some other comments.
    1) It's nice to see you aren't just swallowing exceptions but some of them are kind of pointless if you just continue on. Like here
    try
      //Load the MicroSoft drivers
      Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
    catch (ClassNotFoundException err)
      //No drivers found
      System.err.println("Driver did not load properly");
    }And then you continue on with the method. What for? There's no point since the driver didn't load.
    2) Please look into the use of PreparedStatements. Very good things those. You can use them in place of your Statements. They are safer but for your purposes help you by you not having to worry about the formatting of data you bind to queries. For example what happens if a manufacturer name contains a ' (single quote) ? Trouble that's what. PreparedStatements make that problem go away.
    3) Don't use SELECT *. It is always good practice to put the names of the columns you are selecting. This prevents your code from breaking if the order of the columns should change in any way.

  • Changing AWT components to Swing components

    I'm having a little trouble changing some AWT components to Swing components. I received an error message when I tried to run my program. I looked up the component in the java docs. But, I did not see the option the error was talking about. The error and the area of code is listed below. Thank you for any help you can provide.
    Error message:
    Exception in thread "main" java.lang.Error: Do not use P5AWT.setLayout() use P5A
    WT.getContentPane().setLayout() instead
    at javax.swing.JFrame.createRootPaneException(JFrame.java:446)
    at javax.swing.JFrame.setLayout(JFrame.java:512)
    at P5AWT.<init>(P5AWT.java:56)
    at P5AWT.main(P5AWT.java:133)
    Press any key to continue . . .
    Code:
    JPanel p3 = new JPanel();
    p3.setLayout(new FlowLayout(FlowLayout.CENTER));
    ta = new JTextArea(20, 60);
    p3.add(ta);
    setLayout(new FlowLayout(FlowLayout.CENTER));
    add(p3);

    you need to change the line...
    setLayout(new FlowLayout(FlowLayout.CENTER)); to
    getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));

Maybe you are looking for

  • A/P Aging Report

    Hello Gurus, I am trying to get a report that will give me the aging of vendor open items in buckets, over 30, 60, 90, and 120 days. I think report S_ALR_87012085 will work, but I don't need the master data. How can I get teh same report or something

  • How to creating background

    Hi, 1)Iam still new to shake and i need you help. I have some footage which i want to put them over a white background.I have created the white background from Final cut Pro generators.You may have seen of what I am talking about on some music videos

  • 10.1.3 JMS Cache Synchronization on OC4J

    Hi, We're using stand-alone OC4j 10.1.3.0 along with TopLink 10.1.3.0 (packaged with OC4j). In enabling JMS cache synchronization, I get the following error message: Exception [TOPLINK-12000] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118

  • Using a mac and a PC with iphone 3g

    I have an iphone 3g i was using with my old apple powerbook g4 i just bought an new PC  and i want to update my phone using the PC it won't let me.  Can you use a new computer to update and backup iphone 3g?

  • Internet work but itunes report me error -3259

    I access the iTunes Store but I can not download itunes because it shows the error -3259 'timed out network', What can I do?