JButton help

Hey everyone, I have a program that will be a slot game. basically what I need help with is I have a bet max button that should set the bet to 3. Then another button to spin the reels. When the spin button is pressed, the bet amout should be subtracted from the total credits. When I run the program and press the bet max button and then spin, my credits display correctly at 97 (origionlly set to 100). The second time I press the spin button, the credits display -296. Im not sure what I did wrong can someone look through my code and find my error. thx for the help.
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import javax.swing.JOptionPane;
import java.awt.event.*;
public class SpudSlotTest extends JComponent
     Image background = new ImageIcon("background1.png").getImage();
     Image[] images = new Image[10];
     int x = (int)(Math.random()*10);
     int y = (int)(Math.random()*10);
     int z = (int)(Math.random()*10);
    int frame = x;
    int frame2= y;
    int frame3= z;
    int bet = 0;
    int credits = 100;
    int win = 0;
    int spinCounter = 0;
    ImageIcon change = new ImageIcon("change.png");
     JButton button = new JButton(change);
     ImageIcon cashout = new ImageIcon("cashout.png");
     JButton button2 = new JButton(cashout);
     ImageIcon betone = new ImageIcon("betone.png");
     JButton button3 = new JButton(betone);
     ImageIcon betmax = new ImageIcon("betmax.png");
     JButton button4 = new JButton(betmax);
     ImageIcon spin = new ImageIcon("spin.png");
     JButton button5 = new JButton(spin);
    public void paintComponent(Graphics g)
         button.setSize(112, 95);
          button.setLocation(363, 538);
        button.addActionListener(new CashierListener());
        add(button);
        button2.setSize(112, 95);
        button2.setLocation(521, 538);
        button2.addActionListener(new CashoutListener());
        add(button2);
        button3.setSize(112, 95);
        button3.setLocation(667, 538);
        button3.addActionListener(new BetOneListener());
        add(button3);
        button4.setSize(112, 95);
        button4.setLocation(813, 538);
        button4.addActionListener(new BetMaxListener());
        add(button4);
        button5.setSize(171, 150);
        button5.setLocation(958, 487);
        button5.addActionListener(new MyStartListener());
        add(button5);
         Image image = images[frame];
         Image image2 = images[frame2];
         Image image3 = images[frame3];
        g.drawImage(background, 0, 0, this);
        g.drawImage(image, 199, 150, this);
           g.drawImage(image2, 475, 150, this);
        g.drawImage(image3, 750, 150, this);
        g.setColor(Color.red);
        g.setFont(new Font("Garamond", Font.BOLD, 50));
        g.drawString("" + bet, 770, 428);
        g.drawString("" + credits, 225, 428);
        g.drawString("" + win, 871, 428);
    public static void main(String[] args)
         SpudSlotTest slot = new SpudSlotTest();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1280, 800);
        frame.getContentPane().add(slot);
        frame.setVisible(true);
    public class MyStartListener implements ActionListener
         public void actionPerformed(ActionEvent e)
              credits = credits - bet;
              new Thread()
                        public void run()
                             images[0] = new ImageIcon(
                             "spud1.png").getImage();
                            images[1] = new ImageIcon(
                             "blank2.png").getImage();
                            images[2] = new ImageIcon(
                                 "cherries.png").getImage();
                            images[3] = new ImageIcon(
                             "blank3.png").getImage();
                            images[4] = new ImageIcon(
                             "triplebone.png").getImage();
                            images[5] = new ImageIcon(
                             "blank4.png").getImage();
                            images[6] = new ImageIcon(
                             "doublebone.png").getImage();
                            images[7] = new ImageIcon(
                             "blank5.png").getImage();
                            images[8] = new ImageIcon(
                             "bone.png").getImage();
                            images[9] = new ImageIcon(
                             "blank6.png").getImage();
                            int delay = 10;
                            try
                                int t = (int)(Math.random() * 10);
                                while (t<150)
                                     int a = (int)(Math.random()*10);
                                        int s = (int)(Math.random()*10);
                                        int d = (int)(Math.random()*10);
                                    frame = (frame+a)%images.length;
                                        frame2 = (frame2+s)%images.length;
                                        frame3 = (frame3+d)%images.length;
                                     Thread.sleep(delay);
                                        repaint();
                                        ++t;
                                    ++spinCounter;
                                    //JOptionPane.showMessageDialog(null, "" + spinCounter);
                                    wait();
                            catch (Exception e){}
                            //PayoutTest();
                 }.start();
    public class BetOneListener implements ActionListener
         public void actionPerformed(ActionEvent e)
              Graphics g = getGraphics();
             g.setColor(Color.black);
             g.setFont(new Font("Garamond", Font.BOLD, 50));
             if (bet<3)
                  g.drawString("" + bet, 770, 428);
                  ++bet;
                  g.setColor(Color.red);
                  g.drawString("" + bet, 770, 428);
             else
                  g.drawString("" + bet, 770, 428);
                  g.setColor(Color.red);
                  g.drawString("3", 770, 428);
     public class BetMaxListener implements ActionListener
          public void actionPerformed(ActionEvent e)
               Graphics g = getGraphics();
             g.setColor(Color.black);
             g.setFont(new Font("Garamond", Font.BOLD, 50));
             g.drawString("" + bet, 770, 428);
             g.setColor(Color.red);
             bet = 3;
             g.drawString("" + bet, 770, 428);
     public class CashoutListener implements ActionListener
          public void actionPerformed(ActionEvent e)
               System.exit(0);
     public class CashierListener implements ActionListener
          public void actionPerformed(ActionEvent e)
               System.exit(0);
}

Before we get to the real problem we have some design issues to discuss:
a) Your paintComponent(...) method should not be painting all the components. You should be using JLabels to display the text and images you want painted. Then you use LayoutManagers to position the labels the way you want them displayed. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers. You can mix and match layout managers to get the desired effect.
b) don't hardcode a frame size. You size of 1280 x 800 doesn't work for me since I run at 1024 x 768. If you want to maximize the frame then you can use:
frame.setExtendedState (JFrame.MAXIMIZED_BOTH); Even better is to use LayoutManagers and then just use the pack() method so the frame will size to the preferred size of all your components.
c) Don't load images in you ActionListener. Every time the button is clicked you reload the images.
d) don't invoke repaint() in your ActionListener code. This will repaint the entire frame. All you want to do is use a JLabel and then use setIcon(...) to change the image. The label will repaint itself. This way you don't need to keep an Image array of the current image.
e) When you catch an exception what good does it do when you don't display an error message? How do you expect to debug your program. Take a look at your try/catch block in the actionPerformed method.
Finally, the answer to your original question.
In your paintComponent(...) method you keep adding the ActionListener to your button. Since your Thread loops 150 times, 150 listeners get added, the next time more get added.......

