Flowlayout question

hi everyone...i have a panel that have a flow layout and a scroll pane attached to it and i also have a button that when pressed, a component is added to the panel...my problem is that when i press the button, the components are added fine but when there is no more place on the line, the components are not placed on the second line even though i have a scroll pane and a flow layout....
please help
here are the three classes needed to show the problem
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class GUI extends JFrame implements ActionListener {
    public GUI() {
        initializeGUI();
    public void initializeGUI() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(true);
        setTitle("DVD");
        setSize(1000, 700);
        setLocation(20, 20);
        JTabbedPane tp = new JTabbedPane(JTabbedPane.LEFT);
        getContentPane().add(tp);
        tp.addTab("Rent Page", new MultipleRentGUI());
    public static void main(String[] args) {
        new GUI().setVisible(true);
     * Invoked when an action occurs.
    public void actionPerformed(ActionEvent e) {
    ActionListener BackupListener = new ActionListener() {
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MultipleRentGUI extends JPanel implements ActionListener, GUIConstants {
    private JRadioButton id = new JRadioButton("Customer ID", true);
    private JRadioButton name = new JRadioButton("Customer name");
    private JLabel label = new JLabel("Customer ID: ");
    private JTextField cust = new JTextField(10);
    private JButton rent = new JButton("Rent");
    private JButton reset = new JButton("Reset");
    private JButton add = new JButton("Add");
    private JButton remove = new JButton("Remove");
    private JPanel bPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    private JPanel lPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    private JPanel b2Panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    private JPanel tPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    private JPanel b3Panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    private JPanel nPanel = new JPanel();
    private ArrayList<MultipleTitleRentGUI> titles = new ArrayList<MultipleTitleRentGUI>();
    private int count = 0;
    private Calendar c = Calendar.getInstance();
    private final int FONT_SIZE = 15;
    private Font f = new Font("Times New Roman", Font.BOLD, FONT_SIZE);
    private Font borderFont = new Font("Times New Roman", Font.BOLD, FONT_SIZE + 5);
    public MultipleRentGUI() {
        setupComponents();
        setupFonts();
        setupButtons();
        initializeGUI();
    public void setupFonts() {
        id.setFont(f);
        name.setFont(f);
        rent.setFont(f);
        reset.setFont(f);
        cust.setFont(f);
    public void setupComponents() {
        Border b = BorderFactory.createLoweredBevelBorder();
        this.setBorder(BorderFactory.createTitledBorder(b
                , "Multiple Rent Page"
                , TitledBorder.DEFAULT_JUSTIFICATION
                , TitledBorder.DEFAULT_POSITION
                , borderFont
                , Color.blue));
        cust.setBorder(BorderFactory.createLoweredBevelBorder());
        nPanel.setLayout(new BoxLayout(nPanel, BoxLayout.Y_AXIS));
    public void initializeGUI() {
        rent.setEnabled(true);
        reset.setEnabled(false);
        ButtonGroup bg = new ButtonGroup();
        bg.add(id);
        bg.add(name);
        setLayout(new BorderLayout());
        add(nPanel, BorderLayout.NORTH);
        bPanel.add(id);
        bPanel.add(name);
        nPanel.add(bPanel);
        lPanel.add(label);
        lPanel.add(cust);
        nPanel.add(lPanel);
        b2Panel.add(add);
        b2Panel.add(remove);
        nPanel.add(b2Panel);
        JScrollPane sp = new JScrollPane(tPanel
                , JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
                , JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        add(sp, BorderLayout.CENTER);
        b3Panel.add(rent);
        b3Panel.add(reset);
        add(b3Panel, BorderLayout.SOUTH);
    public void setupButtons() {
        rent.addActionListener(this);
        rent.setActionCommand("rent");
        reset.addActionListener(this);
        reset.setActionCommand("reset");
        id.addActionListener(this);
        id.setActionCommand("id");
        name.addActionListener(this);
        name.setActionCommand("name");
        add.addActionListener(this);
        add.setActionCommand("add");
        remove.addActionListener(this);
        remove.setActionCommand("remove");
    public void resetFields() {
        rent.setEnabled(true);
        reset.setEnabled(false);
        id.setSelected(true);
        cust.setText("");
        label.setText("Customer ID: ");
    public Box addComponent(Component c1, Component c2, int spacing) {
        return null;
     * Invoked when an action occurs.
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equalsIgnoreCase("id")) {
            label.setText("Customer ID: ");
        if (e.getActionCommand().equalsIgnoreCase("name")) {
            label.setText("Customer Name: ");
        if (e.getActionCommand().equalsIgnoreCase("reset")) {
            resetFields();
        if (e.getActionCommand().equalsIgnoreCase("add")) {
            titles.add(new MultipleTitleRentGUI());
            tPanel.add(titles.get(count));
            count++;
            revalidate();
        if (e.getActionCommand().equalsIgnoreCase("remove")) {
            if (count == 0) {
                return;
            } else {
                tPanel.remove(titles.get(count - 1));
                titles.remove(count - 1);
                count--;
                tPanel.revalidate();
                tPanel.repaint();
        if (e.getActionCommand().equalsIgnoreCase("rent")) {
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class MultipleTitleRentGUI extends JPanel implements ActionListener {
    private JLabel title = new JLabel("Title Barcode: ");
    private JTextField barcode = new JTextField(5);
    private JRadioButton reg = new JRadioButton("Regular price", true);
    private JRadioButton half = new JRadioButton("Half price");
    private JRadioButton free = new JRadioButton("Free of Charge");
    private int fee = getRentFee();
    private JPanel text = new JPanel(new FlowLayout(FlowLayout.LEFT));
    private JPanel buttons = new JPanel();
    private final int FONT_SIZE = 15;
    private Font f = new Font("Times New Roman", Font.BOLD, FONT_SIZE);
    private Font borderFont = new Font("Times New Roman", Font.BOLD, FONT_SIZE + 5);
    public MultipleTitleRentGUI() {
        setupButtons();
        setupComponents();
        initializeGUI();
    private void initializeGUI() {
        setLayout(new BorderLayout());
        setSize(50, 60);
        ButtonGroup bg = new ButtonGroup();
        bg.add(reg);
        bg.add(half);
        bg.add(free);
        text.add(title);
        text.add(barcode);
        add(text, BorderLayout.NORTH);
        buttons.add(reg);
        buttons.add(half);
        buttons.add(free);
        add(buttons, BorderLayout.CENTER);
    private void setupButtons() {
        reg.setFont(f);
        half.setFont(f);
        free.setFont(f);
        reg.addActionListener(this);
        reg.setActionCommand("regular");
        half.addActionListener(this);
        half.setActionCommand("half");
        free.addActionListener(this);
        free.setActionCommand("free");
    private void setupComponents() {
        Border b = BorderFactory.createLoweredBevelBorder();
        this.setBorder(BorderFactory.createTitledBorder(b
                , "Title"
                , TitledBorder.DEFAULT_JUSTIFICATION
                , TitledBorder.DEFAULT_POSITION
                , borderFont
                , Color.blue));
        barcode.setBorder(BorderFactory.createLoweredBevelBorder());
        buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS));
    public String getBarcode() {
        return barcode.getText();
    public int getFee() {
        return fee;
    private int getRentFee() {
        int cost = 0;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/dvd", "root", "swordfrogy");
            String sql = "SELECT rent " +
                    "FROM fees";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                cost = rs.getInt("rent");
        } catch (InstantiationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        return cost;
     * Invoked when an action occurs.
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equalsIgnoreCase("regular")) {
            fee = getRentFee();
        if (e.getActionCommand().equalsIgnoreCase("half")) {
            fee = getRentFee() / 2;
        if (e.getActionCommand().equalsIgnoreCase("free")) {
            fee = 0;
}

Sorry, I've just read the question more carefully :)
FlowLayout will add the component on a second line if it runs out of space on the first. That's not the cause of the problem.
However, this container is in a scroll pane. That means it will never run out of space. The layout manager is still adding components to the first line - it's just that they can't be seen because you've suppressed the horizontal scroll bar.
Note that suppressing the scroll bar does just that: it doesn't restrict the size of the component in the viewport.
If you want to check that that's what happening, add a println() after your revalidate() call to dump the preferred size of the container - you should see it growing horizontally.
In order to make the components flow as you intend, the solution I use is an extension of JViewport which uses its own custom layout manaer.
There may be an easier solution but I didn't find one before I wrote that and I've stuck with it ever since.

Similar Messages

  • Why FlowLayout - JPane will NOT auto adjust in size?

    Hello java friends,
    I don't understand why my little demo program's JPane(use FlowLayout manager) will not adjust the size correctly. When run, I see one row of buttons, which only show 11 of them; the rest are shown on secon row which only visible if I go resize the window. Why is that? Wouldn't FlowLayout manager will auto size the pane? My main frame used the pack() method, so it's up to the pane's preferredsize. Please give me some ideas. Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Template {
        public static void main(String[] args) {
             JFrame mainFrame =new JFrame("Template");
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainFrame.setContentPane(new TemplatePane());
            //Display the window.
            mainFrame.pack();
            mainFrame.setVisible(true);
    class TemplatePane extends JPanel
              implements ActionListener {
         JButton componentAry[] =new JButton[100];
         TemplatePane() {
              this.setLayout(new FlowLayout());
              for(int i=0; i<componentAry.length; i++) {
                   componentAry[i] =new JButton("Test#"+i);
                   componentAry.addActionListener(this);
                   this.add(componentAry[i]);
         public void actionPerformed(ActionEvent ae) {
              System.out.println(ae.getActionCommand());

    I did read the API doc:
    >>>>
    A flow layout arranges components in a left-to-right flow, much like lines of text in a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line. Each line is centered.
    >>>>
    My question is why won't it adjust the pane size if the there is more than one line? It did draw the second line for things that won't fit in the first line... just not visible unless the whole window is resized to a bigger view. Can you please provide an explanation?

  • More JTextPane Questions

    Hi Guys
    I posted this question on the Java Ranch forums yesterday evening, but I haven't received a response yet, so I figured that I'd try these forums as well. You can view the other thread here; http://www.coderanch.com/t/554155/GUI/java/JTextPane-Questions.
    We're trying to build a simple WYSIWYG HTML editor using a JTextPane. I've used Charles Bell's example, available here; http://www.artima.com/forums/flat.jsp?forum=1&thread=1276 as a reference. My biggest gripe with it at the moment is that bullets aren't working as I would expect them to. If I highlight text and click the "Bullet" button, I want a bullet to be placed immediately before the highlighted text, on the same line. If I try to do this, my code is creating bullets, but it moves the selected text one line down. I've gone through the Oracle tutorial on text components, but I couldn't find anything that helped me with this particular issue.
    Also, if I copy and paste text into my JTextPane, the pasted text always appears on a new line (a new paragraph tag in the actual HTML). Is there a way to prevent the JTextPane from creating new paragraphs?
    Lastly, I'm flabbergasted as to why my buttons actually work. I can't see anything that explicitly links my buttons to my HTMLEditorKit or my JTextPane. Short of a little voodoo man living under my keyboard, how on earth do my buttons/actions know that they should update the JTextPane?
    The code is as follows;
    package myhtmleditor;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.html.HTML;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class Main {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("My HTML Editor");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(500, 500);
                    frame.setLayout(new BorderLayout());
                    JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                    HTMLDocument document = new HTMLDocument();
                    final JTextPane htmlEditorPane = new JTextPane(document);
                    Action bold = new StyledEditorKit.BoldAction();
                    Action italic = new StyledEditorKit.ItalicAction();
                    Action underline = new StyledEditorKit.UnderlineAction();
                    JButton boldButton = new JButton(bold);
                    boldButton.setText("Bold");
                    buttonsPanel.add(boldButton);
                    JButton italicButton = new JButton(italic);
                    italicButton.setText("Italic");
                    buttonsPanel.add(italicButton);
                    JButton underlineButton = new JButton(underline);
                    underlineButton.setText("Underline");
                    buttonsPanel.add(underlineButton);
                    HTMLEditorKit.InsertHTMLTextAction bulletAction = new HTMLEditorKit.InsertHTMLTextAction("Bullet", "<ul><li> </li></ul>", HTML.Tag.BODY, HTML.Tag.UL);
                    JButton bulletButton = new JButton(bulletAction);
                    bulletButton.setText("Bullet");
                    buttonsPanel.add(bulletButton);
                    JButton printButton = new JButton("Print to Console");
                    printButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println(htmlEditorPane.getText());
                    buttonsPanel.add(printButton);
                    htmlEditorPane.setContentType("text/html");
                    HTMLEditorKit editorKit = new HTMLEditorKit();
                    htmlEditorPane.setEditorKit(editorKit);
                    frame.add(buttonsPanel, BorderLayout.NORTH);
                    frame.add(new JScrollPane(htmlEditorPane), BorderLayout.CENTER);
                    frame.setVisible(true);
    }Thank you for your input.
    Cheers,
    rfnel

    See how the bullet action changes HTML (compare getText() result before and after the bullet applying. It seems you need more smart way of adding bullets.
    Answer some questions if user selects whole paragraph should the <p> tag be removed and replaced with <li>? If user selects just one word in the paragraph and pressed bullet should the whole paragraph be bulleted?
    When you copy something you clipboard contains something like this "<html><body> content</body></html>". Try to override read() method of your kit (or Reader) to skip the main tags.
    For components see ObjectView class source.
    In fact when HTMLDocument is created from String components classes are created and stored in attributes of Elements. Then during rendering ComponentView extension (ObjectView) creates components.

  • The Vertical FlowLayout that doesn't Exist?

    Ok, I've looked through the forum, and checked on a popular search engine, and it seems to me that there is no such thing as a vertically oriented FlowLayout. But why not? Is it difficult/impossible to implement? Please, someone, explain.
    Some suggested solutions to this involve using a vertical BoxLayout, but that just seems ugly, what with the way components get stretched to fit the entire height of the window. Of course one can set the maximum sizes of the components and so on, but it seems to me that that's just making things more complicated than (I think) they ought to be. And to make matters worse the components are all crushed together with no gaps in between..
    Surely a LayoutManager that stacks components vertically at their preferred sizes by default would be a fundamentally useful thing?
    Well anyway... not much of a question (more of a moan), never-the-less, if anyone knows why a vertical FlowLayout doesn't exist as standard please let me know... Then later I'll have a moan about the GridLayout asking why it doesn't keep each row and column only as tall and as wide as it needs to be.
    Regards
    -- Mick

    and it seems to me that there is no such thing as a vertically oriented FlowLayoutCheck out the [Relative Layout|http://www.camick.com/java/blog.html?name=relative-layout]. I know from the name you would never guess it could do a vertical FlowLayout, but it turned out to be far more flexible than I ever imagined it would be. In your case the code would be something like:
    RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS, 5);
    //rl.setAlignment(RelativeLayout.LEADING);
    rl.setAlignment(RelativeLayout.CENTER);
    JPanel panel = new JPanel( rl );
    panel.add(component1);
    panel.add(component2);
    ...

  • Panels to be displayed when clicking on a button: general question

    Hi there,
    I want to design a GUI that will look something like:
    | |
    | |
    | |
    | |
    | |
    | |
    | |
    | |
    | |
    | |
    | |
    | A | B | C | D | E | F |
    That should be two panels:
    - bottom panel: just a some buttons (A, B, C...)
    - top panel: to start with, it'll be empty/blank, but when a button is pressed, some content should be displayed (buttons, labels, etc)
    So, my idea was to have a main UI class, where I would have both panels; and for each different button I'd also have a different class. These classes should just display their own panel within the "top panel".
    And that's what I'm not getting.
    In the main UI class, I wrote some instances for each possible class that I'd be calling. And each class would have a constructor:
    UITesting(Panel aPanel, String aWord)
    Where aPanel is the top panel from the main UI, and aWord just a word to display in a lable for example (just testing purposes).
    My question:
    how do I make visible panelA when I press the buttonA and so on?
    Anybody knows where I could find a similar example or tutorial?
    Thanks!

    Try using a Card Layout.
    Giving an Example with two buttons.
    ====================================
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TestDialog extends JDialog
         private JPanel p3 = new JPanel();
         private CardLayout cd = new CardLayout(0,0);     
         public TestDialog()
              init();
         public static void main(String[] args)
              System.out.println("Hello World!");
              TestDialog t = new TestDialog();
              t.setSize(200,200);
              t.pack();
              t.setVisible(true);
         private void init()
              JPanel p1 = (JPanel)this.getContentPane();
              p1.setLayout(new BorderLayout(0,0));
              JPanel p2 = new JPanel();
              JButton b1 = new JButton("Button1");
              JButton b2 = new JButton("Button2");
              p2.setLayout(new FlowLayout(FlowLayout.CENTER, 0,0));
              p2.add(b1);
              p2.add(b2);
              p1.add(BorderLayout.SOUTH, p2);
              p1.add(BorderLayout.CENTER, p3);
              p3.setLayout(cd);
              JPanel p4 = new JPanel();
              JPanel p5 = new JPanel();
              p4.add(new JLabel("Panel1"));
              p5.add(new JLabel("Panel2"));
              p3.add("Card1", p4);
              p3.add("Card2", p5);
              cd.show(p3, "Card1");
              b1.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        cd.show(p3, "Card1");
              b2.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        cd.show(p3, "Card2");

  • JFileChooser question

    Hey Guys,
    My First post on the sun forums, so a big hello to you guys. I have a question in relation to best practice in querying something in one user interface, of another user interface. Suppose i have a class that consists on a TextField,JButton, and a JButton which opens a JFileChooser; i would like to return the value of the JTextField from the second GUI class to a calling gui class (gui1), once the OK button has been pressed. The second gui class consists of the following.
    package UserInterface;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    Class that allows for a local file to be chosen
    @author pthug
    public class ImageChooser extends JFrame {
    private JButton okButton;
    private JButton chooseFileButton;
    private JTextField locationTextField;
    private JPanel mainPanel;
    private JPanel locationPanel;
    private JFileChooser fc;
    private String address;
    //default constructor
    public ImageChooser() {
    super("Image Chooser");
    //set default size
    setSize(new Dimension(450,250));
    setResizable(false);
    //create components
    initComponents();
    //set layout - top to bottom
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
    locationPanel.setLayout(new FlowLayout());
    //add components to frame
    addComponents();
    //pak components
    pack();
    //centre frame on screen
    setLocationRelativeTo(null);
    //close frame as default operation
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    //add action listeners to components
    createActionListeners();
    //show frame
    setVisible(true);
    //*adds all components*
    *private void addComponents() {*
    *locationPanel.add(locationTextField);*
    *locationPanel.add(chooseFileButton);*
    *mainPanel.add(locationPanel);*
    *mainPanel.add(okButton);*
    *this.add(mainPanel);*
    *//*create the components for interface
    private void initComponents() {
    okButton = new JButton("OK");
    chooseFileButton = new JButton("...");
    locationTextField = new JTextField(50);
    mainPanel = new JPanel();
    locationPanel = new JPanel();
    fc = new JFileChooser();
    address = new String("");
    //create action listeners for components
    private void createActionListeners() {
    //open File Choose Dialog
    chooseFileButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == chooseFileButton) {
    int returnVal = fc.showOpenDialog(ImageChooser.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    locationTextField.setText(file.getPath());
    } else {
    System.out.println("Open command cancelled by user." + "\n");
    //ok button action listener
    okButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    address = locationTextField.getText();
    //some more methods that determine if a web address has been typed in the JTextField or whether a
    //local file has been chosen using the JFileChooser which has not been written yet
    //@param args
    public static void main(String[] args) {
    ImageChooser co = new ImageChooser();
    }and a call the class from a the first gui class as such
    GUI 1
    addImageItem.addActionListener(new ActionListener() {
                 @Override
                      public void actionPerformed(ActionEvent arg0) {
                           imageChooser = new ImageChooser();
    ... remaining source of class remove as its not necessary to the questionhow can i query when the ok button has been pressed on the second gui class, so that the first gui knows when to take the value from the JTextField. Would i just put a method in the second gui which is a boolean that holds true or false whether its ok to take the value from the JTextField and query it like such...
    //                       while(imageChooser.isStillOpen()) {
    //                       }Hope that makes sense.
    Regards,
    KevJ
    Edited by: KevJ on 10-Nov-2009 17:05

    Thank you for your reply bharath.bravo, that has solved my question. Which i did as such, i provided a method in the second GUI class to enable me to add an ActionListener to the OK button. As such
          * this method allows other classes to add their action listeners to
          * the OK Button
          * @param e Action Listener from another class
         public void addActionToOKButton(ActionListener e) {
              okButton.addActionListener(e);
         }     I then added a accessor method, to get the value from the textfield; which i've implemented it as such:
    imageChooser.addActionToOKButton(new ActionListener() {
                                  @Override
                                  public void actionPerformed(ActionEvent arg0) {
                                                                                                                    //use imageChooser accessor method to get the value from the text field
                                       imageLocation = imageChooser.getLocationTextField();
                                                                                                                    //DEBUG statement
                                       System.out.println("gui one recieved: " + imageLocation);
                                                                                                                    //get rid of imageChooser window
                                       imageChooser.dispose();
                                  }For the sake of clarity, in your first suggestion. You mentioned that i could implement the WindowListener Interface in the first gui, and add it as a Listener to the second gui. Would i do that like this, and what would be a prefferable way of doing this out of the two methods you suggested.
    public class GUI extends JFrame implements WindowListener
         @Override
         public void windowClosed(WindowEvent arg0) {
              // TODO Auto-generated method stub
              //get value of jTextField using its public accessor method          
    add window listener to second gui, from the first GUI
    imageChooser.addWindowListener(this);Regards,
    KevinJ
    Edited by: KevJ on 11-Nov-2009 14:38

  • Setting Up a GUI - FlowLayout - Using Two JPanels

    Hello:
    I am getting confused with setting up a GUI with two JPanels one that would be on top and the other middlePanel having a FlowLayout.
    I set up two JPanels but obviously have something wrong because my northPanel has "disappeared" when I added a middlePanel. My componets are all over the place and again my northPanel is no longer showing.
    Idea of what I'm doing.
    1) Enter total number of diners
    2)Confirm that diners # is correct.
    3)Enter name of Diner
    4)Take order - Entree (Pull-Down)
    5)Two sides (CheckBox)
    6)Display Completed Order of diners.
    P.S. I hope my question is not too stupid I am new and has justed started Java Programming. I have tried to look through the Documentation but am getting confused with GUI relating to FlowLayout, GridLayout. etc. I'm just not sure which one I should use to set up my GUI in an organized manner. Am I on the right track or is my code completely screwed. Thanks.
    ** My Code **
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Menu extends JFrame {
    private JTextField partyNumField, dinerName;
    private JComboBox orderComboBox;
    private int partyNum;
    private JButton getParty, continueOrder;
    private JLabel party, companyLogo, dinerLabel, entreeOrder;
    private String dinnerEntree[] = {"Filet Mignon", "Chicken Cheese Steak", "Tacos", "Ribs"};
    private JCheckBox mashed, cole, baked, french;
    public Menu() {
    super("O'Brien Caterer - Where we make good Eats!");
    Container container = getContentPane();
    JPanel northPanel = new JPanel();
    northPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 80, 5));
    companyLogo = new JLabel("Welcome to O'Brien's Caterer's");
    northPanel.add(companyLogo);
    party = new JLabel("Enter the Total Number in Party Please");
    partyNumField = new JTextField(5);
    northPanel.add(party);
    northPanel.add(partyNumField);
    getParty = new JButton("GO - Continue with Order");
    getParty.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent)
    partyNum = Integer.parseInt(partyNumField.getText());
    String ans=JOptionPane.showInputDialog(null, "Total Number is party is: "
    + partyNum + " is this correct?\n\n" + "Enter 1 to continue\n"
    + "Enter 2 to cancel\n");
    if (ans.equals("1")) {
    System.out.println(ans+"=continue"); // handle continue
    } else { // assume to be 2 for cancel
    System.out.println(ans+"=cancel"); // handle cancel
    ); // end Listener
    northPanel.add(getParty);
    JPanel middlePanel = new JPanel();
    middlePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    dinerLabel = new JLabel("Please enter Diner's name");
    dinerName = new JTextField(30);
    continueOrder = new JButton("continue");
    middlePanel.add(dinerLabel);
    middlePanel.add(continueOrder);
    middlePanel.add(dinerName);
    entreeOrder = new JLabel("Please choose an entree");
    orderComboBox = new JComboBox(dinnerEntree);
    orderComboBox.setMaximumRowCount(4);
    //orderComboBox.addItemListener(
    // new ItemListener(){
    // public void itemsStateChanged(ItemEvent event)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // add entree order to Person
    // continue ** enable the two sides order
    mashed = new JCheckBox("Mashed Potatoes");
    middlePanel.add(mashed);
    cole = new JCheckBox("Cole Slaw");
    middlePanel.add(cole);
    baked = new JCheckBox("Baked Beans");
    middlePanel.add(baked);
    french = new JCheckBox("FrenchFries");
    middlePanel.add(french);
    // CheckBoxHandler handler = new CheckBoxHandler();
    // mashed.addItemListener(handler);
    // cole.addItemListener(handler);
    // baked.addItemListener(handler);
    // french.addItemListener(handler);
    middlePanel.add(entreeOrder);
    middlePanel.add(orderComboBox);
    container.add(northPanel);
    container.add(middlePanel);
    middlePanel.setEnabled(true);
    setSize(500, 500);
    show();
    // private class to handle event of choosing Check BOx Item
    // private class CheckBoxHandler implements ItemListener{
    // private int count = 0;
    // public void itemStateChanged(ItemEvent event){
    // if (event.getsource() == mashed)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    // add mashed choice to person's order
    // if (event.getsource() == cole)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add cole slaw to person's order
    // if (event.getsource() == baked)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add baked beans to person's order
    // if (event.getsource() == french)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add french to person's order
    public static void main(String args[])
    Menu application = new Menu();
    application.addWindowListener(
    new WindowAdapter(){
    public void windowClosing(WindowEvent windowEvent)
    System.exit(0);
    }

    This looks better, i myself don't like the flow layout
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Menu1 extends JFrame
         private JTextField partyNumField, dinerName;
         private JComboBox orderComboBox;
         private int partyNum;
         private JButton getParty, continueOrder;
         private JLabel party, companyLogo, dinerLabel, entreeOrder;
         private String dinnerEntree[] = {"Filet Mignon", "Chicken Cheese Steak", "Tacos", "Ribs"};
         private JCheckBox mashed, cole, baked, french;
    public Menu1()
         super("O'Brien Caterer - Where we make good Eats!");
         addWindowListener(new WindowAdapter()
             public void windowClosing(WindowEvent ev)
                   dispose();
                   System.exit(0);
         Container container = getContentPane();
         JPanel northPanel = new JPanel();
         northPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 120,15));
         companyLogo   = new JLabel("Welcome to O'Brien's Caterer's");
         northPanel.add(companyLogo);
         party         = new JLabel("Enter the Total Number in Party Please");
         partyNumField = new JTextField(5);
         northPanel.add(party);
         northPanel.add(partyNumField);
         getParty    = new JButton("GO - Continue with Order");
         northPanel.add(getParty);
         northPanel.setPreferredSize(new Dimension(700,150));
         getParty.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent actionEvent)
                   partyNum = Integer.parseInt(partyNumField.getText());
                   String ans=JOptionPane.showInputDialog(null, "Total Number is party is: "
                   + partyNum + " is this correct?\n\n" + "Enter 1 to continue\n"
                   + "Enter 2 to cancel\n");
                   if (ans.equals("1"))
                        System.out.println(ans+"=continue"); // handle continue
                   else { // assume to be 2 for cancel
                   System.out.println(ans+"=cancel"); // handle cancel
         }}); // end Listener
         JPanel middlePanel = new JPanel();
         middlePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
         dinerLabel         = new JLabel("Please enter Diner's name");
         dinerName          = new JTextField(30);
         continueOrder      = new JButton("continue");
         middlePanel.add(dinerLabel);
         middlePanel.add(dinerName);
         middlePanel.add(continueOrder);
         entreeOrder   = new JLabel("Please choose an entree");
         orderComboBox = new JComboBox(dinnerEntree);
         orderComboBox.setMaximumRowCount(4);
    //orderComboBox.addItemListener(
    // new ItemListener(){
    // public void itemsStateChanged(ItemEvent event)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // add entree order to Person
    // continue ** enable the two sides order
         mashed = new JCheckBox("Mashed Potatoes");
         middlePanel.add(mashed);
         cole   = new JCheckBox("Cole Slaw");
         middlePanel.add(cole);
         baked  = new JCheckBox("Baked Beans");
         middlePanel.add(baked);
         french = new JCheckBox("FrenchFries");
         middlePanel.add(french);
    // CheckBoxHandler handler = new CheckBoxHandler();
    // mashed.addItemListener(handler);
    // cole.addItemListener(handler);
    // baked.addItemListener(handler);
    // french.addItemListener(handler);
         middlePanel.add(entreeOrder);
         middlePanel.add(orderComboBox);
    //container.add(northPanel);
    //container.add(middlePanel);
         container.add(northPanel, java.awt.BorderLayout.NORTH);
         container.add(middlePanel, java.awt.BorderLayout.CENTER);
         middlePanel.setEnabled(true);
         setSize(600, 500);
         show();
    // private class to handle event of choosing Check BOx Item
    // private class CheckBoxHandler implements ItemListener{
    // private int count = 0;
    // public void itemStateChanged(ItemEvent event){
    // if (event.getsource() == mashed)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    // add mashed choice to person's order
    // if (event.getsource() == cole)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add cole slaw to person's order
    // if (event.getsource() == baked)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add baked beans to person's order
    // if (event.getsource() == french)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add french to person's order
    public static void main(String args[])
         new Menu1();
    no edit
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Menu1 extends JFrame
         private JTextField partyNumField, dinerName;
         private JComboBox orderComboBox;
         private int partyNum;
         private JButton getParty, continueOrder;
         private JLabel party, companyLogo, dinerLabel, entreeOrder;
         private String dinnerEntree[] = {"Filet Mignon", "Chicken Cheese Steak", "Tacos", "Ribs"};
         private JCheckBox mashed, cole, baked, french;
    public Menu1()
         super("O'Brien Caterer - Where we make good Eats!");
         addWindowListener(new WindowAdapter()
         public void windowClosing(WindowEvent ev)
                   dispose();
                   System.exit(0);
         Container container = getContentPane();
         JPanel northPanel = new JPanel();
         northPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 120,15));
         companyLogo = new JLabel("Welcome to O'Brien's Caterer's");
         northPanel.add(companyLogo);
         party = new JLabel("Enter the Total Number in Party Please");
         partyNumField = new JTextField(5);
         northPanel.add(party);
         northPanel.add(partyNumField);
         getParty = new JButton("GO - Continue with Order");
         northPanel.add(getParty);
         northPanel.setPreferredSize(new Dimension(700,150));
         getParty.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent actionEvent)
                   partyNum = Integer.parseInt(partyNumField.getText());
                   String ans=JOptionPane.showInputDialog(null, "Total Number is party is: "
                   + partyNum + " is this correct?\n\n" + "Enter 1 to continue\n"
                   + "Enter 2 to cancel\n");
                   if (ans.equals("1"))
                        System.out.println(ans+"=continue"); // handle continue
                   else { // assume to be 2 for cancel
                   System.out.println(ans+"=cancel"); // handle cancel
         }}); // end Listener
         JPanel middlePanel = new JPanel();
         middlePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
         dinerLabel = new JLabel("Please enter Diner's name");
         dinerName = new JTextField(30);
         continueOrder = new JButton("continue");
         middlePanel.add(dinerLabel);
         middlePanel.add(dinerName);
         middlePanel.add(continueOrder);
         entreeOrder = new JLabel("Please choose an entree");
         orderComboBox = new JComboBox(dinnerEntree);
         orderComboBox.setMaximumRowCount(4);
    //orderComboBox.addItemListener(
    // new ItemListener(){
    // public void itemsStateChanged(ItemEvent event)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // add entree order to Person
    // continue ** enable the two sides order
         mashed = new JCheckBox("Mashed Potatoes");
         middlePanel.add(mashed);
         cole = new JCheckBox("Cole Slaw");
         middlePanel.add(cole);
         baked = new JCheckBox("Baked Beans");
         middlePanel.add(baked);
         french = new JCheckBox("FrenchFries");
         middlePanel.add(french);
    // CheckBoxHandler handler = new CheckBoxHandler();
    // mashed.addItemListener(handler);
    // cole.addItemListener(handler);
    // baked.addItemListener(handler);
    // french.addItemListener(handler);
         middlePanel.add(entreeOrder);
         middlePanel.add(orderComboBox);
    //container.add(northPanel);
    //container.add(middlePanel);
         container.add(northPanel, java.awt.BorderLayout.NORTH);
         container.add(middlePanel, java.awt.BorderLayout.CENTER);
         middlePanel.setEnabled(true);
         setSize(600, 500);
         show();
    // private class to handle event of choosing Check BOx Item
    // private class CheckBoxHandler implements ItemListener{
    // private int count = 0;
    // public void itemStateChanged(ItemEvent event){
    // if (event.getsource() == mashed)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    // add mashed choice to person's order
    // if (event.getsource() == cole)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add cole slaw to person's order
    // if (event.getsource() == baked)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add baked beans to person's order
    // if (event.getsource() == french)
    // if (event.getStateChange() == ItemEvent.SELECTED)
    // count++;
    //add french to person's order
    public static void main(String args[])
         new Menu1();
    }

  • Swing interview questions

    I thought this would be the best place to ask some of you all what type of questions should be asked in an interview for a Swing developer. I also would love to have some questions about general GUI development.
    I have to interview a guy and I need to know what to expect from him and this is the first GUI interview I've done.

    So, after discussing this thread with some co-workers we came up with the following, which I think are acceptable GUI and Swing questions. They aren't too hard but aren't easy, and they tend to more relevant than just asking for specific information that can be looked up in the API.
    We did go through them and give some of what should be heard in an answer. These 'answers' aren't catch-alls, and may not have what individual interviewers are looking for but I think they make a good starting point. Some of the questions require a mockup or screenshot to ask them and these weren't included. Since different jobs require different skills an interviewer will need to create their own mockups and screenshots to focus the interview to the job listing.
    Interview Questions
    Graphical User Interface and Swing
    Section 1 - General Swing and GUI Questions
    What types of components have you used?
    This will depend on what the company does but you can never go wrong with JTables and JTrees. If you do MDI development, obviously JInternalFrames might be something you want to hear. The interviewee gets extra points for GridBagLayout experience since it is so powerful but feared by many Java delevopers.
    When you are building a GUI do you prefer to use an IDE or build it by hand?
    You want an employee who can do it by hand but you don't want the person to be inefficient and not use an IDE if it's available. If the person doesn't have any experience with an IDE that's not a plus or minus, it just means they will need to learn (if you are an IDE shop). If the person is only creating GUIs through an IDE builder, that may be a problem but there are other questions to clarify the person's skills.
    What is the difference between AWT and Swing?
    The difference is that an AWT component is a 'heavyweight' and Swing is a 'lightweight' component. Obviously, the interviewee needs to know that a heavyweight component depends on the native environment to draw the components. Swing does not. The interviewee gets extra points for some of the other things Swing brings to the table, like a pluggable look & feel, MVC architecture, and a more robust feature set.
    Can you name four or five layout managers?
    GridBagLayout, GridLayout, BorderLayout, FlowLayout, and CardLayout tend to be the most common. There are others that are listed in the Java API; check out the java.awt.LayoutManager interface for more.
    What is the difference between a component and a container?
    All Swing 'objects' are components, like buttons, tables, trees, text fields, etc. A container is a component that can contain other components. Technically, since JComponent inherits from Container all Swing components are containers as well. However, only a handful of top-level containers exist (JFrame, JDialog, etc.), and to be visible and GUI must start by adding components to a top-level container.
    Some components do not implement their 'add' methods so while they may be containers they do not allow the nesting of other components within their bounds. Specifically, JPanels can be used for component-nesting purposes.
    What would you change about this dialog?
    Using a dialog screenshot that has a poor layout, uses the wrong component for a specific task, has poor spacing between components, allow the interviewee to dissect the dialog and describe what should be done. I would suggest that a completely fictitious dialog is used to remove any personal biases the interviewer might have.
    This definitely needs to come before the next question, since we don't want to taint the interviewee with how we think a dialog should look. So the next question is:
    Explain how you would achieve the layout given this mockup.
    Using a screenshot of a dialog with a fair number of components, the user is to explain how they would get the components to be in the locations that they are in the mockup. This is much like the layout manager question although in this case the skill with the layout managers is being questioned. The weight each interviewer places on this question is up to them, but it can be used to discover whether someone knows about, has used it occasionally, or is intimately familiar with GridBagLayout or other layout managers. Also take into consideration the grouping of logical components in panels that might make a new piece of data that needs to be reflected in the dialog easier to add in later.
    What is the significance of a model in a component (for example, in a JTable or JTree)?
    What are the advantages of using your own model?
    The model in a component is used to fine-tune what the component displays by returning the specific data in specific instances where either the default values are used (a default model) or custom values are used (a custom model).
    When would you use a renderer or editor on a component?
    A renderer is used to create a custom display for the data in a component. The custom display is all that a renderer does. Implementing an editor allows the user to manipulate the data as well as have a custom display. However, once editing is completed the renderer is once again used to display the data.
    Why is Swing not 'thread safe'?
    A Swing application is run completely in the event-dispatching thread. Changes to components are placed in this thread and handled in the order they are received. Since threads run concurrently, making a change to a component in another thread may cause an event in the event-dispatching thread to be irrelevant or override the other thread's change.
    To get around this, code that needs to be run in a thread should be run in the event-dispatching thread. This can be achieved by creating the thread as normal but starting the thread by using SwingUtilities.invokeLater() and SwingUtilities.invokeAndWait().
    What would you do if you had to implement a component you weren't familiar with?
    This question is more about the process a person uses to solve a coding problem. Where do they go to find an answer? The order of the sources of information is just as important as which sources. Asking team members or other co-workers should be first, with other sources like the Internet (documents and forums) and books next. The Java API can also be useful in some cases but I think we have to assume that the component's requirements were more complex than just the API documentation can tell you.
    Section 2 - GUI Design Skills
    In this section, we are going to give the user an example of some inputs that need to be implemented and have them design a GUI for us. This will be completely done on the whiteboard and we don't care about any code. The timeframe is irrelevant so any component or custom component can be used.
    What we are looking for:
    - A design that focuses on the workflow from the user's perspective.
    - The proper components used to represent the data, but also
    - Unique and interesting ways of displaying data.

  • Quick graphics question  (again)

    I'm trying to display a string (and an image) on my applet but I don't want to put the code in the paint() method. The reason is that paint() is called every time the display is refreshed and I just want to display some text (g.drawString) one time only.
    So, what is wrong with this code: (from inside my JApplet class)
    public void drawTest() {
       Graphics g = getContentPane().getGraphics();
       g.drawString("My string", 20, 20);
       g.dispose();
    }I've also tried using:
    Graphics g = this.getGraphics();But that doesn't seem to work either.
    What am I doing wrong?

    Getting back to your original question, here's a demo of two of the many ways of combining a string with an image. Your original post mentioned this, but was sketchy...
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class X {
        public static void main(String[] args) throws IOException {
            BufferedImage image = ImageIO.read(new URL("http://today.java.net/jag/Image1-large.jpeg"));
            String title = "James Gosling";
            Font font = new Font("Lucida Sans", Font.PLAIN, 12);
            Color foreground = Color.WHITE;
            JLabel label = new JLabel(new ImageIcon(labelIt(image, title, font, foreground)));
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBackground(Color.BLACK);
            panel.add(new JLabel(new ImageIcon(image)));
            JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
            titleLabel.setForeground(foreground);
            panel.add(titleLabel, BorderLayout.NORTH);
            JFrame f = new JFrame(title);
            Container cp = f.getContentPane();
            cp.setLayout(new FlowLayout());
            cp.add(label);
            cp.add(panel);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
        public static BufferedImage labelIt(BufferedImage image, String text, Font font, Color color) {
            BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = result.createGraphics();
            g.drawRenderedImage(image, null);
            Rectangle2D bounds = font.getStringBounds(text, g.getFontRenderContext());
            float x = (float)(image.getWidth() - bounds.getWidth())/2;
            float y = (float)bounds.getHeight();
            g.setColor(color);
            g.setFont(font);
            g.drawString(text, x, y);
            g.dispose();
            return result;
    }

  • Simple KeyListener question

    I was wondering how to change the KeyPressed event to immediately start counting when a key is held down, as opposed to its second-long delay when the button is first pressed (for game purposes). For example, in this program I wrote, it will print out "up pressed" (when the up arrow is held) and then pause, before it will infinately print out "up pressed" until the key is released. I want to eliminate the pause.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Example extends JFrame implements KeyListener
    private JLabel square;
    private JPanel panel;
    private int squareX = 100, squareY = 50;
    public Example()
    super("Game");
    super.addKeyListener(this);
    super.setFocusable(true);
    //set your own image to make this work
    ImageIcon getSquare = new ImageIcon("C:\\Documents and Settings\\Phil\\My Documents\\My Pictures\\square.jpg");
    setDefaultLookAndFeelDecorated(true);
    FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
    Container container = getContentPane();
    container.setLayout(layout);
    panel = new JPanel(null);
    panel.setPreferredSize(new Dimension(150, 105));
    panel.setBorder(BorderFactory.createTitledBorder("Move the square"));
    square = new JLabel(getSquare);
    square.setBounds(squareX, squareY, 10, 10);
    panel.add(square);
    container.add(panel);
    setSize(300, 150);
    setVisible(true);
    public void keyPressed(KeyEvent e)
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    System.out.println("left pressed");
    moveLeft(); }
    if (e.getKeyCode() == KeyEvent.VK_UP) {
    System.out.println("up pressed");
    moveUp(); }
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    System.out.println("right pressed");
    moveRight(); }
    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    System.out.println("down pressed");
    moveDown(); }
    public void keyReleased(KeyEvent e)
    if (e.getKeyCode() == KeyEvent.VK_LEFT)
    System.out.println("left released");
    if (e.getKeyCode() == KeyEvent.VK_UP)
    System.out.println("up released");
    if (e.getKeyCode() == KeyEvent.VK_RIGHT)
    System.out.println("right released");
    if (e.getKeyCode() == KeyEvent.VK_DOWN)
    System.out.println("down released");
    public void keyTyped(KeyEvent e){}
    private void moveLeft() {
    if (checkLeft())
    square.setLocation(squareX--, squareY); }
    private void moveUp() {
    if (checkUp())
    square.setLocation(squareX, squareY--); }
    private void moveRight() {
    if (checkRight())
    square.setLocation(squareX++, squareY); }
    private void moveDown() {
    if (checkDown())
    square.setLocation(squareX, squareY++); }
    private boolean checkLeft() {
    return (square.getBounds().x >= 0); }
    private boolean checkUp() {
    return (square.getBounds().y >= 0); }
    private boolean checkRight() {
    return (square.getBounds().width <= panel.getPreferredSize().width); }
    private boolean checkDown() {
    return (square.getBounds().x <= panel.getPreferredSize().height); }
    public static void main (String[] args)
    Example myExample = new Example();
    myExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    Swing related questions should be posted in the Swing forum.
    Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags when posting code to the code is readable.
    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html]How to Use Timers. You start a Timer when the key is pressed and stop the timer when the key is released. You can control the interval at which the Timer fires so its not dependent on the key repeat rate of the system.

  • Simple question I think, add JPanel to JScrollPane

    I would imagine that for anyone with experience with Java this will be a simple problem. Why can't I add a JPanel to a JScrollPane using myScrollPane.Add(myPanel); ?? it seems to get hidden...
    This works correctly:
         //Create a panel
         JPanel panel = new JPanel(new FlowLayout());
         //Make it pink
         panel.setBackground(Color.pink);
         //Make it 400,400
         panel.setPreferredSize(new Dimension(400,400));
         //Create a Scrollpane
         JScrollPane scrollPane = new JScrollPane(panel);
         //Make it 300,300
         scrollPane.setPreferredSize(new Dimension(300,300));
         //Create a JFrame
         JFrame frame = new JFrame("Test Scrollpane");
         frame.setLayout(new FlowLayout());
         //Set close operation
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Set its size
         frame.setSize(600,600);
         //Add Scrollpane to JFrame
         frame.add(scrollPane);
         //Show it
         frame.setVisible(true);
    This doesnt:
         //Create a panel
         JPanel panel = new JPanel(new FlowLayout());
         //Make it pink
         panel.setBackground(Color.pink);
         //Make it 400,400
         panel.setPreferredSize(new Dimension(400,400));
         //Create a Scrollpane
         JScrollPane scrollPane = new JScrollPane();
         scrollPane.add(panel);
         //Make it 300,300
         scrollPane.setPreferredSize(new Dimension(300,300));
         //Create a JFrame
         JFrame frame = new JFrame("Test Scrollpane");
         frame.setLayout(new FlowLayout());
         //Set close operation
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Set its size
         frame.setSize(600,600);
         //Add Scrollpane to JFrame
         frame.add(scrollPane);
         //Show it
         frame.setVisible(true);

    rcfearn wrote:
    I would appreciate it you could read the sample code, I am asking the question as to why I have to do this? For structural reasons I don't want to have to add the JPanel during instatiation of the JScrollPane...Please read the [jscrollpane api.|http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html] To display something in a scroll pane you need to add it not to the scroll pane but to its viewport. If you add the component in the scroll pane's constructor, then it will be automatically added to the viewport. if you don't and add the component later, then you must go out of your way to be sure that it is added to the viewport with:
    JScrollPane myScrollPane = new JScrollPane();
    myScrollPane.getViewport().add(myComponent);

  • FlowLayout and Jlabels and Jbuttons,  Help!!!!!

    Ok, I have an Assignment using the FlowLayout only!!. I have been readin all the tutorials and documentation regarding the FlowLayout. Yet it seems I have a problem. Within my prrogram I am to position the buttons on the right and postion the text on the left.
    My question is: Is there a way to postion each component separtely using FlowLayout. Can yoo position the Jlabels to the left and the JButtons to the right?
    I know other layouts would be easier but our proffessor wants us to use the flowlayout for this assignment.
    Here is my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.FlowLayout;
    import java.awt.Font;
                   public class VideoStore extends JFrame {
                        JButton b1, b2, b3;
                        JLabel movie1,movie2,movie3,header;
                   public VideoStore (String title) {
                        super (title);
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        FlowLayout video = new FlowLayout(FlowLayout.LEFT);
                       setLayout(video);
                        header = new JLabel("CCAC VideoStore");
                        header.setFont(new Font("Times New Roman", Font.BOLD, 24));
                       add(header);
                       {movie1= new JLabel("Johnson Family Vacation");
                       movie1.setFont(new Font("Courier New", Font.BOLD, 14));
                        add(movie1);
                        b1= new JButton("Buy");
                        video.setAlignment(FlowLayout.RIGHT);
                        add(b1);}
                        movie2= new JLabel("PitchBlack");
                            movie2.setFont(new Font("Courier New", Font.BOLD, 14));
                       add(movie2);
                        b2 = new JButton ("Buy");
                        add(b2);
                        movie3= new JLabel ("Meet The Fockers");
                       movie3.setFont(new Font("Courier New", Font.BOLD, 14));
                       add(movie3);
                        b3 = new JButton ("Buy");
                        add(b3);
                   }Edited by: ConfusedNewb on Apr 20, 2010 8:10 AM

    ConfusedNewb wrote:
    Sorry.Requirements are: All of the "Buy" JButtons need aligned to the right and all of the JLabels need aligned to the left. There are 3 movie Jlabels and 3 jbuttons. I just cant get them to align without using the spacing trick. Everything has to fit in one window.This should be layed out with 2 JPanels, one for the Labels and one for the Buttons. Since FlowLayout will lay the 2 JPanels side by side, you will get the separation that you need. You just need to justify the Label and Button Panels appropriately and make the outer container and Panels appropriate widths to allow the layout to function as you need.

  • Questions on Print Quote report

    Hi,
    I'm fairly new to Oracle Quoting and trying to get familiar with it. I have a few questions and would appreciate if anyone answers them
    1) We have a requirement to customize the Print Quote report. I searched these forums and found that this report can be defined either as a XML Publisher report or an Oracle Reports report depending on a profile option. Can you please let me know what the name of the profile option is?
    2) When I select the 'Print Quote' option from the Actions drop down in the quoting page and click Submit I get the report printed and see the following URL in my browser.
    http://<host>:<port>/dev60cgi/rwcgi60?PROJ03_APPS+report=/proj3/app/appltop/aso/11.5.0/reports/US/ASOPQTEL.rdf+DESTYPE=CACHE+P_TCK_ID=23731428+P_EXECUTABLE=N+P_SHOW_CHARGES=N+P_SHOW_CATG_TOT=N+P_SHOW_PRICE_ADJ=Y+P_SESSION_ID=c-RAuP8LOvdnv30grRzKqUQs:S+P_SHOW_HDR_ATTACH=N+P_SHOW_LINE_ATTACH=N+P_SHOW_HDR_SALESUPP=N+P_SHOW_LN_SALESUPP=N+TOLERANCE=0+DESFORMAT=RTF+DESNAME=Quote.rtf
    Does it mean that the profile in our case is set to call the rdf since it has reference to ASOPQTEL.rdf in the above url?
    3) When you click on submit button do we have something like this in the jsp code: On click call ASOPQTEL.rdf. Is the report called using a concurrent program? I want to know how the report is getting invoked?
    4) If we want to customize the jsp pages can you please let me know the steps involved in making the customizations and testing them.
    Thanks and Appreciate your patience
    -PC

    1) We have a requirement to customize the Print Quote report. I searched these forums and found that this report can be defined either as a XML Publisher report or an Oracle Reports report depending on a profile option. Can you please let me know what the name of the profile option is?
    I think I posted it in one of the threads2) When I select the 'Print Quote' option from the Actions drop down in the quoting page and click Submit I get the report printed and see the following URL in my browser.
    http://<host>:<port>/dev60cgi/rwcgi60?PROJ03_APPS+report=/proj3/app/appltop/aso/11.5.0/reports/US/ASOPQTEL.rdf+DESTYPE=CACHE+P_TCK_ID=23731428+P_EXECUTABLE=N+P_SHOW_CHARGES=N+P_SHOW_CATG_TOT=N+P_SHOW_PRICE_ADJ=Y+P_SESSION_ID=c-RAuP8LOvdnv30grRzKqUQs:S+P_SHOW_HDR_ATTACH=N+P_SHOW_LINE_ATTACH=N+P_SHOW_HDR_SALESUPP=N+P_SHOW_LN_SALESUPP=N+TOLERANCE=0+DESFORMAT=RTF+DESNAME=Quote.rtf
    Does it mean that the profile in our case is set to call the rdf since it has reference to ASOPQTEL.rdf in the above url?
    Yes, your understanding is correct.3) When you click on submit button do we have something like this in the jsp code: On click call ASOPQTEL.rdf. Is the report called using a concurrent program? I want to know how the report is getting invoked?
    No, there is no conc program getting called, you can directly call a report in a browser window, Oracle reports server will execute the report and send the HTTP response to the browser.4) If we want to customize the jsp pages can you please let me know the steps involved in making the customizations and testing them.
    This is detailed in many threads.Thanks
    Tapash

  • JSeparator is not getting displayed in Flowlayout !!!

    Hi all,
    I was trying to put a vertical JSeparator between two buttons placed in a panel having Flowlayout; it simply doesn't show up. What could be the reason? and if it is a bug or known behaviour, what is the work around avilable.
    The other two layouts I am interested in (viz. BorderLayout and TableLayout) behave as expected.
    Thanks,
    AV

    I didn't mean to rude or ungrateful. I am not using separator along with menuitems. But between any JComponents. It works fine with BorderLayout and TableLayout. I am using FlowLayout also; it there where separator doesn't show up.
    BTW, I am using j2sdk1.4.2_04
    import javax.swing.*;
    import java.awt.*;
    public class Test20050131 extends JFrame
        public Test20050131()
            super("Test Test Test");
            JPanel panel = new JPanel();
            panel.add(new JLabel(" Label "));
            panel.add(new JSeparator(JSeparator.VERTICAL));
            panel.add(new JTextField(10));
            panel.add(new JSeparator(JSeparator.VERTICAL));
            panel.add(new JButton(" button "));       
            getContentPane().add(panel);
            pack();
        public static void main(String[] args)
            try
                new Test20050131().setVisible(true);
            catch (Exception e)
                e.printStackTrace();
    }AV

  • Satellite P300D-10v - Question about warranty

    HI EVERYBODY
    I have these overheating problems with my laptop Satellite P300D-10v.
    I did everything I could do to fix it without any success..
    I get the latest update of the bios from Toshiba. I cleaned my lap with compressed air first and then disassembled it all and cleaned it better.(it was really clean insight though...)
    BUT unfortunately the problem still exists...
    So i made a research on the internet and I found out that most of Toshiba owners have the same exactly problem with their laptop.
    Well i guess this is a Toshiba bug for many years now.
    Its a really nice lap, cool sound (the best in laptop ever) BUT......
    So I wanted to make a question. As i am still under warranty, can i return this laptop and get my money back or change it with a different one????
    If any body knows PLS let me know.
    chears
    Thanks in advance

    Hi
    I have already found you other threads.
    Regarding the warranty question;
    If there is something wrong with the hardware then the ASP in your country should be able to help you.
    The warranty should cover every reparation or replacement.
    But I read that you have disasembled the laptop at your own hand... hmmm if you have disasembled the notebook then your warrany is not valid anymore :(
    I think this should be clear for you that you can lose the warrany if you disasemble the laptop!
    By the way: you have to speak with the notebook dealer where you have purchased this notebook if you want to return the notebook
    The Toshiba ASP can repair and fix the notebook but you will not get money from ASP.
    Greets

Maybe you are looking for

  • Export for AppleTV - Settings messed up?

    I have done it this way before (at least I thought this is how I did it): File - Export - Using Quicktime Conversion - Format (Apple TV) -- name it and go... Then drag this file to iTunes, and all is great... I can watch it on my iPhone or my AppleTV

  • Problem while transporting query from development  to quality

    Hi , At the time of collecting objects, we are getting an error. Object '48NYONN6RPXN7Q9YDS6DWSM35' (ROUT) of type 'Routine' is not available in version 'A' (Infact similar error statements round 16 are displayed). I don't see any object as such. i d

  • Random message "The microsoft exchange administrator has made changes that requires you quit and restart Outlook"

    Hello everyone, I have read a lot of subject on technet forums and others but I don't find the solution to my issue. So I explain my problem: I have 2 different clients with Exchange Server 2013 Standard installed on a Windows Server 2012 Standard th

  • Not seen as a drive...

    i have 2 x 20gb pods and now a shuffle. Notethatthe shuffle kicks into itunes ok, and that it is seen in the 'Safely Remove Hardware' option in XP, but does not appear as a drive in 'My Computer' ...any thoughts?

  • Problem with warp text tool

    I have a text layer which I want to do some warping to. When I hit the warp text tool all the options are greyed out ??? Any help ? Incidentally, I tried to just transform warp it but no "handles" appear...