Fit JButtons  in a JFrame

Hy, I am actually creating a Graphical Programming Language Appln and I am facing some problems.
My source code is found below. Here is my problem:
I have inserted some buttons have been inserted in the Main panel until both scroll bar appear,
what I want is that when I click on the button label "Fit", a new window opens,
where it shows the buttons which have been fitted in that window, without any scrollbar.How to do that?
Please send me the code for solving this problem. Its very very urgent.Here are my Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.tree.*;
import java.io.*;
public class MainDesktop extends JFrame implements ActionListener {
JSplitPane splitPane = new JSplitPane();
JPanel mainPane = new JPanel();
JScrollPane mainScrollPane = new JScrollPane();
Container contentPane = getContentPane();
public MainDesktop() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
//Adding the ToolBar to the main window
JToolBar toolBar = new JToolBar();
myToolBar(toolBar);
contentPane.add(toolBar, BorderLayout.NORTH);
//create a list of button and add them to a pane
JButton bgButton = new JButton("Begin");
JButton rdButton = new JButton("Read");
JButton wrButton = new JButton("Write");
JButton efButton = new JButton("If-Else");
JButton ifButton = new JButton("End-If");
JButton wlButton = new JButton("While-Loop");
JButton flButton = new JButton("For-Loop");
JButton elButton = new JButton("End-Loop");
JButton swButton = new JButton("Switch");
JButton arButton = new JButton("Arithmetic");
JButton enButton = new JButton("End");
bgButton.setActionCommand("Begin");
rdButton.setActionCommand("Read");
wrButton.setActionCommand("Write");
efButton.setActionCommand("If-Else");
ifButton.setActionCommand("End-If");
wlButton.setActionCommand("While-Loop");
flButton.setActionCommand("For-Loop");
elButton.setActionCommand("End-Loop");
swButton.setActionCommand("Switch");
arButton.setActionCommand("Arithmetic");
enButton.setActionCommand("End");
bgButton.addActionListener(this);
rdButton.addActionListener(this);
wrButton.addActionListener(this);
efButton.addActionListener(this);
ifButton.addActionListener(this);
wlButton.addActionListener(this);
flButton.addActionListener(this);
elButton.addActionListener(this);
swButton.addActionListener(this);
arButton.addActionListener(this);
enButton.addActionListener(this);
JPanel toolPane = new JPanel();
toolPane.setLayout(new GridLayout(15,0));
toolPane.add(bgButton);
toolPane.add(rdButton);
toolPane.add(wrButton);
toolPane.add(efButton);
toolPane.add(ifButton);
toolPane.add(wlButton);
toolPane.add(flButton);
toolPane.add(elButton);
toolPane.add(swButton);
toolPane.add(arButton);
toolPane.add(enButton);
//Create a pane for the drawing area and add scroll pane to it
mainPane.setLayout(new FlowLayout());
mainScrollPane = new JScrollPane(mainPane);
mainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
mainScrollPane.setHorizontalScrollBarPolicy (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
mainScrollPane.setLayout(new ScrollPaneLayout());
//Create a split pane with the two scroll panes in it
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,toolPane, mainScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(100);
splitPane.setPreferredSize(new Dimension(1000, 650));
getContentPane().add(splitPane);
protected void myToolBar(JToolBar toolBar) {
//Fit button
JButton fitButton = new JButton("Fit");
fitButton.setToolTipText("Fit Flowchart to drawing area");
fitButton.setActionCommand("Fit");
fitButton.addActionListener(this);
toolBar.add(fitButton);
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Fit")) {
//fit flowchart to drawing area
if (cmd.equals("Delete")) {
//Delete a node from flowchart
//Action command for the list of button from the toolbox
if (cmd.equals("Begin")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Read")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Write")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("If-Else")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("End-If")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("While-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("For-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("End-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Switch")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Arithmetic")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
//mainPane.repaint();
if (cmd.equals("End")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
//mainPane.repaint();
class dragbutton extends JButton implements DragGestureListener, DragSourceListener {
public dragbutton() {
super("Begin");
DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this,DnDConstants.ACTION_COPY_OR_MOVE,this);
public void dragGestureRecognized(DragGestureEvent e) {
e.startDrag(DragSource.DefaultCopyDrop,
new StringSelection(null),this);
public void dragDropEnd(DragSourceDropEvent e) {}
public void dragEnter(DragSourceDragEvent e) {}
public void dragExit(DragSourceEvent e) {}
public void dragOver(DragSourceDragEvent e) {}
public void dropActionChanged(DragSourceDragEvent e) {}
public static void main(String [] args) {
MainDesktop mainWindow = new MainDesktop();
mainWindow.setTitle("Graphical Programming Language");
mainWindow.setSize(700, 600);
mainWindow.setVisible(true);

Hy, I am actually creating a Graphical Programming Language Appln and I am facing some problems.
My source code is found below. Here is my problem:
I have inserted some buttons have been inserted in the Main panel until both scroll bar appear,
what I want is that when I click on the button label "Fit", a new window opens,
where it shows the buttons which have been fitted in that window, without any scrollbar.How to do that?
Please send me the code for solving this problem. Its very very urgent.Here are my Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.tree.*;
import java.io.*;
public class MainDesktop extends JFrame implements ActionListener {
JSplitPane splitPane = new JSplitPane();
JPanel mainPane = new JPanel();
JScrollPane mainScrollPane = new JScrollPane();
Container contentPane = getContentPane();
public MainDesktop() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
//Adding the ToolBar to the main window
JToolBar toolBar = new JToolBar();
myToolBar(toolBar);
contentPane.add(toolBar, BorderLayout.NORTH);
//create a list of button and add them to a pane
JButton bgButton = new JButton("Begin");
JButton rdButton = new JButton("Read");
JButton wrButton = new JButton("Write");
JButton efButton = new JButton("If-Else");
JButton ifButton = new JButton("End-If");
JButton wlButton = new JButton("While-Loop");
JButton flButton = new JButton("For-Loop");
JButton elButton = new JButton("End-Loop");
JButton swButton = new JButton("Switch");
JButton arButton = new JButton("Arithmetic");
JButton enButton = new JButton("End");
bgButton.setActionCommand("Begin");
rdButton.setActionCommand("Read");
wrButton.setActionCommand("Write");
efButton.setActionCommand("If-Else");
ifButton.setActionCommand("End-If");
wlButton.setActionCommand("While-Loop");
flButton.setActionCommand("For-Loop");
elButton.setActionCommand("End-Loop");
swButton.setActionCommand("Switch");
arButton.setActionCommand("Arithmetic");
enButton.setActionCommand("End");
bgButton.addActionListener(this);
rdButton.addActionListener(this);
wrButton.addActionListener(this);
efButton.addActionListener(this);
ifButton.addActionListener(this);
wlButton.addActionListener(this);
flButton.addActionListener(this);
elButton.addActionListener(this);
swButton.addActionListener(this);
arButton.addActionListener(this);
enButton.addActionListener(this);
JPanel toolPane = new JPanel();
toolPane.setLayout(new GridLayout(15,0));
toolPane.add(bgButton);
toolPane.add(rdButton);
toolPane.add(wrButton);
toolPane.add(efButton);
toolPane.add(ifButton);
toolPane.add(wlButton);
toolPane.add(flButton);
toolPane.add(elButton);
toolPane.add(swButton);
toolPane.add(arButton);
toolPane.add(enButton);
//Create a pane for the drawing area and add scroll pane to it
mainPane.setLayout(new FlowLayout());
mainScrollPane = new JScrollPane(mainPane);
mainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
mainScrollPane.setHorizontalScrollBarPolicy (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
mainScrollPane.setLayout(new ScrollPaneLayout());
//Create a split pane with the two scroll panes in it
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,toolPane, mainScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(100);
splitPane.setPreferredSize(new Dimension(1000, 650));
getContentPane().add(splitPane);
protected void myToolBar(JToolBar toolBar) {
//Fit button
JButton fitButton = new JButton("Fit");
fitButton.setToolTipText("Fit Flowchart to drawing area");
fitButton.setActionCommand("Fit");
fitButton.addActionListener(this);
toolBar.add(fitButton);
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Fit")) {
//fit flowchart to drawing area
if (cmd.equals("Delete")) {
//Delete a node from flowchart
//Action command for the list of button from the toolbox
if (cmd.equals("Begin")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Read")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Write")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("If-Else")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("End-If")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("While-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("For-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("End-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Switch")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Arithmetic")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
//mainPane.repaint();
if (cmd.equals("End")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
//mainPane.repaint();
class dragbutton extends JButton implements DragGestureListener, DragSourceListener {
public dragbutton() {
super("Begin");
DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this,DnDConstants.ACTION_COPY_OR_MOVE,this);
public void dragGestureRecognized(DragGestureEvent e) {
e.startDrag(DragSource.DefaultCopyDrop,
new StringSelection(null),this);
public void dragDropEnd(DragSourceDropEvent e) {}
public void dragEnter(DragSourceDragEvent e) {}
public void dragExit(DragSourceEvent e) {}
public void dragOver(DragSourceDragEvent e) {}
public void dropActionChanged(DragSourceDragEvent e) {}
public static void main(String [] args) {
MainDesktop mainWindow = new MainDesktop();
mainWindow.setTitle("Graphical Programming Language");
mainWindow.setSize(700, 600);
mainWindow.setVisible(true);

Similar Messages

  • Positioning JButton in a JFrame

    Hello,
    I am having a problem positioning a JButton in a JFrame. All I want to do is to have a JFrame that contains a JButton at location 100,100. I dont know why I've been having trouble with this. I just want something simple, so if anyone can write a small program that extends JFrame as an example for me that would be much appreciated. Thanks for your time everyone

    For component positioning, Java use LayoutManagers which are placement algorithms.
    By default, all components have a layout manager :
    JPanels have a FlowLayout that layout the sub-components like a text document,
    The contentPane of a JFrame has a BorderLayout which divides the screen in five areas (NORTH, SOUTH,EAST, WEST and CENTER).
    If you want an absolute positioning you have to "remove" this layout manager and replace it by an "hidden" layout manager : AbsoluteLayout.
    To do this use :
    frame.getContentPane().setLayout(null);
    After that you can give absolute positions and size to your components which won't be moved or resized.
    I hope this helps,
    Denis

  • JButton to link JFrame?

    Can i know how can i code to link a JButton in a JFrame to another JFrame?
    example: while building an application, i want to link a logon JFrame to the main JFrame. after entering the username and passwork, i need to click the JButton "ok" to link into the main JFrame.

    This might be one way
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class MainFrame extends JFrame
      final String PASSWORD = "java";
      String password;
      public MainFrame()
        class Login extends JDialog
          JTextField tf = new JTextField(10);
          public Login()
            setModal(true);
            setLocation(400,300);
            getContentPane().setLayout(new BorderLayout());
            JPanel top = new JPanel();
            top.add(new JLabel("Password: "));
            top.add(tf);
            getContentPane().add(top,BorderLayout.NORTH);
            JButton btn = new JButton("OK");
            btn.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e){
                password = tf.getText();
                dispose();}});
            getContentPane().add(btn,BorderLayout.SOUTH);
            pack();
            setVisible(true);
        new Login();
        if(password == null || !password.equals(PASSWORD))
          JOptionPane.showMessageDialog(null,"Invalid password, exiting");
          System.exit(0);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(100,50);
        setSize(800,600);
        JPanel main = new JPanel();
        main.add(new JLabel("I am the main frame"));
        getContentPane().add(main);
        setVisible(true);
      public static void main(String[] args){new MainFrame();}
    }

  • Problem with KeyAdapter and JButtons in a Jframe

    yes hi
    i have searched almost most of the threads here but nothing
    am trying to make my frame accepts keypress and also have some button on the frame here is the code and thank you for the all the help
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPg extends JFrame implements ActionListener
                private int width;
                private int hight;
                public    JPanel north;
                public    JPanel se;
                public    JButton start;
                public    JButton quit;
                public    Screen s;//a Jpanel
                public    KeyStrokeHandler x;
        public RPg() {
               init();
               setTitle("RPG");
               setSize(width,hight);
               setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               setResizable(false);
               setVisible(true);
               x=new KeyStrokeHandler();
             addKeyListener(x);
             public void init() {
               north=new JPanel();
               Container cp = getContentPane();
               s=new Screen();
               this.width=s.width;
               this.hight=s.hight+60;
              start=new JButton("START");
                  start.addActionListener(this);
              quit=new JButton("QUIT");
                  quit.addActionListener(this);
              north.setBackground(Color.DARK_GRAY);
              north.setLayout(new FlowLayout());
              north.add(start);
              north.add(quit);
              cp.add(north, BorderLayout.NORTH);
              cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPg rpg = new RPg();
       public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
       class KeyStrokeHandler extends KeyAdapter {
               public void keyTyped(KeyEvent ke) {}
               public void keyPressed(KeyEvent ke){
                  int keyCode = ke.getKeyCode();
                  if ((keyCode == KeyEvent.VK_M)){
                     System.out.println("it works");
               public void keyReleased(KeyEvent ke){}

    Use the 'tab' key to navigate through 'contentPane > start > quit' focus cycle. 'M' key works when focus is on contentPane (which it is on first showing). See tutorial pages on 'Using Key Bindings' and 'Focus Subsystem' for more.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPG extends JFrame implements ActionListener {
        private int width;
        private int hight;
        public JPanel north;
        public JPanel se;
        public JButton start;
        public JButton quit;
        public Screen s;    //a Jpanel
        public RPG() {
            init();
            setTitle("RPG");
            setSize(width,hight);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setResizable(false);
            setVisible(true);
        public void init() {
            north=new JPanel();
            Container cp = getContentPane();
            registerKeys((JComponent)cp);
            s=new Screen();
            this.width=s.width;
            this.hight=s.hight+60;
            start=new JButton("START");
                start.addActionListener(this);
            quit=new JButton("QUIT");
                quit.addActionListener(this);
            north.setBackground(Color.DARK_GRAY);
            north.setLayout(new FlowLayout());
            north.add(start);
            north.add(quit);
            cp.add(north, BorderLayout.NORTH);
            cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPG rpg = new RPG();
        public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
        private void registerKeys(JComponent jc)
            jc.getInputMap().put(KeyStroke.getKeyStroke("M"), "M");
            jc.getActionMap().put("M", mAction);
        Action mAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("it works");
    class Screen extends JPanel {
        int width, hight;
        public Screen() {
            width = 300;
            hight = 300;
            setBackground(Color.pink);
    }

  • Selecting checkbox through a JButton click in JFrame

    i am trying to change the state of the check box in a JFrame through a JButton click, using the getsource() method.
    if (e.getSource()==johnButton){
    // Set the state of the checkbox to on
    checkbox.setSelected(true);
    i have also tried using isSelected().
    there is no error in the programme, how ever it doesn't work for me.

    Must be
    if(e.getSource()== JCheckbox)
    do whatever
    However, a better way if you had many checkboxs
    JCheckbox b = new JCheckbox(...);
    b.addActionListener(this);
    b.setActionCommand("MyChkBx");
    public void actionPerformed(ActionEvent e)
    String cmd = e.getActionEvent();
    if(cmd.equals("MyChkBx"))
    do whatever
    }

  • Fitting JButton width to JToolBar width

    Hello everyone,
    In my application I need to have a vertical set of buttons (only one column), so I thought using JToolBar and JButton would be okay. Unfortunately, I would like to make JButtons to fit the whole width of JToolBox, and can't do this. I've looked through this forum, google, tried to chang BoxLayout, but nothing really works.
    Is the only solution to use JTable and put JButtons in it?
    Generally speaking- funcionality I'am currently trying to achieve is to get the list of users, who are 'clickable' (I mean, when I doubleclick on the user's nicname an Action is going to be launched)
    I hope anyone is going to help me :)
    regards
    MD

    I had forgotten to tell you, that the list of users may change dynamically.
    JToolBox is not an only solution, but at first I thought it'd be ok.
    What about JButton in JTable?
    According to JButtons in JLabel.
    I also thought about that solution, but...does any LayoutManager allows to change number of "rows" without repainting again? (when I add or remove any user)

  • How do i use jbutton for mutiple frames(2frames)???

    im an creating a movie database program and i have a problem with the jButtons on my second frame i dont know how to make them work when clicked on. i managed to make the jButtons work on my first frame but not on the second....
    here is that code so far----
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    * real2.java
    * Created on December 7, 2007, 9:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author J
    public class real2 extends JPanel  implements ActionListener{
        private JButton addnew;
        private JButton help;
        private JButton exit;
        private JFrame frame1;
        private JButton save;
        private JButton cancel;
        private JButton save2;
        private JLabel moviename;
        private JTextField moviename2;
        private JLabel director;
        private JTextField director2;
        private JLabel year;
        private JTextField year2;
        private JLabel genre;
        private JTextField genre2;
        private JLabel plot;
        private JTextField plot2;
        private JLabel rating;
        private JTextField rating2;
        /** Creates a new instance of real2 */
        public real2() {
            super(new GridBagLayout());
            //Create the Buttons.
            addnew = new JButton("Add New");
            addnew.addActionListener(this);
            addnew.setMnemonic(KeyEvent.VK_E);
            addnew.setActionCommand("Add New");
            help = new JButton("Help");
            help.addActionListener(this);
            help.setActionCommand("Help");
            exit = new JButton("Exit");
            exit.addActionListener(this);
            exit.setActionCommand("Exit");
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(600, 100));
            table.setFillsViewportHeight(true);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 1;
            c.gridx = 0;
            c.gridy = 1;
            add(addnew, c);
            c.gridx = 0;
            c.gridy = 2;
            add(help, c);
            c.gridx = 0;
            c.gridy = 3;
            add(exit, c);
        public static void addComponentsToPane(Container pane){
            pane.setLayout(null);
            //creating the components for the new frame
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            JButton cancel = new JButton("Cancel");
            JLabel moviename= new JLabel("Movie Name");
            JTextField moviename2 = new JTextField(8);
            JLabel director = new JLabel("Director");
            JTextField director2 = new JTextField(8);
            JLabel genre = new JLabel("Genre");
            JTextField genre2 = new JTextField(8);
            JLabel year = new JLabel("year");
            JTextField year2 = new JTextField(8);
            JLabel plot = new JLabel("Plot");
            JTextField plot2 = new JTextField(8);
            JLabel rating = new JLabel("Rating(of 10)");
            JTextField rating2 = new JTextField(8);
            //adding components to new frame
            pane.add(save);
            pane.add(save2);
            pane.add(cancel);
            pane.add(moviename);
            pane.add(moviename2);
            pane.add(director);
            pane.add(director2);
            pane.add(genre);
            pane.add(genre2);
            pane.add(year);
            pane.add(year2);
            pane.add(plot);
            pane.add(plot2);
            pane.add(rating);
            pane.add(rating2);
            //setting positions of components for new frame
                Insets insets = pane.getInsets();
                Dimension size = save.getPreferredSize();
                save.setBounds(100 , 50 ,
                         size.width, size.height);
                 size = save2.getPreferredSize();
                save2.setBounds(200 , 50 ,
                         size.width, size.height);
                 size = cancel.getPreferredSize();
                cancel.setBounds(400 , 50 ,
                         size.width, size.height);
                 size = moviename.getPreferredSize();
                moviename.setBounds(100 , 100 ,
                         size.width, size.height);
                size = moviename2.getPreferredSize();
                moviename2.setBounds(200 , 100 ,
                         size.width, size.height);
                 size = director.getPreferredSize();
                director.setBounds(100, 150 ,
                         size.width, size.height);
                 size = director2.getPreferredSize();
                director2.setBounds(200 , 150 ,
                         size.width, size.height);
                size = genre.getPreferredSize();
                genre.setBounds(100 , 200 ,
                         size.width, size.height);
                 size = genre2.getPreferredSize();
                genre2.setBounds(200 , 200 ,
                         size.width, size.height);
                 size = year.getPreferredSize();
                year.setBounds(100 , 250 ,
                         size.width, size.height);
                size = year2.getPreferredSize();
                year2.setBounds(200 , 250 ,
                         size.width, size.height);
                 size = plot.getPreferredSize();
                plot.setBounds(100 , 300 ,
                         size.width, size.height);
                 size = plot2.getPreferredSize();
                plot2.setBounds(200 , 300 ,
                         size.width, size.height);
                size = rating.getPreferredSize();
                rating.setBounds(100 , 350 ,
                         size.width, size.height);
                 size = rating2.getPreferredSize();
                rating2.setBounds(200 , 350 ,
                         size.width, size.height);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            frame.add(new real2());
            //Display the window.
            frame.setSize(600, 360);
            frame.setVisible(true);
            frame.pack();
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void actionPerformed(ActionEvent e) {
            if ("Add New".equals(e.getActionCommand())){
               frame1 = new JFrame("add");
               frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
               addComponentsToPane(frame1.getContentPane());
               frame1.setSize(600, 500);
               frame1.setVisible(true);
                //disableing first frame etc:-
                if (frame1.isShowing()){
                addnew.setEnabled(false);
                help.setEnabled(false);
                exit.setEnabled(true);
                frame1.setVisible(true);
               }else{
                addnew.setEnabled(true);
                help.setEnabled(true);
                exit.setEnabled(true);           
            if ("Exit".equals(e.getActionCommand())){
                System.exit(0);
            if ("Save".equals(e.getActionCommand())){
                // whatever i ask it to do it wont for example---
                help.setEnabled(true);
            if ("Save" == e.getSource()) {
                //i tried this way too but it dint work here either
                help.setEnabled(true);
    }so if someone could help me by either telling me what to type or by replacing what iv done wrong that would be great thanks...

    (1)Java class name should begin with a capital letter. See: http://java.sun.com/docs/codeconv/
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            // ... etc. ...(2)Don't redeclare class members in a method as its local variable. Your class members become eternally null, a hellish null.
    how to make them work when clicked on(3)Add action listener to them.

  • Adding a JButton when there's a paint method

    I'm creating a game application, sort of like a maze, and I want to add buttons to the levelOne panel to be able to move around the maze. When I add the buttons to the panel they don't appear, I assume the paint method is the reason for this. here's my code, I have 3 files, ill post the user_interface, and the levels class, where the level is created and where i tried to add the button. I tried putting the buttons in a JOptionPane, but then my JMenu wouldn't work at the same time the OptionPane was opened. If anyone knows a way around this instead, please let me know. I also tried using a separate class with a paintComponent method in it, and then adding the button (saw on a forum, not sure if it was this one), but that didn't work either. Also, if there is a way just to simply have the user press the directional keys on the keyboard and have the program perform a certain function when certain keys are pressed, I'd like to know, as that would solve my whole problem. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
    static Levels l = new Levels ();
    static Delay d = new Delay ();
    private Container contentPane = getContentPane ();
    private JPanel main, levelOne;
    private String level;
    private CardLayout cc = new CardLayout ();
    private GridBagConstraints gbc = new GridBagConstraints ();
    private JPanel c = new JPanel ();
    private String label = "MainMenu";
    public User_Interface ()
    //Generates the User-Interface
    super ("Trapped");
    main = new JPanel ();
    GridBagLayout gbl = new GridBagLayout ();
    main.setLayout (gbl);
    c.setLayout (cc);
    // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
    c.add (main, "Main Page");
    contentPane.add (c, BorderLayout.CENTER);
    cc.show (c, "Main Page");
    levelOne = new JPanel ();
    levelOne.setLayout (new GridBagLayout ());
    levelOne.setBackground (Color.black);
    c.add (levelOne, "LevelOne");
    JMenuBar menu = new JMenuBar ();
    JMenu file = new JMenu ("File");
    JMenu help = new JMenu ("Help");
    JMenuItem about = new JMenuItem ("About");
    JMenuItem mainmenu = new JMenuItem ("Main Menu");
    mainmenu.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    cc.show (c, "Main Page");
    label = "MainMenu";
    JMenuItem newGame = new JMenuItem ("New Game");
    newGame.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    l.xCord = 2;
    l.yCord = 2;
    l.xLoc = 140;
    l.yLoc = 140;
    JPanel entrance = new JPanel ();
    entrance.setLayout (new FlowLayout ());
    c.add (entrance, "Entrance");
    label = "Entrance";
    level = "ONE";
    cc.show (c, "Entrance");
    JMenuItem loadgame = new JMenuItem ("Load Game");
    JMenuItem savegame = new JMenuItem ("Save Game");
    JMenuItem exit = new JMenuItem ("Exit");
    exit.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    JFrame frame = new JFrame ();
    frame.setLocation (10, 10);
    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
    System.exit (0);
    file.add (about);
    file.add (mainmenu);
    file.add (newGame);
    file.add (loadgame);
    file.add (savegame);
    file.add (exit);
    menu.add (file);
    menu.add (help);
    setJMenuBar (menu);
    //Sets the size of the container (columns by rows)
    setSize (750, 550);
    //Sets the location of the container
    setLocation (10, 10);
    //Sets the background colour to a dark blue colour
    main.setBackground (Color.black);
    //Makes the container visible
    setVisible (true);
    public void paint (Graphics g)
    super.paint (g);
    g.setColor (Color.white);
    if (label == "MainMenu")
    for (int x = 0 ; x <= 50 ; ++x)
    g.setColor (Color.white);
    g.setFont (new Font ("Arial", Font.BOLD, x));
    g.drawString ("T R A P P E D", 100, 125);
    d.delay (10);
    if (x != 50)
    g.setColor (Color.black);
    g.drawString ("T R A P P E D", 100, 125);
    if (label == "Entrance")
    l.Entrance ("ONE", g);
    label = "LevelOne";
    if (label == "LevelOne")
    l.LevelOne (g, levelOne, gbc);
    label = "";
    public static void main (String[] args)
    // calls the program
    User_Interface application = new User_Interface ();
    application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Levels extends Objects
    private JFrame frame = new JFrame ();
    //Sets location, size, and visiblity to the frame where the JOptionPane
    //will be placed
    frame.setLocation (600, 600);
    frame.setSize (1, 1);
    frame.setVisible (false);
    public int xCord = 2;
    public int yCord = 2;
    public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
    ***Trying to add the button, doesn't appear. Tried adding to the container, and any JPanel i had created***
    JButton button1 = new JButton ("TEST");
    one.add (button1);
    g.setColor (Color.white);
    g.fillRect (500, 100, 200, 300);
    g.setColor (Color.black);
    g.drawRect (500, 100, 200, 300);
    g.setFont (new Font ("Verdana", Font.BOLD, 25));
    g.setColor (Color.black);
    g.drawString ("LEVEL ONE", 525, 80);
    //ROW ONE
    counter = -80;
    counter2 = 200;
    for (int a = 1 ; a <= 7 ; ++a)
    if (xCord < a && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
    if (xCord > a - 1 && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
    counter += 40;
    counter2 += 40;
    *****Theres 9 more rows, just edited out to save space****
    int y = 100;
    int x = 100;
    for (int a = 0 ; a < 20 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    y += 40;
    if (a == 9)
    x += 320;
    y = 100;
    x = 140;
    y = 100;
    for (int a = 0 ; a < 14 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    x += 40;
    if (a == 6)
    x = 140;
    y += 360;
    g.setColor (Color.black);
    g.drawRect (100, 100, 360, 400);
    ImageIcon[] images = new ImageIcon [4];
    images [0] = new ImageIcon ("arrow_left.gif");
    images [1] = new ImageIcon ("arrow_up.gif");
    images [2] = new ImageIcon ("arrow_down.gif");
    images [3] = new ImageIcon ("arrow_right.gif");
    int direction = -1;
    *****This is where I tried to have the OptionPane show the directional buttons******
    //frame.setVisible (true);
    // direction = JOptionPane.showOptionDialog (frame, "Choose Your Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
    // JOptionPane.QUESTION_MESSAGE,
    // null,
    // images,
    // images [3]);
    // if (direction == 0)
    // if (xCord - 1 > 0)
    // xCord -= 1;
    // xLoc += 40;
    // if (direction == 1)
    // if (yCord - 1 > 0)
    // yCord -= 1;
    // yLoc += 40;
    // if (direction == 2)
    // if (yCord + 1 < 9)
    // yCord += 1;
    // yLoc -= 40;
    // if (direction == 3)
    // if (xCord + 1 < 13)
    // xCord += 1;
    // xLoc -= 40;
    //LevelOne (g, one, gbc);
    }

    i tried adding a keylistener, that didn't work too well, i had tried to add it to a button and a textarea which i added to the 'one' frame, it didn't show up, and it didn't work. How would i go about changing the paint method so that it doesn't contain any logic? That's the only way I could think of getting the program to move forward in the game. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
        static Levels l = new Levels ();
        static Delay d = new Delay ();
        private Container contentPane = getContentPane ();
        private JPanel main, levelOne;
        private String level;
        private CardLayout cc = new CardLayout ();
        private GridBagConstraints gbc = new GridBagConstraints ();
        private JPanel c = new JPanel ();
        private String label = "MainMenu";
        public User_Interface ()
            //Generates the User-Interface
            super ("Trapped");
            main = new JPanel ();
            GridBagLayout gbl = new GridBagLayout ();
            main.setLayout (gbl);
            c.setLayout (cc);
            // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
            c.add (main, "Main Page");
            contentPane.add (c, BorderLayout.CENTER);
            cc.show (c, "Main Page");
            levelOne = new JPanel ();
            levelOne.setLayout (new GridBagLayout ());
            levelOne.setBackground (Color.black);
            c.add (levelOne, "LevelOne");
            JMenuBar menu = new JMenuBar ();
            JMenu file = new JMenu ("File");
            JMenu help = new JMenu ("Help");
            JMenuItem about = new JMenuItem ("About");
            JMenuItem mainmenu = new JMenuItem ("Main Menu");
            mainmenu.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    cc.show (c, "Main Page");
                    label = "MainMenu";
            JMenuItem newGame = new JMenuItem ("New Game");
            newGame.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    l.xCord = 2;
                    l.yCord = 2;
                    l.xLoc = 140;
                    l.yLoc = 140;
                    JPanel entrance = new JPanel ();
                    entrance.setLayout (new FlowLayout ());
                    c.add (entrance, "Entrance");
                    label = "Entrance";
                    level = "ONE";
                    cc.show (c, "Entrance");
            JMenuItem loadgame = new JMenuItem ("Load Game");
            JMenuItem savegame = new JMenuItem ("Save Game");
            JMenuItem exit = new JMenuItem ("Exit");
            exit.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    JFrame frame = new JFrame ();
                    frame.setLocation (10, 10);
                    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);
            file.add (about);
            file.add (mainmenu);
            file.add (newGame);
            file.add (loadgame);
            file.add (savegame);
            file.add (exit);
            menu.add (file);
            menu.add (help);
            setJMenuBar (menu);
            //Sets the size of the container (columns by rows)
            setSize (750, 550);
            //Sets the location of the container
            setLocation (10, 10);
            //Sets the background colour to a dark blue colour
            main.setBackground (Color.black);
            //Makes the container visible
            setVisible (true);
        public void paint (Graphics g)
            super.paint (g);
            g.setColor (Color.white);
            if (label == "MainMenu")
                for (int x = 0 ; x <= 50 ; ++x)
                    g.setColor (Color.white);
                    g.setFont (new Font ("Arial", Font.BOLD, x));
                    g.drawString ("T    R    A    P    P    E    D", 100, 125);
                    d.delay (10);
                    if (x != 50)
                        g.setColor (Color.black);
                        g.drawString ("T    R    A    P    P    E    D", 100, 125);
            if (label == "Entrance")
                l.Entrance ("ONE", g);
                label = "LevelOne";
            if (label == "LevelOne")
                l.LevelOne (g, levelOne, gbc);
                label = "";
            //g.setColor (new Color
        public static void main (String[] args)
            // calls the program
            User_Interface application = new User_Interface ();
            application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.ActionMap;
    import javax.swing.plaf.*;
    public class Levels extends Objects
        implements KeyListener
        //static final String newline = System.getProperty ("line.separator");
        JButton button;
        private JFrame frame = new JFrame ();
            //Sets location, size, and visiblity to the frame where the JOptionPane
            //will be placed
            frame.setLocation (600, 600);
            frame.setSize (1, 1);
            frame.setVisible (false);
        JButton button1;
        public int xCord = 2;
        public int yCord = 2;
        public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
        //    button = new JButton ("TEST");
        //    ButtonHandler handler = new ButtonHandler ();
         //   button.addActionListener (handler);
          //  one.add (button);
            g.setColor (Color.white);
            g.fillRect (500, 100, 200, 300);
            g.setColor (Color.black);
            g.drawRect (500, 100, 200, 300);
            g.setFont (new Font ("Verdana", Font.BOLD, 25));
            g.setColor (Color.black);
            g.drawString ("LEVEL ONE", 525, 80);
            //ROW ONE
            counter = -80;
            counter2 = 200;
            for (int a = 1 ; a <= 7 ; ++a)
                if (xCord < a && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
                if (xCord > a - 1 && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
                counter += 40;
                counter2 += 40;
            int y = 100;
            int x = 100;
            for (int a = 0 ; a < 20 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                y += 40;
                if (a == 9)
                    x += 320;
                    y = 100;
            x = 140;
            y = 100;
            for (int a = 0 ; a < 14 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                x += 40;
                if (a == 6)
                    x = 140;
                    y += 360;
            g.setColor (Color.black);
            g.drawRect (100, 100, 360, 400);
            ImageIcon[] images = new ImageIcon [4];
            images [0] = new ImageIcon ("arrow_left.gif");
            images [1] = new ImageIcon ("arrow_up.gif");
            images [2] = new ImageIcon ("arrow_down.gif");
            images [3] = new ImageIcon ("arrow_right.gif");
            int direction = -1;
            //frame.setVisible (true);
            // direction = JOptionPane.showOptionDialog (frame, "Choose Your //\Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
            //         JOptionPane.QUESTION_MESSAGE,
            //         null,
            //         images,
            //         images [3]);
            // if (direction == 0)
            //     if (xCord - 1 > 0)
            //         xCord -= 1;
            //         xLoc += 40;
            // if (direction == 1)
            //     if (yCord - 1 > 0)
            //         yCord -= 1;
            //         yLoc += 40;
            // if (direction == 2)
            //     if (yCord + 1 < 9)
            //         yCord += 1;
            //         yLoc -= 40;
            // if (direction == 3)
            //     if (xCord + 1 < 13)
            //         xCord += 1;
            //         xLoc -= 40;
            one.addKeyListener (this);
            // one.add (button1);
            if (xCord == 1)
                LevelOne (g, one, gbc);
        /** Handle the key typed event from the text field. */
        public void keyTyped (KeyEvent e)
        /** Handle the key pressed event from the text field. */
        public void keyPressed (KeyEvent e)
            if (e.getSource () == "Up")
                JOptionPane.showMessageDialog (null, "Hi", "Hi", 0, null);
        /** Handle the key released event from the text field. */
        public void keyReleased (KeyEvent e)
            // displayInfo (e, "KEY RELEASED: ");
    }

  • Image in a JFrame

    I want to display an image (.jpg) in a JFrame.
    How?
    I'm using Containers and setBounds for the JButtons in the JFrame.

    Hi,
    By default a JFrame uses BorderLayout manager. You don't need to setBounds because the layout manager will override them anyway. If the JLabel is the only thing in the frame then the previous poster code will work correctly. If it doesn't display, then you are doing something different and you should show us some code and we can tell you what ...
    Regards,
    Manfred.

  • Jbutton to open a htm file in browser - simple question

    not sure where to look for this, but its a simple question
    I just want to get a jbutton (from a jFrame)to open a local htm page eg:
    When pressing the button open:
    C:\Documents and Settings\****\My Documents\profile.htm
    - Open this with any browser
    any pointers to look in the right direction, couldn't find it with search
    I dont want to use a JEditorPane to display the htm, just open any browser
    Edited by: Mr_Tuition on Dec 7, 2007 3:40 AM

    I also wont be able to use it to open an local file which will be set up differently on each computer:
    C:\\Documents and Settings\\***\\My Documents\\JavaProjX\\Preview\\profile.htmI want to use just: Preview\\profile.htm so it opens from the same location with different users, but
    try { Process process = Runtime.getRuntime().exec("C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE Preview\\profile.htm");}
         catch(IOException e) { System.out.println("could open IE");}opens: http://preview/profile.htm (incorrect location)
    I have just found I can use System.getProperty("user.dir"); to get the location of my program (i think)
    Edited by: Mr_Tuition on Dec 7, 2007 4:25 AM

  • Problem Manipulating JFrames

    Ok,
    I'm currently trying to figure out what's going on with my code (see below). Basically, when you run the program, it builds and displays a options JFrame window. Once you click Ok, it closes the current window, prompts for necessary input, builds and displays an output window, and starts to process data. Ok, my code works great, but when I run the program and it comes time to output data to the output window, it doesn't update the window in real time as it's processing the data, it waits until the program is done executing and processing data, but if I cancel out the code that builds and displays the options window, it works fine and updates the output window as it's processing each value. I've tried several methods moving the code around, setting setVisible() at different times and whatnot. The only way I've gotthe output window to update in real time is commenting out the call to display the options window. I absolutely cannot figure out why this is occurring. Any help is greatly appreciated! Thanks!
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    import java.awt.*;
    import java.lang.*;
    public class urlCheck extends JPanel implements ActionListener, ItemListener {
        static File outFile;
        static int countRec;
        static JButton okButton;
        static JFrame oframe;
        static JFrame frame;
        static JPanel panel;
        static JPanel opanel;
        static JScrollPane sp;
        static JLabel jl;
        static JTextArea jt;
        static JCheckBox netCheck;
        static JCheckBox orgCheck;
        static JCheckBox bizCheck;
        static boolean runNetCheck = false;
      public static void main (String args[]) throws IOException {
          displayOptions();
          //Testing call...
          //mainCall();
      public static void displayOptions(){
            FlowLayout fl = new FlowLayout();
            oframe = new JFrame("Options");
            opanel = new JPanel();
            opanel.setLayout(fl);
            //JCheckBox wwwCheck = new JCheckBox("Check www.");
            netCheck = new JCheckBox("Check .net");
            orgCheck = new JCheckBox("Check .org");
            bizCheck = new JCheckBox("Check .biz");
            okButton = new JButton("Ok");
            //opanel.add(wwwCheck);
            opanel.add(netCheck);
            opanel.add(orgCheck);
            opanel.add(bizCheck);
            opanel.add(okButton);
            oframe.add(opanel);
            oframe.setSize(400,100);
            oframe.setLocation(300,300);
            oframe.setVisible(true);
            oframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            okButton.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent evt) {
                oframe.setVisible(false);
                try {
                  mainCall();
                catch (IOException f) {
            netCheck.addItemListener(new ItemListener() {
              public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == 1) {
                  runNetCheck = true;
      public static void displayOutput() {
        frame = new JFrame("An Output Window");
        panel = new JPanel();
        jt = new JTextArea(19,25);
        sp = new JScrollPane(jt);
        jl = new JLabel();
        jl.setText("");
        panel.add(sp);
        panel.add(jl);
        frame.add(panel);
        frame.setSize(300,375);
        frame.setLocation(300,300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      public static void mainCall() throws IOException {
        FileReader fr = new FileReader(getFile());
        FileWriter INUSE = new FileWriter(outFile.toString().substring(0,3)+"urls_notavailable.txt");
        FileWriter AVAIL = new FileWriter(outFile.toString().substring(0,3)+"urls_available.txt");
        BufferedReader br = new BufferedReader(fr);
        RandomAccessFile randFile = new RandomAccessFile(outFile,"r");
        FileReader fileRead = new FileReader(outFile);
        LineNumberReader lineRead = new LineNumberReader(fileRead);
        //Comment out when running displayOptions in main
        //displayOutput();
        getNumOfLines(randFile, lineRead, fileRead);
        String s;
        int i = 1;
        while ((s = br.readLine()) != null) {
          String domain = ".com"; 
          jt.append("Testing URL: " + "http://"+s+domain+"\n");
          jl.setText("Testing URL: " + i + " of " + countRec);
          if (runCheck(s,domain)) {
            INUSE.write(s+domain+"\n");     
          else {
            AVAIL.write(s+domain+"\n");   
          i++;
          if (runNetCheck) {
            domain = ".net";
          jt.append("Testing URL: " + "http://"+s+domain+"\n");
          jl.setText("Testing URL: " + i + " of " + countRec);
          if (runCheck(s,domain)) {
            INUSE.write(s+domain+"\n");     
          else {
            AVAIL.write(s+domain+"\n");   
          i++;
        fr.close();
        INUSE.close();
        AVAIL.close();
        jt.append("--Process Complete--");
        JOptionPane.showMessageDialog(null,"Created Files: "
    +outFile.toString().substring(0,3)+"urls_available.txt &"
    +outFile.toString().substring(0,3)+"urls_notavailable.txt","Output Files",JOptionPane.INFORMATION_MESSAGE);
      public static File getFile() {
        final JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Open Line-Delimited Word Dictionary File");
        fc.setApproveButtonText("Open File");
        int returnVal = fc.showOpenDialog(null);
        outFile = fc.getSelectedFile();
        return outFile;
      public static boolean runCheck(String address, String domain) {
         try {
        // Construct data
        String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
        data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
        // Send data
        URL url = new URL("http://"+address+domain+":80");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        if (rd.ready()) { return false; }
        wr.close();
        rd.close();
        catch (Exception e) {
          return true;   
        return false;
      public static void getNumOfLines(RandomAccessFile randFile, LineNumberReader lineRead, FileReader fileRead) {
        try
            long lastRec=randFile.length();
            randFile.close();
            lineRead.skip(lastRec);
            countRec=lineRead.getLineNumber();
            if (runNetCheck) { countRec = countRec * 2; }
            jl.setText(String.valueOf(countRec));
            fileRead.close();
            lineRead.close();
        catch(IOException e)
      public void actionPerformed(ActionEvent e) {
        public void itemStateChanged(ItemEvent e) {    
    }Edited by: Dave__ on Oct 7, 2008 9:40 AM

    You've likely got a concurrency issue where a long-processing method is freezing Swing's EDT. Have you tried calling long-running processes in a background thread, such as by using a SwingWorker object?

  • JFrame (menubar) problem

    Hi,
    I have a JFrame with few JPanels on it ( those in turn have JButtons etc). JFrame has the ussual menubar ( set using setJMenuBar) . Menubar is not accessiable using <TAB> . All other items are. Any ideas?
    Thank you in advence for any help.

    Why do you want it to be accessible through pressing tab?
    If you haven't noticed, you can't <TAB> your way to the menubar in any normal GUI application on any platform.

  • JButton not visible after use of Jpanel removeAll ..

    Hi!
    I'm having a calculator class that inherits JFrame. I need to add more buttons after setting an option from the (view) menu bar .. (from normal to scientific calculator). I needed to use the JPanel removeAll method and then add the normal buttons plus extra buttons. But the problem is, that the Buttons are only visible when I touch them with the mouse.
    Does anybody know why? Thanks for your help!
    See code below (still in construction phase):
    Name: Hemanth. B
    Original code from Website: java-swing-tutorial.html
    Topic : A basic Java Swing Calculator
    Conventions Used in Source code
         1. All JLabel components start with jlb*
         2. All JPanel components start with jpl*
         3. All JMenu components start with jmenu*
         4. All JMenuItem components start with jmenuItem*
         5. All JDialog components start with jdlg*
         6. All JButton components start with jbn*
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Calculator extends JFrame
    implements ActionListener {
    // Constants
    final int NORMAL = 0;
    final int SCIENTIFIC = 8;
    final int MAX_INPUT_LENGTH = 20;
    final int INPUT_MODE = 0;
    final int RESULT_MODE = 1;
    final int ERROR_MODE = 2;
    // Variables
    int displayMode;
    int calcType = SCIENTIFIC;
    boolean clearOnNextDigit, percent;
    double lastNumber;
    String lastOperator, title;
    private JMenu jmenuFile, jmenuView, jmenuHelp;
    private JMenuItem jmenuitemExit, jmenuitemAbout;
    private JRadioButtonMenuItem jmenuItemNormal = new JRadioButtonMenuItem("Normal");
    private JRadioButtonMenuItem jmenuItemScientific = new JRadioButtonMenuItem("Scientific");
    private     ButtonGroup viewMenuButtonGroup = new ButtonGroup();
    private JLabel jlbOutput;
    private JButton jbnButtons[];
    private JPanel jplButtons, jplMaster, jplBackSpace, jplControl;
    * Font(String name, int style, int size)
    Creates a new Font from the specified name, style and point size.
    Font f12 = new Font("Verdana", 0, 12);
    Font f121 = new Font("Verdana", 1, 12);
    // Constructor
    public Calculator(String title) {
    /* Set Up the JMenuBar.
    * Have Provided All JMenu's with Mnemonics
    * Have Provided some JMenuItem components with Keyboard Accelerators
         //super(title);
         this.title = title;
         //displayCalculator(title);
    }     //End of Contructor Calculator
    private void displayCalculator (String title) {
         //add WindowListener for closing frame and ending program
         addWindowListener (
         new WindowAdapter() {     
         public void windowClosed(WindowEvent e) {
         System.exit(0);
         //setResizable(false);
    //Set frame layout manager
         setBackground(Color.gray);
         validate();
         createMenuBar();
         createMasterPanel();      
         createDisplayPanel();
         clearAll();
         this.getContentPane().validate();
         requestFocus();
         pack();
         //getContentPane().
         setVisible(true);
    private void createMenuBar() {
    jmenuFile = new JMenu("File");
    jmenuFile.setFont(f121);
    jmenuFile.setMnemonic(KeyEvent.VK_F);
    jmenuitemExit = new JMenuItem("Exit");
    jmenuitemExit.setFont(f12);
    jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X,
                                            ActionEvent.CTRL_MASK));
    jmenuFile.add(jmenuitemExit);
    jmenuView = new JMenu("View");
    jmenuFile.setFont(f121);
    jmenuFile.setMnemonic(KeyEvent.VK_W);
    jmenuItemNormal.setMnemonic(KeyEvent.VK_N);
    viewMenuButtonGroup.add(jmenuItemNormal);
    jmenuView.add(jmenuItemNormal);
    jmenuItemScientific.setMnemonic(KeyEvent.VK_S);
    viewMenuButtonGroup.add(jmenuItemScientific);
    jmenuView.add(jmenuItemScientific);
    if (jmenuItemNormal.isSelected() == false &&
    jmenuItemScientific.isSelected() == false)
    jmenuItemScientific.setSelected(true);
         jmenuHelp = new JMenu("Help");
         jmenuHelp.setFont(f121);
         jmenuHelp.setMnemonic(KeyEvent.VK_H);
         jmenuitemAbout = new JMenuItem("About Calculator");
         jmenuitemAbout.setFont(f12);
         jmenuHelp.add(jmenuitemAbout);
         JMenuBar menubar = new JMenuBar();
         menubar.add(jmenuFile);
         menubar.add(jmenuView);
         menubar.add(jmenuHelp);
         setJMenuBar(menubar);
         jmenuItemNormal.addActionListener(this);
         jmenuItemScientific.addActionListener(this);
         jmenuitemAbout.addActionListener(this);
         jmenuitemExit.addActionListener(this);
    private void createDisplayPanel() {
         if (jlbOutput != null) {
         jlbOutput.removeAll();     
         jlbOutput = new JLabel("0",JLabel.RIGHT);
         jlbOutput.setBackground(Color.WHITE);
         jlbOutput.setOpaque(true);
         // Add components to frame
         getContentPane().add(jlbOutput, BorderLayout.NORTH);
         jlbOutput.setVisible(true);
    private void createMasterPanel() {
         if (jplMaster != null) {
         jplMaster.removeAll();     
         jplMaster = new JPanel(new BorderLayout());
         createCalcButtons();      
         jplMaster.add(jplBackSpace, BorderLayout.WEST);
         jplMaster.add(jplControl, BorderLayout.EAST);
         jplMaster.add(jplButtons, BorderLayout.SOUTH);
         ((JPanel)getContentPane()).revalidate();
         // Add components to frame
         getContentPane().add(jplMaster, BorderLayout.SOUTH);
         jplMaster.setVisible(true);
    private void createCalcButtons() {
         int rows = 4;
         int cols = 5 + calcType/rows;
         jbnButtons = new JButton[31];
         // Create numeric Jbuttons
         for (int i=0; i<=9; i++) {
         // set each Jbutton label to the value of index
         jbnButtons[i] = new JButton(String.valueOf(i));
         // Create operator Jbuttons
         jbnButtons[10] = new JButton("+/-");
         jbnButtons[11] = new JButton(".");
         jbnButtons[12] = new JButton("=");
         jbnButtons[13] = new JButton("/");
         jbnButtons[14] = new JButton("*");
         jbnButtons[15] = new JButton("-");
         jbnButtons[16] = new JButton("+");
         jbnButtons[17] = new JButton("sqrt");
         jbnButtons[18] = new JButton("1/x");
         jbnButtons[19] = new JButton("%");
         jplBackSpace = new JPanel();
         jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));
         jbnButtons[20] = new JButton("Backspace");
         jplBackSpace.add(jbnButtons[20]);
         jplControl = new JPanel();
         jplControl.setLayout(new GridLayout(1, 2, 2 ,2));
         jbnButtons[21] = new JButton(" CE ");
         jbnButtons[22] = new JButton("C");
         jplControl.add(jbnButtons[21]);
         jplControl.add(jbnButtons[22]);
         //if (calcType == SCIENTIFIC) {     
         jbnButtons[23] = new JButton("s");
         jbnButtons[24] = new JButton("t");
         jbnButtons[25] = new JButton("u");
         jbnButtons[26] = new JButton("v");
         jbnButtons[27] = new JButton("w");
         jbnButtons[28] = new JButton("x");
         jbnButtons[29] = new JButton("y");
         jbnButtons[30] = new JButton("z");
    // Setting all Numbered JButton's to Blue. The rest to Red
         for (int i=0; i<jbnButtons.length; i++)     {
         //activate ActionListener
         System.out.println("add action listener: " + i);
         jbnButtons.addActionListener(this);
         //set button text font/colour
         jbnButtons[i].setFont(f12);
         jbnButtons[i].invalidate();
         if (i<10)
              jbnButtons[i].setForeground(Color.blue);               
         else
              jbnButtons[i].setForeground(Color.red);
         // container for Jbuttons
         jplButtons = new JPanel(new GridLayout(rows, cols, 2, 2));
    System.out.println("Cols: " + cols);      
         //Add buttons to keypad panel starting at top left
         // First row
         // extra left buttons for scientific
         if (calcType == SCIENTIFIC) {
         System.out.println("Adding Scientific buttons");
         setSize(400, 217);
         setLocation(200, 250);
         jplButtons.add(jbnButtons[23]);
         jplButtons.add(jbnButtons[27]);
         } else {
         setSize(241, 217);
         setLocation(200, 250);
         for(int i=7; i<=9; i++)          {
         jplButtons.add(jbnButtons[i]);
         // add button / and sqrt
         jplButtons.add(jbnButtons[13]);
         jplButtons.add(jbnButtons[17]);
         // Second row
         // extra left buttons for scientific
         if (calcType == SCIENTIFIC) {
         System.out.println("Adding Scientific buttons");
         jplButtons.add(jbnButtons[24]);
         jplButtons.add(jbnButtons[28]);
         for(int i=4; i<=6; i++)     {
         jplButtons.add(jbnButtons[i]);
         // add button * and x^2
         jplButtons.add(jbnButtons[14]);
         jplButtons.add(jbnButtons[18]);
         // Third row
         // extra left buttons for scientific
         if (calcType == SCIENTIFIC) {
         System.out.println("Adding Scientific buttons");
         jplButtons.add(jbnButtons[25]);
         jplButtons.add(jbnButtons[29]);
         for( int i=1; i<=3; i++) {
         jplButtons.add(jbnButtons[i]);
         //adds button - and %
         jplButtons.add(jbnButtons[15]);
         jplButtons.add(jbnButtons[19]);
         //Fourth Row
         // extra left buttons for scientific
         if (calcType == SCIENTIFIC) {
         System.out.println("Adding Scientific buttons");
         jplButtons.add(jbnButtons[26]);
         jplButtons.add(jbnButtons[30]);
         // add 0, +/-, ., +, and =
         jplButtons.add(jbnButtons[0]);
         jplButtons.add(jbnButtons[10]);
         jplButtons.add(jbnButtons[11]);
         jplButtons.add(jbnButtons[16]);
         jplButtons.add(jbnButtons[12]);
         jplButtons.revalidate();
    // Perform action
    public void actionPerformed(ActionEvent e){
         double result = 0;
         if(e.getSource() == jmenuitemAbout) {
         //JDialog dlgAbout = new CustomABOUTDialog(this,
         //                              "About Java Swing Calculator", true);
         //dlgAbout.setVisible(true);
         } else if(e.getSource() == jmenuitemExit) {
         System.exit(0);
    if (e.getSource() == jmenuItemNormal) {
    calcType = NORMAL;
    displayCalculator(title);
    if (e.getSource() == jmenuItemScientific) {
    calcType = SCIENTIFIC;
    displayCalculator(title);
    System.out.println("Calculator is set to "
    + (calcType == NORMAL?"Normal":"Scientific") + " :" + jbnButtons.length);      
         // Search for the button pressed until end of array or key found
         for (int i=0; i<jbnButtons.length; i++)     {
         if(e.getSource() == jbnButtons[i]) {
              System.out.println(i);
              switch(i) {
              case 0:
                   addDigitToDisplay(i);
                   break;
              case 1:
                   System.out.println("1");
                   addDigitToDisplay(i);
                   break;
              case 2:
                   addDigitToDisplay(i);
                   break;
              case 3:
                   addDigitToDisplay(i);
                   break;
              case 4:
                   addDigitToDisplay(i);
                   break;
              case 5:
                   addDigitToDisplay(i);
                   break;
              case 6:
                   addDigitToDisplay(i);
                   break;
              case 7:
                   addDigitToDisplay(i);
                   break;
              case 8:
                   addDigitToDisplay(i);
                   break;
              case 9:
                   addDigitToDisplay(i);
                   break;
              case 10:     // +/-
                   processSignChange();
                   break;
              case 11:     // decimal point
                   addDecimalPoint();
                   break;
              case 12:     // =
                   processEquals();
                   break;
              case 13:     // divide
                   processOperator("/");
                   break;
              case 14:     // *
                   processOperator("*");
                   break;
              case 15:     // -
                   processOperator("-");
                   break;
              case 16:     // +
                   processOperator("+");
                   break;
              case 17:     // sqrt
                   if (displayMode != ERROR_MODE) {
                   try {
                        if (getDisplayString().indexOf("-") == 0)
                        displayError("Invalid input for function!");
                        result = Math.sqrt(getNumberInDisplay());
                        displayResult(result);
                   catch(Exception ex) {
                        displayError("Invalid input for function!");
                        displayMode = ERROR_MODE;
                   break;
              case 18:     // 1/x
                   if (displayMode != ERROR_MODE){
                   try {
                        if (getNumberInDisplay() == 0)
                        displayError("Cannot divide by zero!");
                        result = 1 / getNumberInDisplay();
                        displayResult(result);
                   catch(Exception ex) {
                        displayError("Cannot divide by zero!");
                        displayMode = ERROR_MODE;
                   break;
              case 19:     // %
                   if (displayMode != ERROR_MODE){
                   try {
                        result = getNumberInDisplay() / 100;
                        displayResult(result);
                   catch(Exception ex) {
                        displayError("Invalid input for function!");
                        displayMode = ERROR_MODE;
                   break;
              case 20:     // backspace
                   if (displayMode != ERROR_MODE) {
                   setDisplayString(getDisplayString().substring(0,
                   getDisplayString().length() - 1));
                   if (getDisplayString().length() < 1)
                        setDisplayString("0");
                   break;
              case 21:     // CE
                   clearExisting();
                   break;
              case 22:     // C
                   clearAll();
                   break;
    void setDisplayString(String s) {
         jlbOutput.setText(s);
    String getDisplayString () {
         return jlbOutput.getText();
    void addDigitToDisplay(int digit) {
         if (clearOnNextDigit)
         setDisplayString("");
         String inputString = getDisplayString();
         if (inputString.indexOf("0") == 0) {
         inputString = inputString.substring(1);
         if ((!inputString.equals("0") || digit > 0)
                             && inputString.length() < MAX_INPUT_LENGTH) {
         setDisplayString(inputString + digit);
         displayMode = INPUT_MODE;
         clearOnNextDigit = false;
    void addDecimalPoint() {
         displayMode = INPUT_MODE;
         if (clearOnNextDigit)
         setDisplayString("");
         String inputString = getDisplayString();
         // If the input string already contains a decimal point, don't
         // do anything to it.
         if (inputString.indexOf(".") < 0)
         setDisplayString(new String(inputString + "."));
    void processSignChange() {
         if (displayMode == INPUT_MODE) {
         String input = getDisplayString();
         if (input.length() > 0 && !input.equals("0"))     {
              if (input.indexOf("-") == 0)
              setDisplayString(input.substring(1));
              else
              setDisplayString("-" + input);
         } else if (displayMode == RESULT_MODE) {
         double numberInDisplay = getNumberInDisplay();
         if (numberInDisplay != 0)
         displayResult(-numberInDisplay);
    void clearAll() {
         setDisplayString("0");
         lastOperator = "0";
         lastNumber = 0;
         displayMode = INPUT_MODE;
         clearOnNextDigit = true;
    void clearExisting() {
         setDisplayString("0");
         clearOnNextDigit = true;
         displayMode = INPUT_MODE;
    double getNumberInDisplay()     {
         String input = jlbOutput.getText();
         return Double.parseDouble(input);
    void processOperator(String op) {
         if (displayMode != ERROR_MODE) {
         double numberInDisplay = getNumberInDisplay();
         if (!lastOperator.equals("0")) {
              try {
              double result = processLastOperator();
              displayResult(result);
              lastNumber = result;
              catch (DivideByZeroException e)     {
              displayError("Cannot divide by zero!");
         } else {
         lastNumber = numberInDisplay;
         clearOnNextDigit = true;
         lastOperator = op;
    void processEquals() {
         double result = 0;
         if (displayMode != ERROR_MODE){
         try {
              result = processLastOperator();
              displayResult(result);
         catch (DivideByZeroException e) {
              displayError("Cannot divide by zero!");
         lastOperator = "0";
    double processLastOperator() throws DivideByZeroException {
         double result = 0;
         double numberInDisplay = getNumberInDisplay();
         if (lastOperator.equals("/")) {
         if (numberInDisplay == 0)
              throw (new DivideByZeroException());
         result = lastNumber / numberInDisplay;
         if (lastOperator.equals("*"))
         result = lastNumber * numberInDisplay;
         if (lastOperator.equals("-"))
         result = lastNumber - numberInDisplay;
         if (lastOperator.equals("+"))
         result = lastNumber + numberInDisplay;
         return result;
    void displayResult(double result){
         setDisplayString(Double.toString(result));
         lastNumber = result;
         displayMode = RESULT_MODE;
         clearOnNextDigit = true;
    void displayError(String errorMessage){
         setDisplayString(errorMessage);
         lastNumber = 0;
         displayMode = ERROR_MODE;
         clearOnNextDigit = true;
    public static void main(String args[]) {
         Calculator calci = new Calculator("My Calculator");
         calci.displayCalculator("My Calculator");
    System.out.println("Exitting...");
    }     //End of Swing Calculator Class.
    class DivideByZeroException extends Exception{
    public DivideByZeroException() {
         super();
    public DivideByZeroException(String s) {
         super(s);
    class CustomABOUTDialog extends JDialog implements ActionListener {
    JButton jbnOk;
    CustomABOUTDialog(JFrame parent, String title, boolean modal){
         super(parent, title, modal);
         setBackground(Color.black);
         JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
         StringBuffer text = new StringBuffer();
         text.append("Calculator Information\n\n");
         text.append("Developer:     Hemanth\n");
         text.append("Version:     1.0");
         JTextArea jtAreaAbout = new JTextArea(5, 21);
         jtAreaAbout.setText(text.toString());
         jtAreaAbout.setFont(new Font("Times New Roman", 1, 13));
         jtAreaAbout.setEditable(false);
         p1.add(jtAreaAbout);
         p1.setBackground(Color.red);
         getContentPane().add(p1, BorderLayout.CENTER);
         JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
         jbnOk = new JButton(" OK ");
         jbnOk.addActionListener(this);
         p2.add(jbnOk);
         getContentPane().add(p2, BorderLayout.SOUTH);
         setLocation(408, 270);
         setResizable(false);
         addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                   Window aboutDialog = e.getWindow();
                   aboutDialog.dispose();
         pack();
    public void actionPerformed(ActionEvent e) {
         if(e.getSource() == jbnOk) {
         this.dispose();
    Message was edited by:
    dungorg

    Swing related questions should be posted in the Swing forum.
    After adding or removing components from a visible panel you need to use panel.revalidate() and sometimes panel.repaint();
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • Updating JFrame content

    I'm developing a Poker game.
    I have done the GUI for the table, card, etc...
    But now I don't really know how/where to put things like
    - Request the system to deal cards
    - Update the table GUI after each time a turn is dealt (hole cards, flop, turn, river, showdown)
    My table GUI is in this form, I don't put my TableGUI code up here as it is too long.
    TableGUI {
    //Set up the table, display the table and actions panel (check, fold, bet, etc..)
    actionPerformed{
       private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
             TableGUI frame = new TableGUI();
       public static void main(String[] args) {
             //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                 createAndShowGUI();
    }Could some one tell me how/where to put those above?
    Thanks

    for changing cards here's a simple demo
    I used these 2 images (from google) - download/use at your own risk
    http://www.markhope.com/imagebank/poker/cards/aceofclubs.gif
    http://www.markhope.com/imagebank/poker/cards/aceofdiamonds.gif
    click the button to change the card - you would also have a cardback.gif - for face down
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      JLabel card = new JLabel(new ImageIcon("aceofclubs.gif"));
      public void buildGUI()
        JPanel p = new JPanel(new GridBagLayout());
        p.add(card,new GridBagConstraints());
        JButton btn = new JButton("Next Card");
        JFrame f = new JFrame();
        f.getContentPane().add(p,BorderLayout.CENTER);
        f.getContentPane().add(btn,BorderLayout.SOUTH);
        f.setSize(600,400);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            card.setIcon(new ImageIcon("aceofdiamonds.gif"));
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }for the betting I would image it would be set up to have the options in a popup,
    or dialog, and then
    actionPerformed(..) {
      if (e.getSource() == raise) {
        user.money() = user.money() - raiseAmount;
        computerTurn();
      else if (e.getSource() == call) {
        user.money() = user.money() - callAmount;
        determineWinner();
      else if(e.getSource() == fold){
        newGame();//which would include dealCards()
    }

  • Having Trouble Closing a JFrame With a Button Click in Swing

    I am brand new to Java so this is probably something really stupid.
    On my main form I have a table displaying records from a database. When you double click a record, it pops up a second form showing the details of that record. You can then edit the data in this second form and click a "save" button which saves the data to the database. I want this button to also close that second form, however in the button click event, the second form variable is null.
    Here is some code showing the basic concept:
    public class SampleForm {
        private JButton  saveJobButton;
        private JFrame frame;
        private JFrame editDetailFrame;
        public static void main(String[] args) {
            SampleForm sample = new SampleForm();
            sample.createMainFrame();
        public void createMainFrame() {
            frame = new JFrame();
            JComponent panel = buildPanel(); 
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.getContentPane().add(panel); 
            frame.pack();
            frame.setVisible(true);
        public void createEditFrame() {
            editDetailFrame = new JFrame();
            editDetailFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            JComponent editPanel = new SampleForm().buildDetailPanel();
            editDetailFrame.getContentPane().add(editPanel);
            editDetailFrame.pack();
            editDetailFrame.setVisible(true);
            editDetailFrame.validate();
    // save button
        private JButton getSaveJobButton() {
            if (saveJobButton == null) {
                saveJobButton = new JButton();
                saveJobButton.setText("Save Job");
                saveJobButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                       .. saves data to database.
                        // here is where I thought the dispose() should go but the editDetailFrame is null at this point.
                        editDetailFrame.dispose();
            return saveJobButton;
        }Any assistance would be much appreciated.

    That handles the NullPointer, but still doesn't close my second Frame. The editDetailFrame should not be null at this point as I am clicking a button on the editDetailFram itself so I think the problem is that I just don't have a reference to the actual object at that point and my variable is just an empty one.

Maybe you are looking for

  • List view problem in iTunes 10.  How to move Album/Artist description text.

    Starting with iTunes 10, in list view the Artist and Album name info was moved from underneath the Album Art in the "Artwork" column to the right of it. like the 1st screenshot below Is there a way to revert to having that info placed underneath the

  • Error while execution in background

    Hi all when iam using file download function , it is working fine in foreground but giving error dump while executing in background plz reply , its urgent

  • How do you see iTunes library size

    need to find out how many GB my iTunes music file is on iTunes.

  • Where can i download version 3.6.x?

    I need to submit a FAFSA with the Version 3.6.x!! Where can I go to, to download to my laptop? I have Windows Vista. Please Help!!!

  • Confused about ORA - 12560 Error

    OK, I just read the chapter on starting up and shutting down on Windows (Chapter 5 - Administering a Database on Windows). Here is what Oracle doc says, These instructions assume that a database instance has been created. (The previous chapter shows