Similar Messages

  • Jbutton Help!!Pls do help if know

    i have a program that can;t compile because it stated canot resolve the button symbol,just got one error!!can anyone help see why the problem appear and how to fix it.Just cut and paste to compile(urgent)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class bb extends JFrame implements ActionListener{
         public bb() {
              super("Software License Agreement");
              Container contentPane = getContentPane();
              JPanel panel = new JPanel();
              JCheckBox agree = new JCheckBox("I agree with all the term above");
              final JButton
                   accept = new JButton("Accept..."),          
                   decline = new JButton("Decline...");
                   accept.setEnabled(false);          
                   accept.setMnemonic('A');
                   decline.setEnabled(false);
                   decline.setMnemonic('D');
                   decline.addActionListener(this);
              String content = "testing" ;
              JLabel label = new JLabel("Important Notice!Please read this license agreement carefully before proceeding to the next page otherwise utilizing this product indicate your"),
              label2 = new JLabel("acknowledgement that you have already read the entire content agreement and agree all of its term.Scroll down to continue read below the page.");
                                       label.setFont(new Font("Arial", Font.PLAIN, 12));
                        label.setForeground(Color.darkGray);
                        label2.setForeground(Color.darkGray);
                        label2.setFont(new Font("Arial", Font.PLAIN, 12));
              JTextArea word= new JTextArea(content,23,68);
              word.setLineWrap(true);
              panel.add(new JScrollPane(word));
              panel.add(agree);
              agree.setSelected(false);
              word.setEditable(false);
              panel.setPreferredSize(new Dimension(785,470));
              panel.setBorder(BorderFactory.createTitledBorder("Contract"));
              contentPane.setLayout(new FlowLayout());
              contentPane.add(label, BorderLayout.NORTH);
              contentPane.add(label2);
              contentPane.add(panel);
              contentPane.add(accept,"Left");
              contentPane.add(decline,"Left");
              agree.addItemListener(new ItemListener() {
                   public void itemStateChanged(ItemEvent event) {
                        JCheckBox b = (JCheckBox)event.getSource();
                        accept.setEnabled(b.isSelected());
                        decline.setEnabled(b.isSelected());
                        //button.repaint();
         public void QuitScreen() {
         bb BB = new bb();
         programquit pQuit = new programquit(BB);
         pQuit.setVisible(true);
    public static void main(String args[]) {
              JFrame f = new bb();
              Toolkit theKit = f.getToolkit();
              Dimension wndSize = theKit.getScreenSize();
              f.setBounds(wndSize.width/10, wndSize.height/10,800,600);
              f.setVisible(true);
         f.setResizable(false);
    f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
         public void actionPerformed(ActionEvent e){
              if(e.getSource() == decline)
    QuitScreen();

    eg
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    class programquit extends Dialog /*implements ActionListener*/ {
        Label
        lConfirm = new Label("Are you sure ?");
        Button
        bYes = new Button("Yes"),
         bNo = new Button("No");
        Panel
        p1 = new Panel(),
         p2 = new Panel();
        public programquit(Frame owner) {
         this(owner, true);
        public programquit(Frame owner, boolean model) {
         super(owner, model);
         setTitle("Quiting EMS");
         setResizable(false);
         setSize(200, 150);
         setLocation(300, 200);
         setBackground(Color.black);
         setForeground(Color.green);
         addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                  setVisible(false);
         setLayout(new GridLayout(2, 1));
         p1.add(lConfirm);
         p2.add(bYes);
         p2.add(bNo);
         add(p1);
         add(p2);
         bYes.setBackground(Color.green);
         bYes.setForeground(Color.black);
         bNo.setBackground(Color.green);
         bNo.setForeground(Color.black);
         bYes.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  System.exit(0);
         bNo.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  setVisible(false);
    public class bb extends JFrame /*implements ActionListener*/ {
        public bb() {
         super("Software License Agreement");
         Container contentPane = getContentPane();
         JPanel panel = new JPanel();
         JCheckBox agree = new JCheckBox("I agree with all the term above");
         final JButton
             accept = new JButton("Accept..."),
             decline = new JButton("Decline...");
         accept.setEnabled(false);
         accept.setMnemonic('A');
         decline.setEnabled(false);
         decline.setMnemonic('D');
         decline.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e){
                  QuitScreen();
         String content = "testing" ;
         JLabel label = new JLabel("Important Notice!Please read this license agreement carefully before proceeding to the next page otherwise utilizing this product indicate your"),
             label2 = new JLabel("acknowledgement that you have already read the entire content agreement and agree all of its term.Scroll down to continue read below the page.");
         label.setFont(new Font("Arial", Font.PLAIN, 12));
         label.setForeground(Color.darkGray);
         label2.setForeground(Color.darkGray);
         label2.setFont(new Font("Arial", Font.PLAIN, 12));
         JTextArea word= new JTextArea(content,23,68);
         word.setLineWrap(true);
         panel.add(new JScrollPane(word));
         panel.add(agree);
         agree.setSelected(false);
         word.setEditable(false);
         panel.setPreferredSize(new Dimension(785,470));
         panel.setBorder(BorderFactory.createTitledBorder("Contract"));
         contentPane.setLayout(new FlowLayout());
         contentPane.add(label, BorderLayout.NORTH);
         contentPane.add(label2);
         contentPane.add(panel);
         contentPane.add(accept,"Left");
         contentPane.add(decline,"Left");
         agree.addItemListener(new ItemListener() {
              public void itemStateChanged(ItemEvent event) {
                  JCheckBox b = (JCheckBox)event.getSource();
                  accept.setEnabled(b.isSelected());
                  decline.setEnabled(b.isSelected());
    //button.repaint();
        public void QuitScreen() {
         bb BB = new bb();
         programquit pQuit = new programquit(BB);
         pQuit.setVisible(true);
        public static void main(String args[]) {
         JFrame f = new bb();
         Toolkit theKit = f.getToolkit();
         Dimension wndSize = theKit.getScreenSize();
         f.setBounds(wndSize.width/10, wndSize.height/10,800,600);
         f.setVisible(true);
         f.setResizable(false);
         f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }

  • JButton ---- HELP   please

    Hi good guys,
    am developing an application in java. I have added a button to panel which in
    turn is added to a frame. My problem is when i add the button(button with an image of icon of 19X19) to the panel(frame), it covers the whole frame. I want the button to be just small as it is in the frame so that the spaces under it can be empty. How do i do it?
    Thanks for your help.

    kap wrote:
    am developing an application in java. I have added a button to panel which in
    turn is added to a frame. My problem is when i add the button(button with an image of icon of 19X19) to the panel(frame), it covers the whole frame. This is due to the layout that the panel is using. My guess is that it is using the BorderLayout which if only one item is added to it without explicit instructions on where to put the item, it puts it in the center and covers the whole panel.
    I want the button to be just small as it is in the frame so that the spaces under it can be empty. How do i do it?You might want to set the panel's layout to be FlowLayout. Consider studying the LayoutManagers section of the Sun tutorials. Question: are you doing things in AWT (Panel, Frame, Button), or Swing (JPanel, JFrame, and JButton)? and if you are using AWT, why not Swing?

  • JButton Help Required

    Hi,
    I'm new to Java and thought I'd learn some basic things by creating a simple launcher application...
    My problem is that whenever I rollover a JButton, the previous JButton I rolled over is created below the current one (can be seen with transparency set).
    I assume I've done something wrong within my code, and would appreciate some help.
    There are two classes, Launcher and Applications, which can be seen below.
    Apologies if the code is hard to follow, I appreciate it's a bit messy.
    Thanks for your help in advance.
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.lang.reflect.Array;
    import javax.swing.filechooser.FileSystemView;
    class Launcher
         private JDialog w = new JDialog();
         private JButton[] btn = new JButton[50];
         private handler myHandler = new handler();
         public Applications apps = new Applications();
         int numapps = apps.getNumApps();
         int size = 16;
         int ypos, xpos;
         Color bgcolor = new Color(200, 200, 200, 50);
         SystemTray tray = SystemTray.getSystemTray();
         public static void main(String[] args)
            Launcher program = new Launcher();
              program.draw();
         void draw()
              w.setDefaultCloseOperation(w.DISPOSE_ON_CLOSE);
              w.setTitle("Launcher");
              w.setResizable(false);
              w.setUndecorated(true);
              Toolkit toolkit =  Toolkit.getDefaultToolkit();
              Dimension dim = toolkit.getScreenSize();
              ypos = ((dim.height - (size+2)*numapps)/2) -16;
              xpos = -size-4;
              drawItems();
              w.setSize(size+4, 2+(size+2)*numapps);
              w.setLocation(xpos, ypos);
              w.setVisible(true);
              Image img = Toolkit.getDefaultToolkit().getImage("icon0.png");
              PopupMenu popup = new PopupMenu();
              MenuItem mItem1 = new MenuItem("Exit");
              mItem1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        System.exit(0);
              popup.add(mItem1);
              TrayIcon trayIcon = new TrayIcon(img, "SimpleLauncher", popup);
              try {
                   tray.add(trayIcon);
              } catch (AWTException e) {
                   System.err.println("Problem loading Tray :icon");
              int x = 0;
              while (true)
                   PointerInfo a = MouseInfo.getPointerInfo();
                   Point b = a.getLocation();
                   x = (int) b.getX();
                   sleep(100);
                   if (x == 0)
                        w.toFront();
                        if (xpos < -1)
                             for (int i=-size-4; i<0; i++)
                                  xpos = i;
                                  w.setLocation(xpos, ypos);
                                  sleep(5);
                   } else if (x > size+4) {
                        if (xpos > -size-4)
                             for (int j=xpos; j>-size-5; j--)
                                  xpos = j;
                                  w.setLocation(xpos, ypos);
                                  sleep(5);
         void sleep(int a)
              try
                   Thread.sleep(a);
              catch (InterruptedException e)
                   e.printStackTrace();
         void drawItems()
              Box display = Box.createVerticalBox();
              display.add(Box.createVerticalStrut(2));
              for (int i=0; i<(numapps); i++)
                   String path = apps.getPath(i);
                   String x = System.getProperty("file.separator");
                   String pic = apps.getPic(i);
                   if (! pic.equals("*"))
                        URL u = this.getClass().getResource(pic + ".png");
                        ImageIcon image = new ImageIcon(u);
                        btn[i] = new JButton(image);
                   } else {
                        File file = new File(path);
                        Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
                        btn[i] = new JButton(icon);
                   btn.addActionListener(myHandler);
                   btn[i].setBorder(null);
                   btn[i].setBorderPainted(false);
                   btn[i].setPreferredSize(new Dimension(size,size));
                   btn[i].setBackground(bgcolor);
                   display.add(btn[i]);
                   display.add(Box.createVerticalStrut(2));
              JPanel panel = new JPanel();
              panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
              panel.setBackground(bgcolor);
              panel.add(display);
              w.add(panel);
         class handler implements ActionListener
    public void actionPerformed(ActionEvent e)
                   for (int j=xpos; j>-size-5; j--)
                        xpos = j;
                        w.setLocation(xpos, ypos);
                        sleep(5);
                   for (int i=0; i<(numapps); i++)
    if (e.getSource() == btn[i])
                             String path = apps.getPath(i);
                             try {                              
                                  Runtime rt = Runtime.getRuntime();
                                  Process pr = rt.exec(path);
                             catch(Exception error) {
                                  System.out.println(error.toString());
                                  error.printStackTrace();
                             break;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Applications
         private ArrayList<String> paths = new ArrayList<String>();
         private ArrayList<String> pics = new ArrayList<String>();
         private int numapps = 0;
         public static void main(String[] args)
         public Applications()
              loadApps();
         void loadApps()
    try {
    FileReader fr = new FileReader("config.txt");
    BufferedReader br = new BufferedReader(fr);
    String line;
                   String[] lineparts;
    while ((line = br.readLine()) != null)
                        lineparts = line.split(",");
    paths.add(lineparts[0]);
                        pics.add(lineparts[1]);
              //System.out.println(paths.get(numapps) +";"+ pics.get(numapps) +";"+ numapps);
                        numapps += 1;
    catch (FileNotFoundException e){
    throw new Error("File not found!");}
    catch (IOException e){
    throw new Error("Input error!");}
         public String getPath(int a)
              return paths.get(a);
         public String getPic(int a)
              String pic = pics.get(a);
              return pic;
         public int getNumApps()
              return numapps;

    whenever I rollover a JButton, the previous JButton I rolled over is created below the current one Well, I don't see that problem using JDK6 on XP. But I do see other problems. For example if you click on a button, then the button stays the blue color that was visible when the button was pressed.
    Anyway, I've always had problems when using an alpha value in the background color. The contract with Swing is that an opaque component must paint its background, therefore it doesn't matter if there is "garbage" under the component because the component will paint over top of it. But once you start using alpha values, then the "garbage" starts to show through. However, if a component is non-opaque, then the components parent is painted first before the component. Since a background with an alpha value is essentially a non-opaque component, I think Swing should be smart enough to treat it as such and paint the parent first.
    So my workaround is to make the component non-opaque and paint the background myself:
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.lang.reflect.Array;
    import javax.swing.filechooser.FileSystemView;
    class Launcher
         private JDialog w = new JDialog();
         private JButton[] btn = new JButton[50];
         int size = 16;
         int ypos, xpos;
         Color bgcolor = new Color(200, 200, 200, 10);
    //     Color bgcolor = new Color(200, 200, 200);
         public static void main(String[] args)
              Launcher program = new Launcher();
              program.draw();
         void draw()
              w.setDefaultCloseOperation(w.DISPOSE_ON_CLOSE);
              w.setTitle("Launcher");
              w.setResizable(false);
              w.setLocationByPlatform(true);
              drawItems();
              w.pack();
              w.setVisible(true);
              int x = 0;
         void drawItems()
              Box display = Box.createVerticalBox();
              display.add(Box.createVerticalStrut(2));
              for (int i=0; i<8; i++)
                   btn[i] = new JButton(String.valueOf(i))
                        public void paintComponent(Graphics g)
                             g.setColor( getBackground() );
                             g.fillRect(0, 0, getSize().width, getSize().height);
                             super.paintComponent(g);
                   btn.setOpaque(false);
                   btn[i].setBackground(bgcolor);
                   display.add(btn[i]);
                   display.add(Box.createVerticalStrut(2));
              JPanel panel = new JPanel()
                   public void paintComponent(Graphics g)
                        g.setColor( getBackground() );
                        g.fillRect(0, 0, getSize().width, getSize().height);
                        super.paintComponent(g);
              panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
              panel.setOpaque(false);
              panel.setBackground(bgcolor);
              panel.add(display);
              w.add(panel);

  • Getting values from JLabel[] with JButton[] help!

    Hello everyone!
    My problem is:
    I have created JPanel, i have an array of JButtons and array of JLabels, they are all placed on JPanel depending from record count in *.mdb table - JLabels have its own value selected from Access table.mdb! I need- each time i press some button,say 3rd button i get value showing from 3rd JLabel in some elsewere created textfield, if i have some 60 records and 60 buttons and 60 labels its very annoying to add for each button actionlistener and for each button ask for example jButton[1].addActionListener() ...{ jLabel[1].getText()......} and so on!
    Any suggestion will be appreciated! Thank you!

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        final int ROWS = 10;
        JPanel[] rows = new JPanel[ROWS];
        final JLabel[] labels = new JLabel[ROWS];
        JButton[] buttons = new JButton[ROWS];
        JPanel p = new JPanel(new GridLayout(ROWS,1));
        final JTextField tf = new JTextField(10);
        ActionListener listener = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tf.setText(labels[Integer.parseInt(((JButton)ae.getSource()).getName())].getText());
        for(int x = 0; x < ROWS; x++)
          labels[x] = new JLabel(""+(int)(Math.random()*10000));
          buttons[x] = new JButton("Button "+x);
          buttons[x].setName(""+x);
          buttons[x].addActionListener(listener);
          rows[x] = new JPanel(new GridLayout(1,2));
          rows[x].add(labels[x]);
          rows[x].add(buttons[x]);
          p.add(rows[x]);
        JFrame f = new JFrame();
        f.getContentPane().add(p,BorderLayout.CENTER);
        f.getContentPane().add(tf,BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • JButton help, icon +text position

    Hi, is it possible to have JButton with icon on far left and text between the icon and far right hand side?

    Yo can do it by using the setHorizontalTextPosition() method.
    here is one example
    import java.awt.*;//Frame
    import javax.swing.*;
    public class Test extends JFrame
         public Test()//Constructer. Creates the frame
              JButton bt = new JButton("Done", new ImageIcon("image.gif"));
              bt.setHorizontalTextPosition(AbstractButton.LEFT);
              setBounds(300,300,300,300);
              getContentPane().setLayout(new FlowLayout());
              getContentPane().add(bt);
              setVisible(true);//shows on the screen
         public static void main(String[] args)
              new Test();//Creates a new Instance of our class
    }

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

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

  • Help on Error

    I was testing one of the example code from the Java Tutorial, PasswordDemo.java, when i run it this error comes out..
    +++++++++++++++++++++++++++++++++++++++++++++++
    java.lang.NoClassDefFoundError: PasswordDemo (wrong name: components/PasswordDemo)
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
         at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    Exception in thread "main"
    Tool completed with exit code 1
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Can any one tell me why???

    Here is the code....
    package components;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Arrays;
    /* PasswordDemo.java requires no other files. */
    public class PasswordDemo extends JPanel
    implements ActionListener {
    private static String OK = "ok";
    private static String HELP = "help";
    private JFrame controllingFrame; //needed for dialogs
    private JPasswordField passwordField;
    public PasswordDemo(JFrame f) {
    //Use the default FlowLayout.
    controllingFrame = f;
    //Create everything.
    passwordField = new JPasswordField(10);
    passwordField.setActionCommand(OK);
    passwordField.addActionListener(this);
    JLabel label = new JLabel("Enter the password: ");
    label.setLabelFor(passwordField);
    JComponent buttonPane = createButtonPanel();
    //Lay out everything.
    JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
    textPane.add(label);
    textPane.add(passwordField);
    add(textPane);
    add(buttonPane);
    protected JComponent createButtonPanel() {
    JPanel p = new JPanel(new GridLayout(0,1));
    JButton okButton = new JButton("OK");
    JButton helpButton = new JButton("Help");
    okButton.setActionCommand(OK);
    helpButton.setActionCommand(HELP);
    okButton.addActionListener(this);
    helpButton.addActionListener(this);
    p.add(okButton);
    p.add(helpButton);
    return p;
    public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    if (OK.equals(cmd)) { //Process the password.
    char[] input = passwordField.getPassword();
    if (isPasswordCorrect(input)) {
    JOptionPane.showMessageDialog(controllingFrame,
    "Success! You typed the right password.");
    } else {
    JOptionPane.showMessageDialog(controllingFrame,
    "Invalid password. Try again.",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    //Zero out the possible password, for security.
    Arrays.fill(input, '0');
    passwordField.selectAll();
    resetFocus();
    } else { //The user has asked for help.
    JOptionPane.showMessageDialog(controllingFrame,
    "You can get the password by searching this example's\n"
    + "source code for the string \"correctPassword\".\n"
    + "Or look at the section How to Use Password Fields in\n"
    + "the components section of The Java Tutorial.");
    * Checks the passed-in array against the correct password.
    * After this method returns, you should invoke eraseArray
    * on the passed-in array.
    private static boolean isPasswordCorrect(char[] input) {
    boolean isCorrect = true;
    char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };
    if (input.length != correctPassword.length) {
    isCorrect = false;
    } else {
    isCorrect = Arrays.equals (input, correctPassword);
    //Zero out the password.
    Arrays.fill(correctPassword,'0');
    return isCorrect;
    //Must be called from the event dispatch thread.
    protected void resetFocus() {
    passwordField.requestFocusInWindow();
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event dispatch thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("PasswordDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    final PasswordDemo newContentPane = new PasswordDemo(frame);
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Make sure the focus goes to the right component
    //whenever the frame is initially given the focus.
    frame.addWindowListener(new WindowAdapter() {
    public void windowActivated(WindowEvent e) {
    newContentPane.resetFocus();
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    //Turn off metal's use of bold fonts
              UIManager.put("swing.boldMetal", Boolean.FALSE);
              createAndShowGUI();
    }

  • I need help putting my appet on the web. I keep getting an error. Thanks

    This is my code. It works as a .jar but i need it to run from the web. I posted the code and my errors. Please help if possible. I know the coding is quite messy but there are reasons for the mess. Please let me know what I'm doing wrong.
    This is the main class
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class testGUI2 extends JApplet
    testGUI2 t;
         //ALL OF THE QUESTIONS
         public testGUI2()
         {createGUI();
              /*try {
                          SwingUtilities.invokeAndWait(new Runnable() {
                              public void run() {
                                  createGUI();
                      } catch (Exception e) {
                          System.err.println("createGUI didn't complete successfully");
         }// end constructor main
         public  void createGUI()
              gameFrame g = new gameFrame();
              g.setOpaque(true);
              setContentPane(g);
              //JFrame testframe = new JFrame();
              //testframe.add(g);
              //testframe.setSize(500,500);
              //testframe.setVisible(true);
         public static void main(String[] args)
              testGUI2 t = new testGUI2();
              t.setSize(700,700);
         }//end main
    }//end class

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class gameFrame extends JPanel{
         private gameFrame gframe;
         private JLabel title, opLabel,scoreLabel,numberLabel;
         private JButton helpButton,nextButton,playButton,newgameButton,startButton;
         private JRadioButton choiceOne, choiceTwo, choiceThree;
         testGUI2 t;
         private ButtonGroup bgroup;
         private int choicenumber;
         private int score;
         private int i;
         ButtonHandler handle = new ButtonHandler();
         String[] choice1 = new String [20];
         String[] choice2 = new String [20];
         String[] choice3 = new String [20];
         int [] answernum = new int[20];
         String[] audio = new String[20];
         public gameFrame()
              super( new FlowLayout());
         choice1[1]="Hey Steve";
         choice2[1]= "I figured that u needed this";
         choice3[1]= "To test your site";
         answernum[1]=1;
         //audio[1]= "C:/Users/Matt/Desktop/tests/gamesounds/chimes.wav";
         choice1[2]="So here it is";
         choice2[2]= "Im running out of test lyrics";
         choice3[2]= "So im just gonna put lines i think of from songs";
         answernum[2]=2;
         choice1[3]="Here goes";
         choice2[3]= "love electricity";
         choice3[3]= "shockwave central power on the motherboard, yes";
         answernum[3]=3;
         choice1[4]="push up overload legendary heavy glow";
         choice2[4]= "never again will i be dishonored";
         choice3[4]= "and never again will i be reminded";
         answernum[4]=1;
              choice1[5]="were living within the world of the jaded";
              choice2[5]= "they killed inspiration";
              choice3[5]= "its my obligation to never again";
              answernum[5]=2;
              choice1[6]="40 40 dollar to the man that wanna go";
              choice2[6]= "20 20 to the sister when u take it";
              choice3[6]= " at the grocery sto";
              answernum[6]=3;
              choice1[7]="this is as far as i probably need to go";
              choice2[7]= "any further and im past my test zone";
              choice3[7]= "terminate test here i think";
              answernum[7]=1;
              choice1[8]="what";
              choice2[8]= "who";
              choice3[8]= "why";
              answernum[8]=2;
              choice1[9]="what";
              choice2[9]= "who";
              choice3[9]= "why";
              answernum[9]=1;
              choice1[10]="what";
              choice2[10]= "who";
              choice3[10]= "why";
              answernum[10]=3;
              choice1[11]="what";
              choice2[11]= "who";
              choice3[11]= "why";
              answernum[11]=2;
                   i=1;
                   Icon start = new ImageIcon("gameimages/start.gif");
                   Icon replay = new ImageIcon("gameimages/replay.gif");
    Icon help = new ImageIcon("gameimages/althelp.gif");
    Icon next = new ImageIcon("gameimages/altnext.gif");
    Icon play = new ImageIcon("gameimages/altplay.gif");
    startButton=new JButton(start);
    startButton.addActionListener(handle);
    startButton.setBorder(BorderFactory.createLineBorder(Color.black));
    numberLabel= new JLabel("Question #:"+Integer.toString(i));
    numberLabel.setFont(new Font("Times New Roman",Font.PLAIN,20));
    numberLabel.setForeground(Color.white);
    title=new JLabel("Lyrical Expert?",JLabel.CENTER);
    title.setFont(new Font("Times New Roman",Font.BOLD,48));
    title.setForeground(Color.white);
    playButton=new JButton(play);//puttin image in
    playButton.setBackground(Color.BLACK);
    playButton.setSize(100,50);
    playButton.setBorder(BorderFactory.createLineBorder(Color.gray));
    newgameButton= new JButton(replay);
    newgameButton.setVisible(false);
    newgameButton.setBorder(BorderFactory.createLineBorder(Color.gray));
    newgameButton.addActionListener(handle);
    scoreLabel= new JLabel("Score:");
    scoreLabel.setFont(new Font("Times New Roman",Font.PLAIN,20));
    scoreLabel.setForeground(Color.white);
    scoreLabel.setBackground(Color.BLACK);
    opLabel= new JLabel("0");
    opLabel.setFont(new Font("Times New Roman",Font.PLAIN,20));
    opLabel.setForeground(Color.white);
    opLabel.setBackground(Color.BLACK);
    nextButton=new JButton(next);//puttin image in
    nextButton.addActionListener(handle);
    nextButton.setBackground(Color.BLACK);
    nextButton.setSize(100,34);
    nextButton.setBorder(BorderFactory.createLineBorder(Color.gray));
    helpButton= new JButton(help);//puttin image in
    helpButton.setSize(78,75);
    helpButton.setBackground(Color.BLACK);
    helpButton.setBorder(BorderFactory.createLineBorder(Color.black));
    helpButton.addActionListener(handle);
    bgroup=new ButtonGroup();
    choiceOne= new JRadioButton("?");
    choiceTwo= new JRadioButton("?");
    choiceThree= new JRadioButton("?");
    choiceOne.setFont(new Font("Times New Roman",Font.PLAIN,20));
    choiceOne.setForeground(Color.white);
    choiceOne.setBackground(Color.BLACK);
    choiceTwo.setFont(new Font("Times New Roman",Font.PLAIN,20));
    choiceTwo.setForeground(Color.white);
    choiceTwo.setBackground(Color.BLACK);
    choiceThree.setFont(new Font("Times New Roman",Font.PLAIN,20));
    choiceThree.setForeground(Color.white);
    choiceThree.setBackground(Color.BLACK);
    choiceOne.addActionListener(handle);
    choiceTwo.addActionListener(handle);
    choiceThree.addActionListener(handle);
    bgroup.add(choiceOne);
    bgroup.add(choiceTwo);
    bgroup.add(choiceThree);
    choiceOne.setText(choice1[1]);
    choiceTwo.setText(choice2[1]);
    choiceThree.setText(choice3[1]);
    //changeLayout();
                   //gframe = new gameFrame();
                   GroupLayout layout = new GroupLayout(this);
                   this.setLayout(layout);
                   this.setBackground(Color.BLACK);
                   //layout.setAutoCreateGaps(true);
                   //layout.setAutoCreateContainerGaps(true);
                   layout.setVerticalGroup(
                        layout.createSequentialGroup()
                             .addComponent(title)
                                  .addGap(10)
                                  .addComponent(startButton)
                                  .addComponent(playButton)
                                  .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                       .addGroup(layout.createSequentialGroup()
                                            .addComponent(choiceOne)
                                            .addComponent(choiceTwo)
                                            .addComponent(choiceThree))
                                            .addGap(50)
                                       .addComponent(nextButton))
                             //.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,50,50)
                             .addComponent(newgameButton)
                             .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                             .addComponent(helpButton)
                             .addGap(120)
                             .addComponent(numberLabel)
                             .addGap(120)
                             .addComponent(scoreLabel)
                             .addComponent(opLabel)));
                   layout.setHorizontalGroup(
                        layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                             .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                             .addComponent(title)
                             .addGap(10)
                             .addComponent(startButton)
                             .addComponent(playButton))
                             .addGroup(layout.createSequentialGroup()
                                  .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                       .addComponent(choiceOne)
                                       .addComponent(choiceTwo)
                                       .addComponent(choiceThree))
                                       .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED,100,100)
                                  .addComponent(nextButton))
                             .addComponent(newgameButton)
                                  .addGroup(layout.createSequentialGroup()
                                       .addComponent(helpButton)
                                       .addGap(120)
                                       .addComponent(numberLabel)
                                       .addGap(120)
                                       .addComponent(scoreLabel)
                                       .addComponent(opLabel))));
              startButton.setVisible(true);
              nextButton.setVisible(false);
              playButton.setVisible(false);
              numberLabel.setVisible(false);
              scoreLabel.setVisible(false);
              opLabel.setVisible(false);
              choiceOne.setVisible(false);
              choiceTwo.setVisible(false);
              choiceThree.setVisible(false);
              }Edited by: Scubastevie on Jun 21, 2010 1:21 PM

  • Help with putting Frame inside Frame

    I have created two Frames: one with the code that works with the buttons (StudentsFile) and the second as a Tabbed Frame (TabbedPaneDemo).
    I want to put StudentsFile into one of the tabs. The files compile but when I run TabbedPaneDemo the window that is created in StudentsFile comes up but it is not in the Tabbed window. What Am I doing wrong?
    Any assistance would be appreciated.
    This is the portion of the TabbedPaneDemo where I put in the StudentsFile into Panel 1.
    public class TabbedPaneDemo extends JPanel {
        public TabbedPaneDemo() {
            super(new GridLayout(1, 1));
            JTabbedPane tabbedPane = new JTabbedPane();
            ImageIcon icon = createImageIcon("middle.gif");
            JComponent panel1 = makeTextPanel("Panel #1");      
           StudentsFile simpleTable = new StudentsFile();
            tabbedPane.addTab("Report", simpleTable);
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            JComponent panel2 = makeTextPanel("Panel #2");
            tabbedPane.addTab("Tab 2", icon, panel2,
                    "Does twice as much nothing");
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            JComponent panel3 = makeTextPanel("Panel #3");
            tabbedPane.addTab("Tab 3", icon, panel3,
                    "Still does nothing");
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            JComponent panel4 = makeTextPanel(
                    "Panel #4 (has a preferred size of 410 x 50).");
            panel4.setPreferredSize(new Dimension(410, 50));
            tabbedPane.addTab("Tab 4", icon, panel4,
                    "Does nothing at all");
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            //Add the tabbed pane to this panel.
            add(tabbedPane);
            //The following line enables to use scrolling tabs.
            tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        }This is the portion of the StudentsFile where I setup the Frame.
    public class StudentsFile extends JFrame
         //Sets Size of Frame
         private static final int WIDTH = 450;
         private static final int HEIGHT = 450;
         //Declares Text Fields
         private JTextField FNameTF, SIDTF, AddressTF, CityTF, StateTF, TelephoneTF ;
         //Declares Labels
         private JLabel FNameL, SIDL, AddressL, CityL, StateL, sheadingL,  TelephoneL, StatusL;
         //Declares Buttons
         private JButton openB, saveB, shelpB,sexitB, senterB ;
         private ButtonHandler bhHandler;
         //Declares Combobox that will list selections for teacher to select
         private JComboBox Selections;
         //Declares text areas     
         private JTextArea /*SoutputTA,*/ statusTA;
         //Declares filechooser for input/output file
         JFileChooser sfc = new JFileChooser();;
         //Creates object of StudentInformation
         private StudentInformation Studentdata = new StudentInformation();
    public StudentsFile()
         //sets title and size of frame
         setTitle("Student Entries");
         setSize(WIDTH,HEIGHT);
         setBackground(Color.red);
         //Gets the frame
         Container pane = getContentPane();
         pane.setLayout(null);
         pane.setBackground(Color.yellow);
         //Creates button handler
         bhHandler = new ButtonHandler();
         //creates label to be used on pane
         sheadingL = new JLabel ("Student Information Center",
                        SwingConstants.CENTER);
         //sets the labels
         FNameL     = new JLabel("Student Name");
         SIDL       = new JLabel("Student ID");
         AddressL   = new JLabel("Address");
         CityL      = new JLabel("City");
         StateL         = new JLabel ("State");
         TelephoneL = new JLabel ("Telephone");
         StatusL        = new JLabel ("Status");
         //sets size of text fields
         FNameTF     = new JTextField(30);
         SIDTF       = new JTextField(20);
         AddressTF   = new JTextField(30);
         CityTF      = new JTextField(8);
         StateTF     = new JTextField(30);
         TelephoneTF = new JTextField(20);
         //sets size of text area to display status to teacher
         statusTA = new JTextArea(3, 10);
         //sets title of buttons and creates action listener
         openB = new JButton("Open");
         openB.addActionListener(bhHandler);
         saveB = new JButton("Save");
         saveB.addActionListener(bhHandler);
         senterB = new JButton ("Enter");
         senterB.addActionListener(bhHandler);
         shelpB = new JButton ("Help");
         shelpB.addActionListener(bhHandler);
         sexitB = new JButton ("Exit");
         sexitB. addActionListener(bhHandler);
         //Options that will appear in combo box
         String selection[] = {"Choose From The Available Options ",
                        "Add Student","Search for Student", 
                        "Edit Student Record","Delete Student Record"};
         Selections = new JComboBox(selection);
         //sets size of labels, text fields, buttons
         sheadingL.setSize(200,30);
         StatusL.setSize(50,20);
         SIDL.setSize(100,30);          
         SIDTF.setSize(200,30);       
         FNameL.setSize(100,30);          
         FNameTF.setSize(200,30);     
         CityL.setSize(100,30);          
         CityTF.setSize(200,30);          
         AddressL.setSize(100,30);     
         AddressTF.setSize(200,30);     
         StateL.setSize(100,30);          
         StateTF.setSize(200,30);     
         TelephoneL.setSize(100,30);     
         TelephoneTF.setSize(200,30);          
         statusTA.setSize(370, 30);
         Selections.setSize(400,30);
         openB.setSize(80,30);
         saveB.setSize(80,30);          
         shelpB.setSize(80,30);
         sexitB.setSize(80,30);
         senterB.setSize(80,30);
         //sets location of labels, text fields, buttons on frame
         sheadingL.setLocation(110,20);
         FNameL.setLocation(70,110);
         FNameTF.setLocation(170,110);
         SIDL.setLocation(70,140);
         SIDTF.setLocation(170,140);
         AddressL.setLocation(70,170);
         AddressTF.setLocation(170,170);
         CityL.setLocation(70,200);
         CityTF.setLocation(170,200);
         StateL.setLocation(70,230);     
         StateTF.setLocation(170,230);
         TelephoneL.setLocation(70,260);
         TelephoneTF.setLocation(170,260);
            StatusL.setLocation(30, 300);
         statusTA.setLocation(30, 330); 
         Selections.setLocation(20,60);
         openB.setLocation(20,370);     
         saveB.setLocation(100,370);
         senterB.setLocation(180,370);          
         shelpB.setLocation(260,370);
         sexitB.setLocation(340,370);
         //adds labels, text fields, buttons to pane
         pane.add(sheadingL);
         pane.add(SIDL);
         pane.add(SIDTF);
         pane.add(FNameL);
         pane.add(FNameTF);
         pane.add(AddressL);
         pane.add(AddressTF);
         pane.add(CityL);
         pane.add(CityTF);     
         pane.add(StateL);
         pane.add(StateTF);
         pane.add(TelephoneL);
         pane.add(TelephoneTF);
         pane.add (Selections);
         pane.add (openB);
         pane.add (saveB);
         pane.add (shelpB);
         pane.add (sexitB);
         pane.add(StatusL);
         pane.add(statusTA);
         pane.add(senterB);
         setVisible(true);
         setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    I haven't looked at all of your code, but I do see that you are trying to put a JFrame, which is a root container into a JTabbedPane, and this just cannot be done. It would be better to refactor your StudentsFile class to extend a JPanel, and then you can add it to a JTabbedPane.
    Oh, and please ask these types of questions in the Swing forum.

  • Help automate popup code

    i have popup codes like this (too many around 12-20 popup screens) painted for demo.
    most of them have a kind of 1-2 layout ie
    the fields come dynamically from a resultset
    i am guessing i can change the SQL code so that i can get the proper field names
    eg
    SELECT
    FIELD1 AS DisplayName1,
    FIELD2 AD DisplayName2
    is there a way to dynamically adjust the layout to set the fields in a good way according to the recordset returned.
    |            Label1:   Field1           |
    |            Label1:   Field1           |
    |            Label1:   Field1           |
    |            Label1:   Field1           |
    |                       OK     Cancel   |
    package com.samples.swingsamples;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class clsClaimsEDI extends JDialog
      public clsClaimsEDI( JFrame frame ) {
        super( frame, true );
        setTitle( "EDI Information" );
        setSize( 500, 300 );
        // Creates a panel to hold all components
        JPanel panel = new JPanel( new BorderLayout() );
        panel.setLayout( new GridBagLayout() );
        // give the panel a border gap of 5 pixels
        panel.setBorder( new EmptyBorder( new Insets( 5, 5, 5, 5 ) ) );
        getContentPane().add( BorderLayout.NORTH, panel );
        GridBagConstraints c = new GridBagConstraints();
        // Define preferred sizes for input fields
        Dimension shortField = new Dimension( 40, 20 );
        Dimension mediumField = new Dimension( 120, 20 );
        Dimension longField = new Dimension( 240, 20 );
        Dimension hugeField = new Dimension( 240, 80 );
        // Spacing between label and field
        EmptyBorder border = new EmptyBorder( new Insets( 0, 0, 0, 10 ) );
        EmptyBorder border1 = new EmptyBorder( new Insets( 0, 20, 0, 10 ) );
        // add space around all components to avoid clutter
        c.insets = new Insets( 2, 2, 2, 2 );
        // anchor all components WEST
        c.anchor = GridBagConstraints.WEST;
        JLabel lbl1 = new JLabel( "Claim ID" );
        lbl1.setBorder( border ); // add some space to the right
        panel.add( lbl1, c );
        JTextField txt1 = new JTextField();
        txt1.setPreferredSize( longField );
        c.gridx = 1;
        c.weightx = 1.0; // use all available horizontal space
        c.gridwidth = 3; // spans across 3 columns
        c.fill = GridBagConstraints.HORIZONTAL; // fills the 3 columns
        panel.add( txt1, c );
        JLabel lbl2 = new JLabel( "External Reference Number" );
        lbl2.setBorder( border );
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 1;;
        c.weightx = 0.0; // do not use any extra horizontal space
        panel.add( lbl2, c );
        JTextField txt2 = new JTextField();
        txt2.setPreferredSize( mediumField );
        c.gridx = 1;
        c.ipadx = 0;   // reset the padding to 0
        c.ipady = 0;
        c.weightx = 1.0; // use all available horizontal space
    //    c.weighty = 1.0; // use all available vertical space
        c.gridwidth = 3; // span across 3 columns
    //    c.gridheight = 1; // span across 2 rows
        c.fill = GridBagConstraints.HORIZONTAL; // fills the cols & rows
        panel.add( txt2, c );
        JLabel lbl3 = new JLabel( "Trading Partner" );
        lbl3.setBorder( border );
        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 1;
        c.gridheight = 1;
        c.weightx = 0.0;
        c.weighty = 0.0;
        c.fill = GridBagConstraints.NONE;
        panel.add( lbl3, c );
        JTextField txt3 = new JTextField();
        txt3.setPreferredSize( mediumField);
        c.gridx = 1;
        c.gridwidth = 3; // span across 3 columns
        c.gridheight = 1; // span across 2 rows
        c.fill = GridBagConstraints.BOTH; // fills the cols & rows
        panel.add( txt3, c );
        c.gridx = 2;
        panel.add( Box.createVerticalStrut(1), c );
        c.gridx = 3;
        panel.add( Box.createVerticalStrut(1), c );
        c.gridx = 0;
        c.gridy = 4;
        panel.add( Box.createVerticalStrut(1), c );
        c.gridx = 1;
        c.gridwidth = 3;
        panel.add( Box.createVerticalStrut(1), c );
        c.gridx = 0;
        c.gridy = 5;
        panel.add( Box.createVerticalStrut(1), c );
        c.gridx = 1;
        c.gridwidth = 3;
        panel.add( Box.createVerticalStrut(1), c );
        c.gridx = 0;
        c.gridy = 6;
        panel.add( Box.createVerticalStrut(1), c );
        c.gridx = 1;
        c.gridwidth = 3;
        panel.add( Box.createVerticalStrut(1), c);
        c.gridx = 0;
        c.gridy = 7;
        c.gridwidth = 1;
        panel.add( Box.createVerticalStrut(1), c );
        c.gridx = 1;
        c.gridwidth = 3;
        panel.add( Box.createVerticalStrut(1), c );
        JButton submitBtn = new JButton( "Close" );
        c.gridx = 4;
        c.gridy = 0;
        c.gridwidth = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        panel.add( submitBtn, c );
        JButton cancelBtn = new JButton( "Help" );
        c.gridx = 4;
        c.gridy = 0;
        c.gridwidth = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        panel.add( cancelBtn, c );
        JButton helpBtn = new JButton( "Help" );
        c.gridy = 1;
        c.anchor = GridBagConstraints.NORTH; // anchor north
        panel.add( helpBtn, c );
        setVisible( true );

    any other popup samples :))

  • Bouncing off the wall: Problems with passing/using pointers to classes

    I have a mostly completed "msPaint" (=assigment) program that is driving me nuts!!!
    1. First shape you draw doesn't appear.
    1.5 Draw a shape by clicking twice on Panel, can change shape, color, fill with what buttons you see.
    2. Subsequently only the newest shape appears. Using System.println(); it appears to be drawing as many shapes as it has made, but it doesn't.
    3. I owe much to anyone who helps me, here is complete code. Specifically will ask/reward you to reply to a diff link in which I have dukes, got no answer, and can't reallocate dukes. (=5)
    Thank you very much.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Prog4 extends JApplet implements ActionListener
         //private MainPanel drawingpanel;
         private JPanel top;
         private JPanel left;
         private JPanel bottom;
         private JPanel bottomleft,bottommiddletop,bottommiddle,bottomright;
         //top buttons created
         private JButton first,next,previous,last,help;
         //bottom buttons created
         private JButton custom;
         private JButton white,gray,red,purple,blue,green,yellow,orange;
         private JButton black,darkgray,darkred,darkpurple,darkblue,darkgreen,darkyellow,darkorange;
         private JButton rect,oval,line,solid,hollow,erase;
         private CardLayout drawingscreens;
         private MyShape [] shapes=new MyShape[10];
         private MyShape newshape=new MyShape();     
         private Data information;//=new Data(newshape, shapes);
         private MyPanel temp;//=new MyPanel(information);
         private int thiscard;
         public int x,y;
         //Holder Variable to hold info about shape to be drawn
         int shape;
         int fill;
         int draw;
         int tx,ty,bx,by;
         public void init()
              Container window=getContentPane();
                   window.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   //Top Button Setup
                   first=new JButton("First");
                   first.addActionListener(this);
                   first.setPreferredSize(new Dimension(100,40));
                   next=new JButton("Next");
                   next.addActionListener(this);
                   next.setPreferredSize(new Dimension(100,40));
                   previous=new JButton("Previous");
                   previous.addActionListener(this);
                   previous.setPreferredSize(new Dimension(100,40));
                   last=new JButton("Last");
                   last.addActionListener(this);
                   last.setPreferredSize(new Dimension(100,40));
                   help=new JButton("Help");
                   help.addActionListener(this);
                   help.setPreferredSize(new Dimension(100,40));
                   //TOP PANEL SETUP
                   top=new JPanel();
                   top.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   top.setPreferredSize(new Dimension(800,40));
                   top.setOpaque(true);
                   top.setBackground(Color.white);
                   top.add(first);
                   top.add(next);
                   top.add(previous);
                   top.add(last);
                   top.add(help);
                   window.add(top);
                   //Left Buttons Setup
                   rect=new JButton("Rectangle");
                   rect.setPreferredSize(new Dimension(100,40));
                   rect.addActionListener(this);
                   oval=new JButton("Oval");
                   oval.setPreferredSize(new Dimension(100,40));
                   oval.addActionListener(this);
                   line=new JButton("Line");
                   line.setPreferredSize(new Dimension(100,40));
                   line.addActionListener(this);
                   solid=new JButton("Solid");
                   solid.setPreferredSize(new Dimension(100,40));
                   solid.addActionListener(this);
                   hollow=new JButton("Hollow");
                   hollow.setPreferredSize(new Dimension(100,40));
                   hollow.addActionListener(this);
                   erase=new JButton("Erase");
                   erase.setPreferredSize(new Dimension(100,40));
                   erase.addActionListener(this);
                   //Left Panel Setup
                   left=new JPanel();
                   left.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   left.setPreferredSize(new Dimension(200,600));     
                   left.add(rect);
                   left.add(oval);
                   left.add(line);
                   left.add(solid);
                   left.add(hollow);
                   left.add(erase);
                   window.add(left);// FlowLayout.LEFT);
                   //Middle Setup
                   temp=new panel();
                   temp.setPreferredSize(new Dimension(600,600));
                   temp.setOpaque(true);
                   temp.setBackground(Color.red);
                   temp.addMouseListener(this);
                   window.add(temp);
                   //Panel Listener Initailization
                   for(int i=0; i<shapes.length; i++)
                        shapes=new MyShape();
                   information=new Data(newshape, shapes);
                   temp=new MyPanel(information);
                   Listener panelListener=new Listener(temp, newshape, information);
                   //shapes
                   window.add(temp);
                   temp.addMouseListener(panelListener);
                   //Bottom Buttons Setup
                   int bsize=20; //Int for horz/vert size of buttons
                   //Left Setup, creates a JPanel which displays the current color
                   bottomleft=new JPanel();
                   bottomleft.setPreferredSize(new Dimension(2*bsize,2*bsize));
                   bottomleft.setLayout(new FlowLayout(0,0, FlowLayout.LEFT));
                   bottomleft.setOpaque(true);
                   //Middle Setup creates buttons for each pregenerated color in the top row
                   black=new JButton();
                   black.setPreferredSize(new Dimension(bsize,bsize));
                   black.setOpaque(true);
                   black.setBackground(new Color(0,0,0));
                   black.addActionListener(this);
                   darkgray=new JButton();
                   darkgray.setPreferredSize(new Dimension(bsize,bsize));
                   darkgray.setOpaque(true);
                   darkgray.setBackground(new Color(70,70,70));
                   darkgray.addActionListener(this);
                   darkred=new JButton();
                   darkred.setPreferredSize(new Dimension(bsize,bsize));
                   darkred.setOpaque(true);
                   darkred.setBackground(new Color(180,0,0));
                   darkred.addActionListener(this);
                   darkpurple=new JButton();
                   darkpurple.setPreferredSize(new Dimension(bsize,bsize));
                   darkpurple.setOpaque(true);
                   darkpurple.setBackground(new Color(185,0,185));
                   darkpurple.addActionListener(this);
                   darkblue=new JButton();
                   darkblue.setPreferredSize(new Dimension(bsize,bsize));
                   darkblue.setOpaque(true);
                   darkblue.setBackground(new Color(0,0,150));
                   darkblue.addActionListener(this);
                   darkgreen=new JButton();
                   darkgreen.setPreferredSize(new Dimension(bsize,bsize));
                   darkgreen.setOpaque(true);
                   darkgreen.setBackground(new Color(0,140,0));
                   darkgreen.addActionListener(this);
                   darkyellow=new JButton();
                   darkyellow.setPreferredSize(new Dimension(bsize,bsize));
                   darkyellow.setOpaque(true);
                   darkyellow.setBackground(new Color(176,176,0));
                   darkyellow.addActionListener(this);
                   darkorange=new JButton();
                   darkorange.setPreferredSize(new Dimension(bsize,bsize));
                   darkorange.setOpaque(true);
                   darkorange.setBackground(new Color(170,85,0));
                   darkorange.addActionListener(this);
                   //Adds each button to a Panel
                   bottommiddletop=new JPanel();
                   bottommiddletop.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   bottommiddletop.setPreferredSize(new Dimension(8*bsize,bsize));
                   bottommiddletop.add(black);
                   bottommiddletop.add(darkgray);
                   bottommiddletop.add(darkred);
                   bottommiddletop.add(darkpurple);
                   bottommiddletop.add(darkblue);
                   bottommiddletop.add(darkgreen);
                   bottommiddletop.add(darkyellow);
                   bottommiddletop.add(darkorange);     
                   //Bottom Middle Creates bottom row of colors like top
                   white=new JButton();
                   white.setPreferredSize(new Dimension(bsize,bsize));
                   white.setOpaque(true);
                   white.setBackground(new Color(255,255,255));
                   white.addActionListener(this);
                   gray=new JButton();
                   gray.setPreferredSize(new Dimension(bsize,bsize));
                   gray.setOpaque(true);
                   gray.setBackground(new Color(192,192,192));
                   gray.addActionListener(this);
                   red=new JButton();
                   red.setPreferredSize(new Dimension(bsize,bsize));
                   red.setOpaque(true);
                   red.setBackground(new Color(255,0,0));
                   red.addActionListener(this);
                   purple=new JButton();
                   purple.setPreferredSize(new Dimension(bsize,bsize));
                   purple.setOpaque(true);
                   purple.setBackground(new Color(213,0,213));
                   purple.addActionListener(this);
                   blue=new JButton();
                   blue.setPreferredSize(new Dimension(bsize,bsize));
                   blue.setOpaque(true);
                   blue.setBackground(new Color(0,0,255));
                   blue.addActionListener(this);
                   green=new JButton();
                   green.setPreferredSize(new Dimension(bsize,bsize));
                   green.setOpaque(true);
                   green.setBackground(new Color(0,255,0));
                   green.addActionListener(this);
                   yellow=new JButton();
                   yellow.setPreferredSize(new Dimension(bsize,bsize));
                   yellow.setOpaque(true);
                   yellow.setBackground(new Color(255,255,0));
                   yellow.addActionListener(this);
                   orange=new JButton();
                   orange.setPreferredSize(new Dimension(bsize,bsize));
                   orange.setOpaque(true);
                   orange.setBackground(new Color(244,122,0));
                   orange.addActionListener(this);
                   //Attaches buttons to a panel
                   bottommiddle=new JPanel();
                   bottommiddle.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   bottommiddle.setPreferredSize(new Dimension(8*bsize,bsize));
                   bottommiddle.add(white);
                   bottommiddle.add(gray);
                   bottommiddle.add(     red);
                   bottommiddle.add(purple);
                   bottommiddle.add(blue);
                   bottommiddle.add(green);
                   bottommiddle.add(yellow);
                   bottommiddle.add(orange);     
                   //Creates middle panel for bottom
                   bottom=new JPanel();
                   bottom.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   bottom.setPreferredSize(new Dimension(8*bsize,2*bsize));
                   bottom.add(bottommiddletop);
                   bottom.add(bottommiddle);               
                   //This is for a button on buttom right to make custom colors.
                   //Right Setup creates a button which allows you to make your own color
                   custom=new JButton("More");
                   custom.setPreferredSize(new Dimension(4*bsize,2*bsize));
                   custom.setOpaque(true);
                   bottomright=new JPanel();
                   bottomright.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   bottomright.setPreferredSize(new Dimension(4*bsize,2*bsize));
                   bottomright.add(custom);
                   //The Panel containing current color is added first
                   //Then the two colors panels are added
                   //Then the panel with a custom button is added
                   window.add(bottomleft);
                   window.add(bottom);
                   window.add(bottomright);
         public void actionPerformed(ActionEvent e)
              //Buttons to change colors
              if(e.getSource()==black)
                   bottomleft.setBackground(new Color(0,0,0));
                   newshape.setColor(0,0,0);
              if(e.getSource()==darkgray)
                   bottomleft.setBackground(new Color(70,70,70));
                   newshape.setColor(70,70,70);
              if(e.getSource()==darkred)
                   bottomleft.setBackground(new Color(180,0,0));
                   newshape.setColor(180,0,0);
              if(e.getSource()==darkpurple)
                   bottomleft.setBackground(new Color(185,0,185));
                   newshape.setColor(185,0,185);
              if(e.getSource()==darkblue)
                   bottomleft.setBackground(new Color(0,0,150));
                   newshape.setColor(0,0,150);
              if(e.getSource()==darkgreen)
                   bottomleft.setBackground(new Color(0,140,0));
                   newshape.setColor(0,140,0);
              if(e.getSource()==darkyellow)
                   bottomleft.setBackground(new Color(176,176,0));
                   newshape.setColor(176,176,0);
              if(e.getSource()==darkorange)
                   bottomleft.setBackground(new Color(170,85,0));
                   newshape.setColor(170,85,0);
              if(e.getSource()==white)
                   bottomleft.setBackground(new Color(255,255,255));
                   newshape.setColor(255,255,255);
              if(e.getSource()==blue)
                   bottomleft.setBackground(new Color(0,0,255));
                   newshape.setColor(0,0,255);
              if(e.getSource()==red)
                   bottomleft.setBackground(new Color(255,0,0));
                   newshape.setColor(255,0,0);
              if(e.getSource()==green)
                   bottomleft.setBackground(new Color(0,255,0));
                   newshape.setColor(0,255,0);
              if(e.getSource()==purple)
                   bottomleft.setBackground(new Color(213,0,213));
                   newshape.setColor(213,0,213);
              if(e.getSource()==yellow)
                   bottomleft.setBackground(new Color(255,255,0));
                   newshape.setColor(255,255,0);
              if(e.getSource()==orange)
                   bottomleft.setBackground(new Color(244,122,0));
                   newshape.setColor(244,122,0);
              if(e.getSource()==gray)
                   bottomleft.setBackground(new Color(192,192,192));
                   newshape.setColor(192,192,192);
              //Code for setting shape to draw
              if(e.getSource()==rect)
                   setShapes();
                   rect.setBackground(Color.blue);               
                   newshape.setShape(1);
              if(e.getSource()==line)
                   setShapes();
                   newshape.setShape(0);
                   line.setBackground(Color.blue);
              if(e.getSource()==oval)
                   setShapes();
                   newshape.setShape(2);
                   oval.setBackground(Color.blue);
              //Code for setting to fill or not
              if(e.getSource()==solid)
                   solid.setBackground(Color.blue);
                   hollow.setBackground(Color.gray);
                   newshape.setFill(1);
              if(e.getSource()==hollow)
                   hollow.setBackground(Color.blue);
                   solid.setBackground(Color.gray);
                   newshape.setFill(0);
         public void setShapes()
              rect.setBackground(Color.gray);
              oval.setBackground(Color.gray);
              line.setBackground(Color.gray);
    class Data
         private MyShape newshape;
         private MyShape [] shapes;
         public Data(MyShape a, MyShape [] b)
              newshape=a;
              shapes=b;
         public void drawShapes(Graphics g)
              drawAllShapes(g);
         public void sortShapes()
              for(int t=8; t>=0; t--)
                   shapes[t+1]=shapes[t];
              shapes[0]=newshape;
              System.out.println("Shapes Sorted");
         public void drawAllShapes(Graphics g)
              newshape.reset(true);
              for(int i=9; i>=0; i--)
                   shapes[i].drawShape(g);
              System.out.println("Shapes Drawn??");
    class MyPanel extends JPanel
         private Data information;
         public MyPanel(Data a)
              information=a;
              setPreferredSize(new Dimension(600,600));
              setBackground(Color.blue);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              information.drawShapes(g);
    class Listener extends MouseAdapter
         int x,y;
         private int [] loc=new int[4];
         int horzL, vertL;
         private boolean clicked=false;
         private boolean sortonce;
         private MyPanel temp;
         private MyShape newshape;
         private Data information;
         private int xt,yt,xl,yl;
         public Listener(MyPanel d, MyShape b, Data c)
              temp=d;
              newshape=b;          
              information=c;
         public void mouseClicked(MouseEvent e)
              if(clicked==false)
                   x=e.getX();
                   y=e.getY();
                   clicked=true;
              else
              if(clicked==true)
                   mouseloc(x,y,e.getX(),e.getY());
                   information.sortShapes();
                   temp.repaint();
                   clicked=false;
         public void mouseloc(int xt,int yt,int xl,int yl)
              loc[0]=xt;
              loc[1]=yt;
              loc[2]=xl;
              loc[3]=yl;
              newshape.setLoc(xt,yt,xl,yl);
              newshape.doDraw(true);
    class MyShape
         private int xL, yL, xR, yR; //Local location ints for this class;
         private int red, blue, green; //Local ints defining this color;
         private int shape,fill; //Local info about shape
         private boolean draw=false; // Determines if Shape will draw
         private boolean setupshape=true;
         public void MyShape()
         public void doDraw(boolean a)
              draw=a;
         public void setLoc(int xt,int yt,int xb,int yb)
              xL=xt;
              yL=yt;
              xR=xb;
              yR=yb;
         public void setColor(int r,int b,int g)
              red=r;
              blue=b;
              green=g;
         public void setShape(int thisshape)
              shape=thisshape;
         public void setFill(int fil)
              fill=fil;
         public void drawShape(Graphics g)
              if(draw==true && setupshape==true)
                   System.out.println("This shape setup");
                   g.setColor(new Color(red,blue,green));
                   switch(shape)
                        case 0: makeLine(g);break;
                        case 1: makeRect(g);break;
                        case 2: makeOval(g);break;
                   setupshape=false;
              else if(draw==true)
                   System.out.println("This shape redrawn");
                   switch(shape)
                        case 0: drawLine(g);break;
                        case 1: drawRect(g);break;
                        case 2: drawOval(g);break;
         public void reset(boolean a)
              setupshape=a;
         public void drawLine(Graphics g)
              g.drawLine(xL,yL,xR,yR);
         public void drawRect(Graphics g)
              if(fill==0)
                   g.drawRect(xL,yL,xR,yR);
              else
                   g.fillRect(xL,yL,xR,yR);
         public void drawOval(Graphics g)
              if(fill==0)
                   g.drawOval(xL,yL,xR,yR);
              else
                   g.fillOval(xL,yL,xR,yR);
         public void makeLine(Graphics g)
              g.drawLine(xL,yL,xR,yR);
         public void makeRect(Graphics g)
              sortvalue();
              if(fill==0)
                   g.drawRect(xL,yL,xR,yR);
              else
                   g.fillRect(xL,yL,xR,yR);
         public void makeOval(Graphics g)
              sortvalue();
              if(fill==0)
                   g.drawOval(xL,yL,xR,yR);
              else
                   g.fillOval(xL,yL,xR,yR);
         public void sortvalue()
                   if(xR<xL)
                   int temp=xR;
                   xR=xL;
                   xL=temp;
              if(yR<yL)
                   int temp=yR;
                   yR=yL;
                   yL=temp;
              yR=(yR-yL);
              xR=(xR-xL);     

    Sorry mate but you need a lot of work....
    I like what you've done but (in my humble opinion) it needs a lot of reworking.
    Your problem is you're not storing the shapes. You've set up an array but you never assign the shapes to it. I would reccomend using a vector. Heres a quick bit of pseudo code.
    Listener class
    mouseClicked method
    if first click
    get mouse x/y
    if second click
    get mouse x/y
    create new MyShape(x1, y1, x2, y2)
    call data.addShape(new MyShape)
    Data class
    constructor
    this.myVector = new Vector()
    addShape(MyShape shape) method
    this.myVector.addElement(shape) -- add new shape
    this.myVector.remove(0) -- remove bottom shape
    drawAllShapes method
    Enumeration enum= this.myVector.elements()
    while(enum.hasMoreElements())
    MyShape shape = (MyShape)enum.nextElement()
    shape.draw()
    Feel free to ask any questions.
    Rob.

  • Comparing an Item in a List to...

    Hello. I'm new to these forums, and this is my first post here. I'm working on a hangman game just for fun, and I've run into a snag. When it checks to see if the key pressed is equal to (or the same as) the letter in position x. Every time, even if the letter is in the word, it returns false and does nothing. I hope this is clear. Below is my entire code (just to give you an idea of how this works) of my main class. There is another class that contains methods, but it does not affect this problem.
    Also note that I am fairly new to Java, but have been programming in Python for about half a year now (taking a programming class at my High School). I also so PHP, but even with a good programming background, I still seem to run into snags while programming in Java.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class Hangman extends JFrame implements ActionListener, KeyListener {
        // Initiate some global variables
        int num_guesses;
        String word;
        String end_round = "yes";
        String[] blanks;
        String[] letters;
        // Get the word list
        String location = "C:/Documents and Settings/AMT/My Documents/My Programs/Java/Hangman/build/classes/hangman_words.txt";
        Vector words = hmFunctions.getWords(location);
        Vector backUpWords = words;
        // Create the main buttons
        JButton hint = new JButton("Hint");
        JButton giveup = new JButton("I Give Up");
        JButton help = new JButton("Help");
        JButton about = new JButton("About");
        JButton quit = new JButton("Quit");
        // Create the main window and add componants
        public Hangman() {
            super("Hangman v1.0");
            setSize(631, 510);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // Create the main pane
            Container hm_pane = getContentPane();
            hm_pane.setLayout(null);
            hm_pane.setFocusable(true);
            hm_pane.addKeyListener(this);
            // Set the button properties
            hint.setBounds(new Rectangle(2, 444, 100, 30));
            hint.addActionListener(this);
            giveup.setBounds(new Rectangle(130, 444, 100, 30));
            giveup.addActionListener(this);
            help.setBounds(new Rectangle(260, 444, 100, 30));
            help.addActionListener(this);
            about.setBounds(new Rectangle(390, 444, 100, 30));
            about.addActionListener(this);
            quit.setBounds(new Rectangle(520, 444, 100, 30));
            quit.addActionListener(this);
            // Add Componants to interface pane
            hm_pane.add(hint);
            hm_pane.add(giveup);
            hm_pane.add(help);
            hm_pane.add(about);
            hm_pane.add(quit);
            setContentPane(hm_pane);
            setVisible(true);
        // Check to see if they clicked anything
        public void actionPerformed(ActionEvent event) {
            Object source = event.getSource();
            if (source == hint) {
            } else if (source == giveup) {
            } else if (source == help) {
                JOptionPane.showMessageDialog(null, "JHangman v1.0 Help...");
            } else if (source == about) {
                JOptionPane.showMessageDialog(null, "JHangman v1.0\nProgrammed by...");
            } else if (source == quit) {
                System.exit(0);
        // Check if user pressed any keys
        public void keyTyped(KeyEvent key_event) {
            if (end_round == "yes") {
                mainGame("start");        
            } else if (end_round == "no") {
                Character key = key_event.getKeyChar();
                String let = key.toString();
                System.out.println("Letter Pressed: " + let);
                mainGame(let);
        public void keyPressed(KeyEvent key_event) {  
        public void keyReleased(KeyEvent key_event) {
        // The check letter method
        public void mainGame(String funct) {
            if (funct == "start") {
                num_guesses = 0;
                // Check if words empty
                if (words.size() == 0) {
                    words = backUpWords;
                // Get word needed for the game and back up
                word = hmFunctions.getRndWord(words);
                words.remove(word);
                // Create the blanks and letters vector
                letters = new String[word.length()];
                blanks = new String[word.length()];
                // Make the blanks and letters and draw interface
                for (int a = 0; a < word.length(); a++) {
                    blanks[a] = "_";
                    letters[a] = word.substring(a, a + 1);
                System.out.println("Game Started!");
                System.out.println("Blanks and letters added successfuly!");
                end_round = "no";
            // If no other instruction given, then check to see if key pressed is in the word
            } else {
                for (int x = 0; x < word.length(); x++) {
                    if (funct == letters[x]) {
                        blanks[x] = funct;
                    System.out.println(blanks[x] + " ");
                num_guesses += 1;
                if (num_guesses == 8) {
                    end_round = "yes";
        // Main Program
        public static void main(String[] arguments) {
            hmFunctions hm_fct = new hmFunctions();
            // Draw the main interface
            Hangman HM_Window = new Hangman();
    }Any help would be greatly appriciated!

    Of course, looking more closely, you do seem to be assigning the literal reference into the String object reference. In String s = "a string literal";
    if ( s == "a string literal" )
      // process
    } you may actually get into the if block. I would have to test to be sure. However, in general practice, if you want to check to see if two String objects have the same contents, use equals(). If you want to see if two object references point to the same location in memory, use ==. Primitives, of course, are compared with ==.
    Your keyTyped() method checks for two values of end_round. Have you checked for neither the if nor the else conditions being true?
    Do you know if you are getting into your mainGame() method? Try putting a println() in as soon as you enter, so you know you got there and you know the actual parameter value.
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Problem adding a table to scrollpane

    Hi:
    I have created a JTable that I want to be in a scrollpane. When I tried to add this JTable to a scrollpane I get a null pointer error at execution time. But when I add this table directly to the frame I get no error at execution time.
    Here is my code:
    import java.awt.*;
    import java.awt.event .*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.swing.table.*;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import java.net.*;
    import java.util.regex.*;
    // METHODS
    // =======
    // private String returnSelectedString( int col ))
    public class DialogFrame extends JFrame
    {     //===================
    //MEMBER VARIABLES
    //===================
    public JLabel topClassifiedLabel, bottomClassifiedLabel,printerCountLabel,defaultPrinterLabel ;
    public JPanel panelForLabel,topClassificationPanel , bottomClassificationPanel, SecBotPanel, ClassificationPanel,Classification_botPanel,firstTopPanel, titlePanel,titlePanel2,displayPanel,labelPanel,buttonPanel;
    public DefaultListModel listModel;
    public final String screenTitle = "Printer Configuration "
    + " CSS - 105";
    public JLabel localDisplay = new JLabel("Local: Printer directly connected to this computer");
    public JLabel remoteDisplay = new JLabel("Remote: Printer connected to another computer");
    public JLabel networkDisplay = new JLabel("Network: Printer connected to the LAN");
    public char hotKeys[] = { 'A', 'D', 'Q','T','R','I','Q','H' };
    public JPanel ConnectTypePanel = null, printCountPanel;
    public JScrollPane tabScrollPane;
    public JLabel l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,TitleLabel;
    public JButton addPrinterButton,setDefaultButton,restartPrintSystemButton, deletePrinterButton, displayQueueButton,
    ToggleBannerButton, RestartPrintSystemButton, InstallOpenPrintButton, QuitButton, continueButton,CancelButton,HelpButton;
    public Vector columnNames;
    public String line2 = "";
    public addPrinterDialog aPDialog;
    public printQueueDialog dQDialog;
    public String nextElement,name,Type,Interface,Description,Status,Queue,BannerPage;
    public JRadioButton networkButton, localButton, remoteButton;
    public JLabel nameLabel, descriptionLabel, modelLabel,ClassificationLabel,ClassificationLabel_bot,setL,defaultL;
    public JTextField nameTextField, descriptionTextField, modelTextField;
    private int printerCount = 0;
    static DefaultTableModel model;
    public JTable table;
    //=======================//
    //**Constructor
    //=========================//
    public DialogFrame()
    createTable();
    public void createTable()
    defaultPrinterLabel = new JLabel();
    printerCountLabel = new JLabel();
    //COLUMN FOR TABLE
    columnNames = new Vector();
    columnNames.add("Name");
    columnNames.add("Type");
    columnNames.add("Interface");
    columnNames.add("Description");
    columnNames.add("Status");
    columnNames.add("Queue");
    columnNames.add("BannerPage");
    Vector tableRow = new Vector();
    //tableRow = executeScript("perl garb.pl");
    // tableRow = executeScript("perl c:\\textx.pl");
    model = new DefaultTableModel( tableRow, columnNames ){
    public boolean isCellEditable(int row,int col) {
    return false;
    public Dimension getPreferredScrollableViewportSize() {
    return getPreferredSize();
    table = new JTable(model);
    JTableHeader header = table.getTableHeader();
    TableColumnModel colmod = table.getColumnModel();
    for (int i=0; i < table.getColumnCount(); i++)
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(SwingConstants.CENTER);
    colmod.getColumn(i).setCellRenderer(renderer);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowGrid( false );
    table.getTableHeader().setReorderingAllowed( false );
    table.setIntercellSpacing(new Dimension(0,0) );
    table.addMouseListener( new MouseAdapter () {
    public void mouseClicked( MouseEvent e) {
    if ((e.getModifiers() & InputEvent.BUTTON1_MASK) !=0)
    printSelectCell(table);
    this.setSize(900,900);
    //========================================//
    // Technique for centering a frame on the screen
    //===========================================//
    Dimension frameSize = this.getSize();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation((screenSize.width - frameSize.width)/2,
    (screenSize.height - frameSize.height)/2);
    setResizable(false);
    // CREATE A FEW PANELS
    firstTopPanel = new JPanel();
    BoxLayout box = new BoxLayout(firstTopPanel, BoxLayout.Y_AXIS);
    firstTopPanel.setLayout(box);
    topClassificationPanel = new JPanel();
    topClassificationPanel.setBackground(new Color(45,145,71));
    bottomClassificationPanel = new JPanel();
    bottomClassificationPanel.setBackground(new Color(45,145,71));
    SecBotPanel = new JPanel();
    SecBotPanel.setLayout(new BorderLayout());
    buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1,8));
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0));
    buttonPanel.setBackground(new Color(170,187,119));
    panelForLabel = new JPanel();
    // panelForLabel.setBackground( Color.white );
    //Border etchedBorder = BorderFactory.createEtchedBorder();
    printerCountLabel.setHorizontalAlignment(SwingConstants.LEFT);
    printerCountLabel.setPreferredSize(new Dimension(700, 20));
    //printerCountLabel.setBorder(etchedBorder);
    printerCountLabel.setForeground(Color.black);
    defaultPrinterLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    defaultPrinterLabel.setText("Default Printer: " + name);
    defaultPrinterLabel.setForeground(Color.black);
    panelForLabel.add(printerCountLabel);
    panelForLabel.add(defaultPrinterLabel);
    titlePanel = new JPanel( );
    titlePanel.setBackground( Color.white );
    ConnectTypePanel = new JPanel();
    ConnectTypePanel.setBackground(new Color(219,223,224));
    ConnectTypePanel.setLayout( new GridLayout(3,1) );
    //CREATE A FEW LABELS
    topClassifiedLabel = new JLabel("UNCLASSIFIED", SwingConstants.CENTER );
    topClassifiedLabel.setForeground(Color.white);
    bottomClassifiedLabel = new JLabel("UNCLASSIFIED", SwingConstants.CENTER );
    bottomClassifiedLabel.setForeground(Color.white);
    TitleLabel = new JLabel( screenTitle, SwingConstants.CENTER );
    //ADD LABELS TO PANELS
    topClassificationPanel.add( topClassifiedLabel );
    bottomClassificationPanel.add( bottomClassifiedLabel );
    titlePanel.add( TitleLabel, BorderLayout.CENTER );
    ConnectTypePanel.add(localDisplay );
    ConnectTypePanel.add(remoteDisplay );
    ConnectTypePanel.add(networkDisplay );
    //Create the scrollpane and add the table to it.
    tabScrollPane = new JScrollPane(table);
    JPanel ps = new JPanel();
    ps.add(tabScrollPane);
    getContentPane().setLayout(
    new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ) );
    getContentPane().add(firstTopPanel);
    getContentPane().add(panelForLabel);
    getContentPane().add(header);
    getContentPane().add(ps);//contain table
    getContentPane().add(SecBotPanel);
    WindowListener w = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    DialogFrame.this.dispose();
    System.exit(0);
    this.addWindowListener(w);
    //==================================//
    // AddPrinterButton
    //==================================//
    addPrinterButton = new JButton();
    addPrinterButton.setLayout(new GridLayout(2, 1));
    l1 = new JLabel("Add", JLabel.CENTER);
    l1.setForeground(Color.black);
    l2 = new JLabel("Printer", JLabel.CENTER);
    l2.setForeground(Color.black);
    addPrinterButton.add(l1);
    addPrinterButton.add(l2);
    addPrinterButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    //(aPDialog == null) // first time
    aPDialog = new addPrinterDialog(DialogFrame.this);
    aPDialog.setLocationRelativeTo(null);
    aPDialog.pack();
    aPDialog.show(); // pop up dialog
    //======================================
    // DeletePrinterButton
    //=====================================
    deletePrinterButton = new JButton();
    deletePrinterButton.setLayout(new GridLayout(2, 1));
    l1 = new JLabel("Delete", JLabel.CENTER);
    l1.setForeground(Color.black);
    l2 = new JLabel("Printer", JLabel.CENTER);
    l2.setForeground(Color.black);
    deletePrinterButton.add(l1);
    deletePrinterButton.add(l2);
    deletePrinterButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    int ans = JOptionPane.showConfirmDialog(null,"Are you sure you want to delete printer " + name + "?","Delete",JOptionPane.YES_NO_OPTION);
    switch(ans) {
    case JOptionPane.NO_OPTION:
    return;
    case JOptionPane.YES_OPTION:
    // String machineName = returnSelectedString(0);
    int rowNumber = table.getSelectedRow();
    model.removeRow(rowNumber);
    //TiCutil.exe("/usr/lib/lpadmin -x " + machineName);
    decreasePrinterCount();
    JOptionPane.showMessageDialog(null, "Printer " + name + " have been successfully deleted","SUCCEED",JOptionPane.INFORMATION_MESSAGE);
    return;
    //==============================//
    //DisplayQueuePrinter //
    //================================//
    displayQueueButton = new JButton();
    displayQueueButton.setLayout(new GridLayout(2, 1));
    l5 = new JLabel("Display", JLabel.CENTER);
    l5.setForeground(Color.black);
    l6 = new JLabel("Queue", JLabel.CENTER);
    l6.setForeground(Color.black);
    displayQueueButton.add(l5);
    displayQueueButton.add(l6);
    displayQueueButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    Vector tab = new Vector();
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this" +
    "operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    //PASS TABLE HERE
    /*tab = executeScript("lpstat -o " + name + " | sed \'s/ on$//\'");
    System.out.println("lpstat -o " + name + " | sed \'s/ on$//\'");
    dQDialog = new printQueueDialog(DialogFrame.this, name, tab);
    dQDialog.setLocationRelativeTo(null);
    dQDialog.pack();
    dQDialog.show(); // pop up dialog */
    //===================================
    // SetDefaultButton
    //================================//
    setDefaultButton = new JButton();
    setDefaultButton.setLayout(new GridLayout(2, 1));
    setL = new JLabel("Set", JLabel.CENTER);
    setL.setForeground(Color.black);
    defaultL = new JLabel("Default", JLabel.CENTER);
    defaultL.setForeground(Color.black);
    setDefaultButton.add(setL);
    setDefaultButton.add(defaultL);
    setDefaultButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    JOptionPane.showMessageDialog(null, "printer " + name + " is now the default.","Succeed",JOptionPane.INFORMATION_MESSAGE);
    defaultPrinterLabel.setText("Default Printer: " + name);
    //==============================//
    // ToggleBannerButton
    //==============================//
    ToggleBannerButton = new JButton();
    ToggleBannerButton.setLayout(new GridLayout(2, 1));
    l7 = new JLabel("Toggle", JLabel.CENTER);
    l7.setForeground(Color.black);
    l8 = new JLabel("Banner", JLabel.CENTER);
    l8.setForeground(Color.black);
    ToggleBannerButton.add(l7);
    ToggleBannerButton.add(l8);
    ToggleBannerButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    System.out.println("sr :" + sr);
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    String banner = returnSelectedString(6);
    name = returnSelectedString(0);
    String machineName = returnSelectedString(0);
    Type = returnSelectedString(1);
    if ( !(Type.equals("Remote")) )
    if( banner.equals("Yes") )
    JOptionPane.showMessageDialog(null,"Banner page will NOT be printed for printer "+ name ,"Succeed",JOptionPane.INFORMATION_MESSAGE);
    //TiCutil.exe("sed -e 's/^BANNER=\"yes\"/BANNER=\"\"/' /etc/lp/interfaces/" + machineName + " > /tmp/delete.txt" );
    //TiCutil.exe("mv /tmp/delete.txt /etc/lp/interfaces/" + machineName);
    table.setValueAt("No",sr,6);
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.fireTableCellUpdated(sr,6);
    table.requestFocus();
    else
    JOptionPane.showMessageDialog(null,"Banner page WILL be printed for printer "+ name ,"Succeed",JOptionPane.INFORMATION_MESSAGE);
    //TiCutil.exe("sed -e 's/^BANNER=\"\"/BANNER=\"yes\"/' /etc/lp/interfaces/" + machineName + " > /tmp/delete.txt");
    //TiCutil.exe("mv /tmp/delete.txt /etc/lp/interfaces/" + machineName);
    table.setValueAt("Yes",sr,6);
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.fireTableCellUpdated(sr,6);
    table.requestFocus();
    else
    JOptionPane.showMessageDialog(null,"Operation failed system respond \n" + "was:\n" + "cannot toggle the banner page for a\n" + "REMOTE printer." ,"OPFAIL",JOptionPane.INFORMATION_MESSAGE);
    //==================================//
    // RestartPrintSystemButton
    //==================================//
    restartPrintSystemButton = new JButton();
    restartPrintSystemButton.setLayout(new GridLayout(2, 1));
    l3 = new JLabel("Restart Print", JLabel.CENTER);
    l3.setForeground(Color.black);
    l4 = new JLabel("System", JLabel.CENTER);
    l4.setForeground(Color.black);
    restartPrintSystemButton.add(l3);
    restartPrintSystemButton.add(l4);
    restartPrintSystemButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    //==============================
    // InstallOpenPrint
    //================================
    InstallOpenPrintButton = new JButton();
    InstallOpenPrintButton.setLayout(new GridLayout(2, 1));
    l11 = new JLabel("Install Open", JLabel.CENTER);
    l11.setForeground(Color.black);
    l12 = new JLabel("Print", JLabel.CENTER);
    l12.setForeground(Color.black);
    InstallOpenPrintButton.add(l11);
    InstallOpenPrintButton.add(l12);
    InstallOpenPrintButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int ans = JOptionPane.showConfirmDialog(null,"Are you sure you want to install OPENPrint?","Delete",JOptionPane.YES_NO_OPTION);
    switch(ans) {
    case JOptionPane.NO_OPTION:
    return;
    case JOptionPane.YES_OPTION:
    int cd,opinstall,banner_var,pwd;
    opinstall = runIt("open_print.ksh");
    banner_var = runIt("banner_var.ksh");
    System.out.println("opinstall: " + opinstall );
    System.out.println("banner_var: " + banner_var);
    if ( opinstall == 0 && banner_var == 0)
    JOptionPane.showMessageDialog(null, "OPENprint successfully added"
    ,"SUCCEED",JOptionPane.INFORMATION_MESSAGE);
    return;
    //==========================
    //QuitButton
    //============================
    QuitButton = new JButton("Quit");
    QuitButton.addActionListener (new ActionListener ()
    { public void actionPerformed (ActionEvent e){
    System.exit (0); }
    HelpButton = new JButton("Help");
    //ADD BUTTONS TO PANEL
    buttonPanel.add( addPrinterButton );
    buttonPanel.add( deletePrinterButton );
    buttonPanel.add( displayQueueButton );
    buttonPanel.add( setDefaultButton);
    buttonPanel.add( ToggleBannerButton );
    buttonPanel.add( restartPrintSystemButton );
    buttonPanel.add( InstallOpenPrintButton );
    buttonPanel.add( QuitButton );
    //buttonPanel.add( HelpButton );
    //END OF BUTTONS CREATION
    //ADD PANEL ON TO PANEL
    SecBotPanel.add(ConnectTypePanel, BorderLayout.CENTER);
    SecBotPanel.add(bottomClassificationPanel, BorderLayout.SOUTH);
    firstTopPanel.add(topClassificationPanel);
    firstTopPanel.add(titlePanel);
    firstTopPanel.add(buttonPanel);
    //===========================================================
    // METHODS
    //==========================================================
    public int runIt(String targetCode)
    int result = -1;
    try{
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec( targetCode );
    // Thread.sleep(20000);
    p.waitFor();
    result = p.exitValue();
    catch( IOException ioe )
    ioe.printStackTrace();
    catch( InterruptedException ie )
    ie.printStackTrace();
    return result;
    //====================================================
    public void increasePrinterCount()
    printerCount++;
    printerCountLabel.setText("Printer: " + printerCount);
    //===========================================================
    public void decreasePrinterCount()
    printerCount--;
    printerCountLabel.setText("Printer: " + printerCount);
    private String returnSelectedString( int col )
    int row = table.getSelectedRow();
    String word;
    //javax.swing.table.TableModel model = table.getModel();
    word =(String)model.getValueAt(row, col);
    return word; //return string
    //==============================================================================
    private Vector executeScript(String str)
    Vector tableOfVectors = new Vector();
    try{          
    String line;
    Process ls_proc = Runtime.getRuntime().exec(str);
    //get its output (your input) stream
    BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
    //readLine reads in one line of text
    int k = 1, i = 0;
    //LOOK FOR THE "|"
    Pattern p = Pattern.compile(" ");
    while (( line = in.readLine()) != null)
    Vector data = new Vector();
    Matcher m = p.matcher(line);
    if(m.find() == true)//find " "
    line = line.replaceAll(" {2,}?", "|");
    //creates a new vector for each new line read in
    StringTokenizer t = new StringTokenizer(line,"|");
    while ( t.hasMoreTokens() )
    try
    nextElement = t.nextToken().trim();
    //add a string to a vector
    data.add(nextElement.trim());
    catch(java.util.NoSuchElementException nsx)
    System.out.println(nsx);
    tableOfVectors.add(data);
    //COUNT THE NUMBER OF PRINTER
    printerCount = k;
    printerCountLabel.setText("Printer: " + printerCount);
    k++;
    }//END OF WHILE
    in.close();
    }//END OF TRY
    catch (IOException e1) {
    System.err.println(e1);
    System.exit(1);
    return tableOfVectors;
    //==========================================================================================================
    private String getDefaultPrinter(String str)
    String groupStr = null;
    try{          
    String lin;
    Process ls_proc = Runtime.getRuntime().exec(str);
    BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
    Pattern p2 = Pattern.compile("system default destination: (\\S+)");
    while (( lin = in.readLine()) != null)
    Matcher m2 = p2.matcher(lin);
    m2.reset(lin);
    if (m2.find() == true )
    groupStr = m2.group(1);
    in.close();
    catch (IOException e1) {
    System.err.println(e1);
    System.exit(1);
    return groupStr;
    //================================================================================
    public synchronized void clearTable()
    int numrows = model.getRowCount();
    for ( int i = numrows -1 ; i >= 0 ; i--)
    model.removeRow(i);
    //=======================================================================================================
    private void printSelectCell(JTable table )
    int numCols = table.getColumnCount();
    int row = table.getSelectedRow();
    System.out.println(row);
    javax.swing.table.TableModel model = table.getModel();
    for(int j=0;j < numCols; j++)
    System.out.println(" " + model.getValueAt(row,j));
    System.out.println();
    System.out.println("-----------------------------------------------");
    //CREATE ADD PRINTER DIALOG
    class addPrinterDialog extends JDialog
    public addPrinterDialog(JFrame owner)
    super(owner, "ap1", true);
    final ButtonGroup rbg = new ButtonGroup();
    JPane

    Ok  I have the table  on the page  I created a css with a background image called .search  How to I link that to the table so It shows the image
    I am only used to doing certain css items   Never didi this before
    THXS STeve

Maybe you are looking for

  • How can i disable a button in the application tool bar of a standard trans?

    Hi Experts,    I want to disable the create button in the application tool bar of the standard transaction cv03n. Is there any method?

  • Inbound delivery item deleted is not deleted from BI DSO?

    Hi All   An Inbound deliver created and pushed to BI.. Source PSA is FULL UPDATE and DTP is DELTA UPDATE Ex: 800000 10   10000                     20  10000 This is what pushed to ODS..Later next day, they deleted the to 800000 10 10000 So PSA is ref

  • After ejecting iPod in iTunes

    Hi, This is not really a problem, but when I've Ejected my iPod Nano in iTunes, and I yet want to load music onto it, how do I reconnect the iPod (without having to pull the USB-cable out of my computer, having it to think, pushing the USB-cable into

  • Filter Issue in Oracle BI

    Hi, I am using dashboard prompts to filter the data for a request, for that i put the corresponding filter to the request but when i am selecting the data from dashboard to filter the data it doesn't work. did i miss something? its urgent for me... s

  • AWE Configuration - Elapsed Time Approval in Initiated Status

    We are configuring AWE in 9.1. We are using TLReportedTime Process ID and have a very simple set up - 1 stage, 1 path, 1 step. We enter time for a 2 week period in Self Service Time entry and submit. The first day routes to the supervisor as it shoul