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));

Similar Messages

  • About the difference between the AWT components and the swing components

    As we know that an AWT component has a peer, but dose a lightweight component(e.g: a swing component) has also a peer? And could somebody tell me that who and how creates the CLICKED_EVENT when I click a JButton(a swing component), and where the CLICKED_EVENT to go util it was processed by a method like btn_ok_clicked(Event e)? And if I click a Button(an AWT component), what's the difference?
    Thanks a lot!

    The main difference is that AWT are native components, and Swing components are entirely in java written. That's besides the look and feel. There are a lot of other differences between AWT and Swing, and there are better described in the documentation.

  • GetTreeLock during constructor for swing components

    I've noticed some dead locks in our application that are showing up in the call to getTreeLock that exists in the constructor for various JComponents. Specifically, the updateUI method winds up calling validateTree.
    I thought it was OK to construct JComponents from any thread, this suggests it is not.
    Has anyone else experienced this?

    It goes like this:
    On win32, thread 0 is our windows message pump. If dispatching one of our messages results in a call from C into Java that constructs a JComponent, we call getTreeLock from thread 0.
    Imagine that at the same time, the awt event disptatch thread is trying to show a frame. Since the awt event dispatch thread is part of our process, when the native implemention of the frame calls SendMessage to show the frame, the call to SendMessage blocks until thread 0 calls GetMessage.
    Since thread 0 is now blocking waiting for synchronized(getTreeLock()) to return and the awt event dispatch thread has the tree lock - fetched while executing the show() method - we are in a dead lock.
    This is not a problem with AWT components, only swing components.
    The stack looks like this:
         at java.awt.Component.getTreeLock(Component.java:811)
         at java.awt.Container.invalidateTree(Container.java:1116)
         at java.awt.Container.setFont(Container.java:1148)
         at javax.swing.JComponent.setFont(JComponent.java:2310)
         at javax.swing.LookAndFeel.installColorsAndFont(LookAndFeel.java:89)
         at javax.swing.plaf.basic.BasicButtonUI.installDefaults(BasicButtonUI.java:124)
         at com.sun.java.swing.plaf.windows.WindowsButtonUI.installDefaults(WindowsButtonUI.java:63)
         at javax.swing.plaf.basic.BasicButtonUI.installUI(BasicButtonUI.java:60)
         at javax.swing.JComponent.setUI(JComponent.java:449)
         at javax.swing.AbstractButton.setUI(AbstractButton.java:1616)
         at javax.swing.JButton.updateUI(JButton.java:119)
         at javax.swing.AbstractButton.init(AbstractButton.java:1952)
         at javax.swing.JButton.<init>(JButton.java:109)
         at javax.swing.JButton.<init>(JButton.java:64)
    It seems like we could simply have the invalidateTree method return early if there is no parent or there are no children or somesuch.
    A work around we've done is to have the updateUI method delegate to the event dispatch thread. This is a drag as we need to subclass all the JComponents and make sure developers use the safe subclass.

  • Using of JLoox components in Swing/AWT Paint

    I am facing problem in using JLoox components in Swing/AWT Paint method.I am able to use the JLoox components in Constructor of Swing JFrame and facing problem while using the JLoox components in Paint method.If anybody used JLoox please suggest the way to use it.

    Yes I have used JLOOX since last 2 years.
    There is a LxGraph derived from LxAbstract and LxView derived from LxAbstractView. This LxAbstractView is in turn derived from JComponent. LxGraph is a model for LxView (same apporch like MVC). You create components (i.e. LxRectangle, LxCircle, LxLine, LxLink, etc) and add it to either graph or in view). Finally this view (i.e. LxView) is added to a java container (JPanel, JScrollBar, etc.) You cannot pass JLoox component into JFrame constructor.
    -regards,
    Pratap

  • Catching events on Desktop , without using any AWT or Swing components.

    How can I catch events(for eg: mouse clicks) on the Desktop? I do not want to use any AWT or Swing components in my application.
    Also, i want to get events even some other java/non-java application windows are visible on desktop, as long as my application is running.

    Myrequirement is to capture all AWT events, regardless of on which component its being happened.
    I mean I have to capture events outside the current running application (on desktop and any other java/no-java appliation windows also).
    I couldn't find any other forum which discusses about event handling.
    This is part of my app. other end extensively uses awt.

  • 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>

  • 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.

  • 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.

  • 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();
    }

  • 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

  • Swing Components not displaying in a JFrame

    Hi,
    I have a JFrame with a couple of JLabels, JButtons etc. and a Choice Combo Box
    my problem is that when i run the program the only component that gets displayed at first is Choice and in order for me to see the swing components i have to roll over them with my mouse and the JLabels dont even display when i do that..
    Does anyone know how i can fix this please?
    here is my code
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.awt.Image.*;
    import java.io.*;
    import java.net.*;
    public class ImageViewerAnim extends JFrame {
         private JLabel perc, scale;
         private JTextField inPercent;
         private JButton draw, muteOn;
         private JPanel sPanel;
         private String[] pics = {"Earth", "Moon", "Jupiter", "Pluton", "Neptun"};
         private String[] picsFile = {"images/earth.gif", "images/moon.gif", "images/jupiter.jpg", "images/pluton.jpg", "images/neptun.jpg"};
         private String[] soundsFile = {"sounds/tada.wav", "sounds/notify.wav", "sounds/ding.wav", "sounds/chimes.wav", "sounds/chimes.wav"};
         private Choice ch;
         private Image pic;
         private AudioClip sound = null;
         private int scaleAm = 0;
         private int origScale = 500;
         private int finalScale = 0;
         private boolean proceed = true;
         public ImageViewerAnim() {
              Container c = getContentPane();
              c.setLayout(new BorderLayout());
              sPanel = new JPanel();
              ch = new Choice();
              for(int i = 0; i < pics.length; ++i) {
                   ch.add(pics);
              scale = new JLabel("Scale");
              perc = new JLabel("%");
              inPercent = new JTextField(5); // scale value input field
              draw = new JButton("Draw");
              draw.setBorder(BorderFactory.createEtchedBorder());
              draw.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        int index = 0;
                        index = ch.getSelectedIndex();
                        pic = null;
                        repaint();
                        pic = (Toolkit.getDefaultToolkit().getImage(picsFile[index]));
                        try{
                        File f = new File(soundsFile[index]);
                        sound = Applet.newAudioClip(f.toURL());
                        }catch(MalformedURLException mfe) {
                             mfe.printStackTrace();
                        if(!inPercent.getText().equals("")) {
                             scaleAm = Integer.parseInt(inPercent.getText()); // get the scale amount from the user
                             finalScale = ((origScale * scaleAm)/100); // calculate the final scale amount based on what the user entered
                        }else {
                             finalScale = origScale; // default to original size of the image if no value for scale was entered
                        // creates a scaled instance of an image and takes the amount of scale as an argument
                        repaint();
                        sound.loop();
              muteOn = new JButton("Mute On");
              muteOn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        sound.stop();
                        muteOn.setText("MuteOff");
              sPanel.add(ch);
              sPanel.add(scale);
              sPanel.add(inPercent);
              sPanel.add(perc);
              sPanel.add(draw);
              sPanel.add(muteOn);
              c.add(sPanel, BorderLayout.SOUTH);
              repaint();
    public void paint(Graphics g) {
         if(pic!=null) {
              g.drawImage(pic,0,0,this);
    public static void main(String args[]) {
         ImageViewerAnim app = new ImageViewerAnim();
         app.setSize(500,500);
         app.setVisible(true);
         app.setDefaultCloseOperation(EXIT_ON_CLOSE);
         app.show();
    thank you in advance
    Ivo

    for future reference
    i was able to fix this by adding
    super.paint(g);in the first line of my paint method
    Ivo

  • Issue viewing Swing components

    I currently am able to compile, but not view Swing components. I am running Windows Media Center Edition with Radeon X300 graphics card. Swing programs execute but I only see the border window with only grey content inside. I have 1gb of memory and have tried running very small applications with the same effect. Does Java not support my OS? Any ideas?

    Some sample code follows that doesn't work for me
    At odd times I can see some of the swing applications I try to run, but it isn't consistent. This makes me think it is a memory problem, but I'm not sure. The following application takes 19,040 K with 373688 K available physical memory.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DefaultButton {
    public static void main(String args[]) {
    Runnable runner = new Runnable() {
    public void run() {
    JFrame frame = new JFrame("DefaultButton");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(2, 2, 10, 10));
    JButton button1 = new JButton("Text Button");
    button1.setMnemonic(KeyEvent.VK_B);
    frame.add(button1);
    Icon warnIcon = new ImageIcon("Warn.gif");
    JButton button2 = new JButton(warnIcon);
    frame.add(button2);
    JButton button3 = new JButton("Warning", warnIcon);
    frame.add(button3);
    String htmlButton = "<html><sup>HTML</sup> <sub><em>Button</em></sub><br>" +
    "<font color=\"#FF0080\"><u>Multi-line</u></font>";
    JButton button4 = new JButton(htmlButton);
    frame.add(button4);
    JRootPane rootPane = frame.getRootPane();
    rootPane.setDefaultButton(button2);
    frame.setSize(300, 200);
    frame.setVisible(true);
    EventQueue.invokeLater(runner);
    }

  • Trying to understand "thread-safe" w/ swing components

    The other day there was a big hullabaloo about some code I posted because I was calling JLabel.setText from a thread that wasn't the ui thread. On the other hand, this thread was the only thread making changes to the JLabel. My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?
    Second question - JLabel.setText() is essentially setting data in the model for JLabel, which then gets picked up and displayed the next time the GUI thread paints it. So if it's not safe to update a JLabel's model, I assume its never safe to update any data that also is being displayed visually. So for instance, if I was showing some database table data in a JTable, I should do the update in the UI thread - probably not. But what is the distinction?
    Third question - what swing components and what operations need to be run on the UI thread to call your program "thread-safe". Validate? setSize()? setLocation()? add? remove? Is there anything that can be called on swing components from a non-ui thread?
    Edited by: tjacobs01 on Nov 2, 2008 8:29 PM

    tjacobs01 wrote:
    My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?This is not true. As I mentioned in that hullabaloo thread, the Java Memory Model allows threads to cache values of variables they use. This means that values written by one thread are not guaranteed to ever be visible to other threads, unless you use proper synchronization.
    Take the following example:
    import java.util.concurrent.TimeUnit;
    public class ThreadExample {
        static class Foo {
            private String value = "A";
            public String getValue() {
                return value;
            public void setValue(String value) {
                this.value = value;
        public static void main(String[] args) {
            final Foo foo = new Foo();
            Thread writer = new Thread() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        foo.setValue("B");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            Thread reader = new Thread() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MINUTES.sleep(1);
                        System.out.println(foo.getValue());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            writer.start();
            reader.start();
    }Here two different threads both access the same Foo instance, which is initialized with a value of "A". One thread, the writer, sleeps one second, and then sets foo's value to "B". The other thread, the reader, sleeps one minute (to avoid race conditions) and then prints foo's value to System.out. It may seem obvious that the reader thread will read the value "B", but this is in fact not guaranteed to be true. The reader thread may never see the value that was written by the writer thread, so it may very well read the old value "A".
    (If you run the code you will probably see "B" printed out, but again, this is not guaranteed behavior.)
    A simple way to fix this is to synchronize access to the mutable state that the two threads share. For example, change the class Foo to
        static class Foo {
            private String value = "A";
            public synchronized String getValue() {
                return value;
            public synchronized void setValue(String value) {
                this.value = value;
        }It's for this same reason that you often see the use of a volatile boolean as a control flag for stopping threads, rather than a plain old boolean. The use of volatile guarantees that the thread you want to stop actually sees the new value of the flag once it has been set by another thread.
    Here is an article that touches some of this stuff:
    [http://www.ibm.com/developerworks/java/library/j-jtp02244.html]
    I also highly recommend the book "Java Concurrency in Practice" (one of the authors of which, David Holmes, sometime hangs out on the Concurrency forum here, I believe).
    Edited by: Torgil on Nov 2, 2008 9:01 PM

  • 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

  • Swing Components and Fullscreen Exclusive

    Hi, I am trying to write a program that can switch between full screen and windowed mode seamlessly, while still being able to use standard swing components. I have never worked with the full screen exclusive mode before and am having trouble getting the components to repaint properly.
    The following code works fine in the windowed and undecorated modes, however when I switch to fullscreen exclusive mode all components disappear and only repaint upon mouseover or other interaction. Calls to repaint do not make any difference.
    import java.awt.Dimension;
    import java.awt.DisplayMode;
    import java.awt.FlowLayout;
    import java.awt.GraphicsDevice;
    import java.awt.GraphicsEnvironment;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.WindowConstants;
    public class FullscreenTests {
         private static boolean hwlast = false;
         private static GraphicsDevice dev = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
         public static void main(String[] args) {
              final JFrame fMain = new JFrame("Title");
              fMain.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              fMain.getRootPane().setLayout(new FlowLayout());
              JButton win = new JButton("Windowed");
              win.addActionListener(new ActionListener () {
                   public void actionPerformed (ActionEvent e) {
                        setWindowed(fMain);
              fMain.getRootPane().add(win);
              JButton ful = new JButton("Fullscreen");
              ful.addActionListener(new ActionListener () {
                   public void actionPerformed (ActionEvent e) {
                        setFullscreen(fMain);
              fMain.getRootPane().add(ful);
              JButton hw = new JButton("HW Fullscreen");
              hw.addActionListener(new ActionListener () {
                   public void actionPerformed (ActionEvent e) {
                        setHWFullscreen(fMain);
              fMain.getRootPane().add(hw);
              setWindowed(fMain);
         public static void setWindowed(JFrame f) {
              if (hwlast == true) {
                   dev.setFullScreenWindow(null);
                   hwlast = false;
              f.dispose();
              f.setIgnoreRepaint(false);
              f.setUndecorated(false);
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              f.setSize(new Dimension(808,634));
              f.setMinimumSize(new Dimension(808,634));
              f.setLocation((d.width-f.getWidth())/2, (d.height-f.getHeight())/2);
              f.setVisible(true);
         public static void setHWFullscreen(JFrame f) {
              hwlast = true;
              f.dispose();
              f.setUndecorated(true);
              f.setIgnoreRepaint(true);
              f.setVisible(true);
              dev.setFullScreenWindow(f);
              dev.setDisplayMode(new DisplayMode(800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN));
         public static void setFullscreen(JFrame f) {
              if (hwlast == true) {
                   dev.setFullScreenWindow(null);
                   hwlast = false;
              f.dispose();
              f.setIgnoreRepaint(false);
              f.setUndecorated(true);
              f.setSize(Toolkit.getDefaultToolkit().getScreenSize());
              f.setLocation(0,0);
              f.setVisible(true);
    }On the same note, if there are better ways of doing this I would be glad to know. This is just a quick test so I haven't done any checks etc when switching to fullscreen exclusive.

       public static void setHWFullscreen (JFrame f) {
          hwlast = true;
          f.dispose ();
          f.setUndecorated (true);
          f.setIgnoreRepaint (true);
          // add this
          Graphics g = f.getGraphics ();
          f.paintAll (g);
          f.setVisible (true);
          dev.setFullScreenWindow (f);
          dev.setDisplayMode (new DisplayMode (800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN));
       }db

Maybe you are looking for