Search Results

Search found 230 results on 10 pages for 'jbutton'.

Page 2/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Java Simple Calculator

    - by Lahiru Kavinda
    I have made this calculator program in Java. This works well only when two numbers are calculated at one time. That means to get the sum of 1+2+3 you have to go this way : press 1 press + press 2 press = press + press 3 press = and it calculates it as 6. But I want to program this so that I can get the answer by: press 1 press + press 2 press + press 3 press = but this gives the answer 5!!! How to code this so that it works like an ordinary calculator? Here is my code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class cal1 extends JFrame { double op1 = 0d, op2 = 0d; double result = 0d; char action; boolean b = false; boolean pressequal = false; public cal1() { makeUI(); } private void makeUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); b0 = new JButton("0"); b1 = new JButton("1"); b2 = new JButton("2"); b3 = new JButton("3"); b4 = new JButton("4"); b5 = new JButton("5"); b6 = new JButton("6"); b7 = new JButton("7"); b8 = new JButton("8"); b9 = new JButton("9"); bDot = new JButton("."); bMul = new JButton("*"); bDiv = new JButton("/"); bPlus = new JButton("+"); bMinus = new JButton("-"); bEq = new JButton("="); t = new JTextField(12); t.setFont(new Font("Tahoma", Font.PLAIN, 24)); t.setHorizontalAlignment(JTextField.RIGHT); numpad = new JPanel(); display = new JPanel(); numpad.add(b7); numpad.add(b8); numpad.add(b9); numpad.add(bMul); numpad.add(b4); numpad.add(b5); numpad.add(b6); numpad.add(bDiv); numpad.add(b1); numpad.add(b2); numpad.add(b3); numpad.add(bMinus); numpad.add(bDot); numpad.add(b0); numpad.add(bEq); numpad.add(bPlus); numpad.setLayout(new GridLayout(4, 5, 5, 4)); display.add(t); add(display, BorderLayout.NORTH); add(numpad, BorderLayout.CENTER); t.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { typeOnt(e); } }); b0.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b0pressed(e); } }); b1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b1pressed(e); } }); b2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b2pressed(e); } }); b3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b3pressed(e); } }); b4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b4pressed(e); } }); b5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b5pressed(e); } }); b6.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b6pressed(e); } }); b7.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b7pressed(e); } }); b8.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b8pressed(e); } }); b9.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b9pressed(e); } }); bDot.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bDotpressed(e); } }); bPlus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bPlusPressed(e); } }); bMinus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bMinusPressed(e); } }); bMul.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bMulPressed(e); } }); bDiv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bDivPressed(e); } }); bEq.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bEqpressed(e); } }); } void typeOnt(KeyEvent e) { e.consume(); } void b0pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "0"); } else { t.setText(t.getText() + "0"); } } void b1pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "1"); } else { t.setText(t.getText() + "1"); } } void b2pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "2"); } else { t.setText(t.getText() + "2"); } } void b3pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "3"); } else { t.setText(t.getText() + "3"); } } void b4pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "4"); } else { t.setText(t.getText() + "4"); } } void b5pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "5"); } else { t.setText(t.getText() + "5"); } } void b6pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "6"); } else { t.setText(t.getText() + "6"); } } void b7pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "7"); } else { t.setText(t.getText() + "7"); } } void b8pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "8"); } else { t.setText(t.getText() + "8"); } } void b9pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "9"); } else { t.setText(t.getText() + "9"); } } void bDotpressed(ActionEvent e) { if (!t.getText().contains(".")) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "0."); } else if (t.getText().isEmpty()) { t.setText("0."); } else { t.setText(t.getText() + "."); } } } void bPlusPressed(ActionEvent e) { b = true; action = '+'; op1 = Double.parseDouble(t.getText()); } void bMinusPressed(ActionEvent e) { b = true; action = '-'; op1 = Double.parseDouble(t.getText()); } void bMulPressed(ActionEvent e) { b = true; action = '*'; op1 = Double.parseDouble(t.getText()); } void bDivPressed(ActionEvent e) { b = true; action = '/'; op1 = Double.parseDouble(t.getText()); } void bEqpressed(ActionEvent e) { op2 = Double.parseDouble(t.getText()); doCal(); } void doCal() { switch (action) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case '*': result = op1 * op2; break; case '/': result = op1 / op2; break; } t.setText(String.valueOf(result)); } public static void main(String[] args) { new cal1().setVisible(true); } JButton b0; JButton b1; JButton b2; JButton b3; JButton b4; JButton b5; JButton b6; JButton b7; JButton b8; JButton b9; JButton bDot; JButton bPlus; JButton bMinus; JButton bMul; JButton bDiv; JButton bEq; JPanel display; JPanel numpad; JTextField t; }

    Read the article

  • How to get components from a JFrame with a GridLayout?

    - by NlightNfotis
    I have a question about Java and JFrame in particular. Let's say I have a JFrame that I am using with a GridLayout. Supposing that I have added JButtons in the JFrame, how can I gain access to the one I want using it's position (by position, I mean a x and a y, used to define the exact place on the Grid). I have tried several methods, for instance getComponentAt(int x, int y), and have seen that those methods do not work as intended when combined with GridLayout, or at least don't work as intended in my case. So I tried using getComponent(), which seems fine. The latest method, that seems to be on a right track for me is (assuming I have a JFrame with a GridLayout with 7 rows and 7 columns, x as columns, y as rows): public JButton getButtonByXAndY(int x, int y) { return (JButton) this.getContentPane().getComponent((y-1) * 7 + x); } Using the above, say I want to get the JButton at (4, 4), meaning the 25th JButton in the JFrame, I would index through the first 21 buttons at first, and then add 4 more, finally accessing the JButton I want. Problem is this works like that in theory only. Any ideas? P.S sorry for linking to an external website, but stack overflow won't allow me to upload the image, because I do not have the required reputation.

    Read the article

  • Java swing hold buttons

    - by Simon Charette
    Hi, I'm trying to create a subclass of JButton or AbstractButton that would call specified .actionPerformed as long as the mouse is held down on the button. So far I was thinking of extending JButton, adding a mouse listener on creation (inside constructor) and calling actionPerformed while the mouse is down. So far i came up with that but I was wondwering if I was on the right track and if so, how to correctly implement the "held down" logic. package components; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JButton; public class HoldButton extends JButton { private class HeldDownMouseListener implements MouseListener { private boolean mouseIsHeldDown; private HoldButton button; private long millis; public HeldDownMouseListener(HoldButton button, long millis) { this.button = button; this.millis = millis; } @Override public void mouseClicked(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { mouseIsHeldDown = true; // This should be run in a sub thread? // while (mouseIsHeldDown) { // button.fireActionPerformed(new ActionEvent(button, ActionEvent.ACTION_PERFORMED, "heldDown")); // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // e.printStackTrace(); // continue; // } // } } @Override public void mouseReleased(MouseEvent arg0) { mouseIsHeldDown = false; } } public HoldButton() { addHeldDownMouseListener(); } public HoldButton(Icon icon) { super(icon); addHeldDownMouseListener(); } public HoldButton(String text) { super(text); addHeldDownMouseListener(); } public HoldButton(Action a) { super(a); addHeldDownMouseListener(); } private void addHeldDownMouseListener() { addMouseListener(new HeldDownMouseListener(this, 300)); } } Thanks a lot for your time.

    Read the article

  • Why setPreferredSize does not change the size of the button?

    - by Roman
    Here is the code: import javax.swing.*; import java.awt.event.*; import java.awt.*; public class TestGrid { public static void main(String[] args) { JFrame frame = new JFrame("Colored Trails"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(4, 9)); panel.setMaximumSize(new Dimension(9*30-20,4*30)); JButton btn; for (int i=1; i<=4; i++) { for (int j=1; j<=4; j++) { btn = new JButton(); btn.setPreferredSize(new Dimension(30, 30)); panel.add(btn); } btn = new JButton(); btn.setPreferredSize(new Dimension(30, 10)); panel.add(btn); for (int j=1; j<=4; j++) { btn = new JButton(); btn.setPreferredSize(new Dimension(30, 30)); panel.add(btn); } } mainPanel.add(panel); frame.add(mainPanel); frame.setSize(450,950); frame.setVisible(true); } } I suppose to have a table of buttons with 4 rows and 9 columns. And the middle column should be narrower that other columns. I tried Dimension(30, 10) and Dimension(30, 10) both have no effect on the width of the middle column. Why?

    Read the article

  • Java/Swing: low-profile button height?

    - by Jason S
    I would like to reduce the vertical size of a JButton. The following code works fine for K 1 but I can't seem to reduce the size. Any suggestions? JButton button = /* ... get button here ... */ Dimension d = button.getPreferredSize(); d.setSize(d.getWidth(), d.getHeight()*K); button.setPreferredSize(d);

    Read the article

  • How can I set the Jbuttons in a preferred order?

    - by Umzz Mo
    I have a grid of 30 buttons, and I want to have it from left to right then goes down, right to left, down again left to right. Basically the numbering would be as follow: 1 2 3 4 5 6 7 8 9 10 20 19 18 17 16 15 14 13 12 11 21 22 23 24 25 26 27 28 29 30 So if I have a piece on the button 10 and I instruct it to move up 2 bits it would land on 12 not 19. Below is my Code: //Creates the button using the loop, adds it into the panel and frame. JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3,10)); JButton [] buttons = new JButton[30]; for(int i=0;i<30;i++){ buttons[i] = new JButton("label" + i); buttons[i].setBackground(Color.white); //Puts the player 1 piece on button 1,3,5,7,9 and player 2 piece on button 2,4,6,8,10 if (i < 10) { if (i%2 == 0) { buttons[i].setIcon(piece1); } else { buttons[i].setIcon(piece2); } } panel.add(buttons[i]); } frame.add(panel, BorderLayout.CENTER);

    Read the article

  • JPanel not listening to key event when there is a child component with JButton on it

    - by Yifu
    I'm working on a map editor for my college project. And I had a problem that the map panel is not listening key event while it should. This happens when I add a ToolBarPane (which extends JPanel) with JComponent such as JButton, JComboBox that implements ActionListener on it AND the map panel (which extends the JPanel) together on to the Frame (I used BorderLayout). I have System.out.println statement to test if the key press is received, and it's not printing, if I remove the ToolBar, the key listener works again, so is the mouseListenner is disabled just like the keyListener, which means I can't handle press events etc, but the mouseListener works fine and I can still handle mouse move event. Here is a screen shot how it works without the ToolBarPane http://img684.imageshack.us/img684/3232/sampleku.png note that you can use the mouse to put images on the map, you can also select images using the mouse just like a laser tool, and by pressing number key you can switch between different images, this works fine until I add the ToolBarPane which shows like this: img291.imageshack.us/img291/8020/failve.png (please add http before that, i can only post one hyperlink) (I can't post images here cuz im a new user) With the ToolBarPane on I was no longer able to handle the key event. I guess it might by that the focus as been transfered to that panel somehow, but not sure at all. Does and body know this and can help me out? Thanks very much

    Read the article

  • Java - How can I edit the size and position of a button using Swing?

    - by mino
    I have the following code but I'd like to structure several buttons of certain sizes. I'm just wondering how to do this as I've Googled it and found several different methods but none seem to work. Any advice? import javax.swing.*; public class GUI { public static void main(String[] args) { JFrame window = new JFrame(); window.setSize(500, 500); window.setTitle("My Application"); JButton button = new JButton("click me"); window.add(button); window.setVisible(true); } }

    Read the article

  • Why this method does not use any properties of the object?

    - by Roman
    Here I found this code: import java.awt.*; import javax.swing.*; public class FunWithPanels extends JFrame { public static void main(String[] args) { FunWithPanels frame = new FunWithPanels(); frame.doSomething(); } void doSomething() { Container c = getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(new JButton("A"), BorderLayout.NORTH); p1.add(new JButton("B"), BorderLayout.WEST); JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3, 2)); p2.add(new JButton("F")); p2.add(new JButton("G")); p2.add(new JButton("H")); p2.add(new JButton("I")); p2.add(new JButton("J")); p2.add(new JButton("K")); JPanel p3 = new JPanel(); p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS)); p3.add(new JButton("L")); p3.add(new JButton("M")); p3.add(new JButton("N")); p3.add(new JButton("O")); p3.add(new JButton("P")); c.setLayout(new BorderLayout()); c.add(p1, BorderLayout.CENTER); c.add(p2, BorderLayout.SOUTH); c.add(p3, BorderLayout.EAST); pack(); setVisible(true); } } I do not understand how "doSomething" use the fact that "frame" is an instance of the class JFrame. It is not clear to me because there is no reference to "this" in the code for the method "doSomething".

    Read the article

  • Java Package - To create a button and import one when needed.

    - by Zopyrus
    This is more like a package/import test. We'll start with my base folder at .../javaf/test.java My goal is to create subcategory and create a class with a button that I can import to test.java when I need a button. I feel like I've done it right, I know that the button doesn't do anything as of now, but I just want to make the whole thing work and expand the code thereafter. So here goes - This is test.java import paket.*; // importing classes from subcategory paket! import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class test { public test() { JFrame myFrame; JPanel myPanel; myFrame = new JFrame("Hello FramWorld"); myPanel = new JPanel(); // Here I want to add the object created in paket/myButts.java // The problem is how to make these two lines work. myButts myButton = new myButts(); myPanel.add(myButton); myFrame.setVisible(true); myFrame.getContentPane().add(myPanel, BorderLayout.CENTER); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.pack(); } public static void main(String args[]) { new test(); } } And here is my .../javaf/paket/myButts.java package paket; // Here is the package function (ought to work like a link) import javax.swing.*; import java.awt.*; import java.awt.event.*; // This class should only create a button. public class myButts { public myButts() { JButton myButt = new JButton(); } } I've compiled myButts.java with no errors. But then I compile test.java and it gives me the following error: test.java:19: cannot find symbol symbol : method add(paket.myButts) location: class javax.swing.JPanel myPanel.add(myButton); Thanks for reading, Z

    Read the article

  • Jdbc - Connect remote Mysql Database error

    - by Guilherme Ruiz
    I'm using JDBC to connect my program to a MySQL database. I already put the port number and yes, my database have permission to access. When i use localhost work perfectly, but when i try connect to a remote MySQL database, show this error on console. java.lang.ExceptionInInitializerError Caused by: java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:454) at java.lang.Integer.parseInt(Integer.java:527) at serial.BDArduino.<clinit>(BDArduino.java:25) Exception in thread "main" Java Result: 1 CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo) Thank you in Advance ! MAIN CODE /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package serial; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author Ruiz */ public class BDArduino extends JFrame { static boolean connected = false; static int aux_sql8 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin8")); static int aux_sql2 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin2")); CommPort commPort = null; SerialPort serialPort = null; InputStream inputStream = null; static OutputStream outputStream = null; String comPortNum = "COM10"; int baudRate = 9600; int[] intArray = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; /** * Creates new form ArduinoTest */ public BDArduino() { //super("Arduino Test App"); initComponents(); } class Escrita extends Thread { private int i; public void run() { while (true) { System.out.println("Número :" + i++); } } } //public void actionPerformed(ActionEvent e) { // String arg = e.getActionCommand(); public static void writeData(int a) throws IOException { outputStream.write(a); } public void action(String arg) { System.out.println(arg); Object[] msg = {"Baud Rate: ", "9600", "COM Port #: ", "COM10"}; if (arg == "connect") { if (connected == false) { new BDArduino.ConnectionMaker().start(); } else { closeConnection(); } } if (arg == "disconnect") { serialPort.close(); closeConnection(); } if (arg == "p2") { System.out.print("Pin #2\n"); try { outputStream.write(intArray[0]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p3") { System.out.print("Pin #3\n"); try { outputStream.write(intArray[1]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p4") { System.out.print("Pin #4\n"); try { outputStream.write(intArray[2]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p5") { System.out.print("Pin #5\n"); try { outputStream.write(intArray[3]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p6") { System.out.print("Pin #6\n"); try { outputStream.write(intArray[4]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p7") { System.out.print("Pin #7\n"); try { outputStream.write(intArray[5]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p8") { System.out.print("Pin #8\n"); try { outputStream.write(intArray[6]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p9") { System.out.print("Pin #9\n"); try { outputStream.write(intArray[7]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p10") { System.out.print("Pin #10\n"); try { outputStream.write(intArray[8]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p11") { System.out.print("Pin #11\n"); try { outputStream.write(intArray[9]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p12") { System.out.print("Pin #12\n"); try { outputStream.write(intArray[10]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p13") { System.out.print("Pin #12\n"); try { outputStream.write(intArray[11]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } } //******************************************************* //Arduino Connection *************************************** //****************************************************** void closeConnection() { try { outputStream.close(); } catch (Exception ex) { ex.printStackTrace(); String cantCloseConnectionMessage = "Can't Close Connection!"; JOptionPane.showMessageDialog(null, cantCloseConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } connected = false; System.out.print("\nDesconectado\n"); String disconnectedConnectionMessage = "Desconectado!"; JOptionPane.showMessageDialog(null, disconnectedConnectionMessage, "Desconectado", JOptionPane.INFORMATION_MESSAGE); }//end closeConnection() void connect() throws Exception { String portName = comPortNum; CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if (portIdentifier.isCurrentlyOwned()) { System.out.println("Error: Port is currently in use"); String portInUseConnectionMessage = "Port is currently in use!\nTry Again Later..."; JOptionPane.showMessageDialog(null, portInUseConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } else { commPort = portIdentifier.open(this.getClass().getName(), 2000); if (commPort instanceof SerialPort) { serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); outputStream = serialPort.getOutputStream(); } else { System.out.println("Error: Only serial ports are handled "); String onlySerialConnectionMessage = "Serial Ports ONLY!"; JOptionPane.showMessageDialog(null, onlySerialConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } }//end else //wait some time try { Thread.sleep(300); } catch (InterruptedException ie) { } }//end connect //******************************************************* //*innerclasses****************************************** //******************************************************* public class ConnectionMaker extends Thread { public void run() { //try to make a connection try { connect(); } catch (Exception ex) { ex.printStackTrace(); System.out.print("ERROR: Cannot connect!"); String cantConnectConnectionMessage = "Cannot Connect!\nCheck the connection settings\nand/or your configuration\nand try again!"; JOptionPane.showMessageDialog(null, cantConnectConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } //show status serialPort.notifyOnDataAvailable(true); connected = true; //send ack System.out.print("\nConnected\n"); String connectedConnectionMessage = "Conectado!"; JOptionPane.showMessageDialog(null, connectedConnectionMessage, "Conectado", JOptionPane.INFORMATION_MESSAGE); }//end run }//end ConnectionMaker /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { btnp2 = new javax.swing.JButton(); btncon = new javax.swing.JButton(); btndesc = new javax.swing.JButton(); btnp3 = new javax.swing.JButton(); btnp4 = new javax.swing.JButton(); btnp5 = new javax.swing.JButton(); btnp9 = new javax.swing.JButton(); btnp6 = new javax.swing.JButton(); btnp7 = new javax.swing.JButton(); btnp8 = new javax.swing.JButton(); btn13 = new javax.swing.JButton(); btnp10 = new javax.swing.JButton(); btnp11 = new javax.swing.JButton(); btnp12 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnp2.setText("2"); btnp2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp2MouseClicked(evt); } }); btncon.setText("Conectar"); btncon.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnconMouseClicked(evt); } }); btndesc.setText("Desconectar"); btndesc.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btndescMouseClicked(evt); } }); btnp3.setText("3"); btnp3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp3MouseClicked(evt); } }); btnp4.setText("4"); btnp4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp4MouseClicked(evt); } }); btnp5.setText("5"); btnp5.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp5MouseClicked(evt); } }); btnp9.setText("9"); btnp9.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp9MouseClicked(evt); } }); btnp6.setText("6"); btnp6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp6MouseClicked(evt); } }); btnp7.setText("7"); btnp7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp7MouseClicked(evt); } }); btnp8.setText("8"); btnp8.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp8MouseClicked(evt); } }); btn13.setText("13"); btn13.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btn13MouseClicked(evt); } }); btnp10.setText("10"); btnp10.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp10MouseClicked(evt); } }); btnp11.setText("11"); btnp11.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp11MouseClicked(evt); } }); btnp12.setText("12"); btnp12.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp12MouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(btncon) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btndesc)) .addGroup(layout.createSequentialGroup() .addComponent(btnp6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(btnp10, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp12, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn13, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(btnp2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btncon) .addComponent(btndesc)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp2) .addComponent(btnp3) .addComponent(btnp4) .addComponent(btnp5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp6) .addComponent(btnp7) .addComponent(btnp8) .addComponent(btnp9)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp10) .addComponent(btnp11) .addComponent(btnp12) .addComponent(btn13)) .addGap(22, 22, 22)) ); pack(); }// </editor-fold> private void btnp2MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p2"); } private void btnconMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("connect"); } private void btndescMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("disconnect"); } private void btnp3MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p3"); } private void btnp4MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p4"); } private void btnp5MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here action("p5"); } private void btnp9MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p9"); } private void btnp6MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p6"); } private void btnp7MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p7"); } private void btnp8MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p8"); } private void btn13MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p13"); } private void btnp10MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p10"); } private void btnp11MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p11"); } private void btnp12MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p12"); } /** * @param args the command line arguments */ public static void main(String args[]) throws IOException { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BDArduino().setVisible(true); } }); //} while (true) { // int sql8 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin8")); if (connected == true && sql8 != aux_sql8) { aux_sql8 = sql8; if(sql8 == 1){ writeData(2); }else{ writeData(3); } } int sql2 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin2")); if (connected == true && sql2 != aux_sql2) { aux_sql2 = sql2; if(sql2 == 1){ writeData(4); }else{ writeData(5); } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } // Variables declaration - do not modify private javax.swing.JButton btn13; private javax.swing.JButton btncon; private javax.swing.JButton btndesc; private javax.swing.JButton btnp10; private javax.swing.JButton btnp11; private javax.swing.JButton btnp12; private javax.swing.JButton btnp2; private javax.swing.JButton btnp3; private javax.swing.JButton btnp4; private javax.swing.JButton btnp5; private javax.swing.JButton btnp6; private javax.swing.JButton btnp7; private javax.swing.JButton btnp8; private javax.swing.JButton btnp9; // End of variables declaration }

    Read the article

  • Drawing graphics on top of a JButton

    - by trinth
    I have a situation wherein I have a bunch of JButtons on a GridLayout. I need each of the JButtons to have: a background image (but retain the ability to keep the default button look if needed) custom graphics drawn on top by other classes I have no trouble with the background image, since I am using setIcon() but I am having problems drawing things on top of the background. At one point I was able to draw on top of the button, but after the button was clicked, the drawings disappeared. How can make the button keep this drawing state? Basically, I need a way for my JButtons to have public methods that would allow another class to draw anything on it such as: public void drawSomething() { Graphics g = this.getGraphics(); g.drawOval(3,2,2,2); repaint(); } or public Graphics getGraphics() { return this.getGraphics(); } then another class could do this: button.getGraphics().drawSomething(); The latter is more what I am looking for but the first is equally useful. Is there any way to go about this? Also, overriding the parent class method paintComponent() doesn't help since I need each button to have different graphics.

    Read the article

  • I'm tired of JButtons, how can I make a nicer GUI in java ?

    - by Jules Olléon
    So far I've only build "small" graphical applications, using swing and JComponents as I learned at school. Yet I can't bear ugly JButtons anymore. I've tried to play with the different JButton methods, like changing colors, putting icons etc. but I'm still not satisfied. How do you make a nicer GUI in java ? I'm looking for not-too-heavy alternatives (like, without big frameworks or too complicated libraries).

    Read the article

  • Why I see only part of the image in the button?

    - by Roman
    I add an image to the button in the following way: ImageIcon icon = new ImageIcon("images/col.jpg"); tmp = new JButton(icon); My image is a red sphere but in my button I see only read color. I assume that I see just a small part of the sphere. How can I see the whole image in the button?

    Read the article

  • actionlistener not responding in java calculator

    - by tokee
    hi, please see calculator interface code below, from my beginners point of view the "1" should display when it's pressed but evidently i'm doing something wrong. any suggestiosn please? import java.awt.*; import javax.swing.*; import javax.swing.border.*; import java.awt.event.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** *A Class that operates as the framework for a calculator. *No calculations are performed in this section */ public class CalcFrame extends JPanel { private CalcEngine calc; private JFrame frame; private JTextField display; private JLabel status; /** * Constructor for objects of class GridLayoutExample */ //public CalcFrame(CalcEngine engine) //{ //frame.setVisible(true); // calc = engine; // makeFrame(); //} public CalcFrame() { makeFrame(); calc = new CalcEngine(); } class ButtonListener implements ActionListener { ButtonListener() { } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("1")) { System.out.println("1"); } } } /** * This allows you to quit the calculator. */ // Alows the class to quit. private void quit() { System.exit(0); } // Calls the dialog frame with the information about the project. private void showAbout() { JOptionPane.showMessageDialog(frame, "Declan Hodge and Tony O'Keefe Group Project", "About Calculator Group Project", JOptionPane.INFORMATION_MESSAGE); } // ---- swing stuff to build the frame and all its components ---- /** * The following creates a layout of the calculator frame. */ private void makeFrame() { frame = new JFrame("Group Project Calculator"); makeMenuBar(frame); JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setLayout(new BorderLayout(8, 8)); contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10)); /** * Insert a text field */ display = new JTextField(8); contentPane.add(display, BorderLayout.NORTH); //Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(4, 5)); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); contentPane.add(new JButton("9")); contentPane.add(new JButton("8")); contentPane.add(new JButton("7")); contentPane.add(new JButton("6")); contentPane.add(new JButton("5")); contentPane.add(new JButton("4")); contentPane.add(new JButton("3")); contentPane.add(new JButton("2")); contentPane.add(new JButton("1")); contentPane.add(new JButton("0")); contentPane.add(new JButton("+")); contentPane.add(new JButton("-")); contentPane.add(new JButton("/")); contentPane.add(new JButton("*")); contentPane.add(new JButton("=")); contentPane.add(new JButton("C")); contentPane.add(new JButton("CE")); contentPane.add(new JButton("%")); contentPane.add(new JButton("#")); //contentPane.add(buttonPanel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } /** * Create the main frame's menu bar. * The frame that the menu bar should be added to. */ private void makeMenuBar(JFrame frame) { final int SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu menu; JMenuItem item; // create the File menu menu = new JMenu("File"); menubar.add(menu); // create the Quit menu with a shortcut "Q" key. item = new JMenuItem("Quit"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { quit(); } }); menu.add(item); // Adds an about menu. menu = new JMenu("About"); menubar.add(menu); // Displays item = new JMenuItem("Calculator Project"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAbout(); } }); menu.add(item); } }

    Read the article

  • Having a different action for each button dynamically created in a loop

    - by Oliver
    Hi, use this website a lot but first time posting. My program creates a number of buttons depending on the number of records in a file. E.g. 5 records, 5 buttons. The buttons are being created but i'm having a problem with the action listener. If add the action listener in the loop every button does the same thing; but if I add the action listener outside the loop it just adds the action listener to last button. Any ideas? Here is what I have code-wise (I've just added the for loop to save space): int j=0; for(int i=0; i<namesA.size(); i++) { b = new JButton(""+namesA.get(i)+""); conPanel.add(b); conFrame.add(conPanel); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae2){ System.out.println(namesA.get(j)); } }}); j++; } Much Appreciated

    Read the article

  • Using getters/setters in Java

    - by Crystal
    I'm having some trouble with the idea of accessing variables from other classes. I had a post here: http://stackoverflow.com/questions/3011642/having-access-to-a-private-variable-from-other-classes-in-java where I got some useful information, and thought an example would be better show it, and ask a separate question as well. I have a form that I can input data to, and it has a List variable. I didn't make it static at first, but I thought if I needed to get the total size from another class, then I wouldn't create an instance of that class in order to use the function to getTotalContacts. I basically want to update my status bar with the total number of contacts that are in my list. One of the members said in the above post to use the original Foo member to get the contacts, but I'm not sure how that works in this case. Any thoughts would be appreciated. Thanks. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class AddressBook { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { AddressBookFrame frame = new AddressBookFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open"); JMenuItem saveItem = new JMenuItem("Save"); JMenuItem saveAsItem = new JMenuItem("Save As"); JMenuItem printItem = new JMenuItem("Print"); JMenuItem exitItem = new JMenuItem("Exit"); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(saveAsItem); fileMenu.add(printItem); fileMenu.add(exitItem); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); JMenuItem newItem = new JMenuItem("New"); JMenuItem editItem = new JMenuItem("Edit"); JMenuItem deleteItem = new JMenuItem("Delete"); JMenuItem findItem = new JMenuItem("Find"); JMenuItem firstItem = new JMenuItem("First"); JMenuItem previousItem = new JMenuItem("Previous"); JMenuItem nextItem = new JMenuItem("Next"); JMenuItem lastItem = new JMenuItem("Last"); editMenu.add(newItem); editMenu.add(editItem); editMenu.add(deleteItem); editMenu.add(findItem); editMenu.add(firstItem); editMenu.add(previousItem); editMenu.add(nextItem); editMenu.add(lastItem); menuBar.add(editMenu); JMenu helpMenu = new JMenu("Help"); JMenuItem documentationItem = new JMenuItem("Documentation"); JMenuItem aboutItem = new JMenuItem("About"); helpMenu.add(documentationItem); helpMenu.add(aboutItem); menuBar.add(helpMenu); frame.setVisible(true); } }); } } class AddressBookFrame extends JFrame { public AddressBookFrame() { setLayout(new BorderLayout()); setTitle("Address Book"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); AddressBookToolBar toolBar = new AddressBookToolBar(); add(toolBar, BorderLayout.NORTH); AddressBookStatusBar aStatusBar = new AddressBookStatusBar(); add(aStatusBar, BorderLayout.SOUTH); AddressBookForm form = new AddressBookForm(); add(form, BorderLayout.CENTER); } public static final int DEFAULT_WIDTH = 500; public static final int DEFAULT_HEIGHT = 500; } /* Create toolbar buttons and add buttons to toolbar */ class AddressBookToolBar extends JPanel { public AddressBookToolBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); JToolBar bar = new JToolBar(); JButton newButton = new JButton("New"); JButton editButton = new JButton("Edit"); JButton deleteButton = new JButton("Delete"); JButton findButton = new JButton("Find"); JButton firstButton = new JButton("First"); JButton previousButton = new JButton("Previous"); JButton nextButton = new JButton("Next"); JButton lastButton = new JButton("Last"); bar.add(newButton); bar.add(editButton); bar.add(deleteButton); bar.add(findButton); bar.add(firstButton); bar.add(previousButton); bar.add(nextButton); bar.add(lastButton); add(bar); } } /* Creates the status bar string */ class AddressBookStatusBar extends JPanel { public AddressBookStatusBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); this.statusBarString = new JLabel("Total: " + AddressBookForm.getTotalContacts()); add(this.statusBarString); } public void updateLabel() { contactsLabel.setText(AddressBookForm.getTotalContacts().toString()); } private JLabel statusBarString; private JLabel contactsLabel; } class AddressBookForm extends JPanel { public AddressBookForm() { // create form panel this.setLayout(new GridLayout(2, 1)); JPanel formPanel = new JPanel(); formPanel.setLayout(new GridLayout(4, 2)); firstName = new JTextField(20); lastName = new JTextField(20); telephone = new JTextField(20); email = new JTextField(20); JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT); formPanel.add(firstNameLabel); formPanel.add(firstName); JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT); formPanel.add(lastNameLabel); formPanel.add(lastName); JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT); formPanel.add(telephoneLabel); formPanel.add(telephone); JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT); formPanel.add(emailLabel); formPanel.add(email); add(formPanel); // create button panel JPanel buttonPanel = new JPanel(); JButton insertButton = new JButton("Insert"); JButton displayButton = new JButton("Display"); ActionListener insertAction = new AddressBookListener(); ActionListener displayAction = new AddressBookListener(); insertButton.addActionListener(insertAction); displayButton.addActionListener(displayAction); buttonPanel.add(insertButton); buttonPanel.add(displayButton); add(buttonPanel); } public static int getTotalContacts() { return addressList.size(); } //void addContact(Person contact); private JTextField firstName; private JTextField lastName; private JTextField telephone; private JTextField email; private JLabel contacts; private static List<Person> addressList = new ArrayList<Person>(); private class AddressBookListener implements ActionListener { public void actionPerformed(ActionEvent e) { String buttonPressed = e.getActionCommand(); System.out.println(buttonPressed); if (buttonPressed == "Insert") { Person aPerson = new Person(firstName.getText(), lastName.getText(), telephone.getText(), email.getText()); addressList.add(aPerson); } else { for (Person p : addressList) { System.out.println(p); } } } } } My other question is why do I get the error, "int cannot be dereferenced contactsLabel.setText(AddressbookForm.getTotalContacts().toString()); Thanks!

    Read the article

  • Passing ActionListeners in Java, pack()

    - by Crystal
    Two questions. First question is I'm trying to create a simple form that when you press a button, it adds a Person object to the ArrayList. However, since I am not used to GUIs, I tried creating one and am first just trying to get the user input from the JTextField, create an ActionListener object of the appropriate type, so once that works, then I can pass in all the JTextField inputs to create my Person object. Unfortunately, I am not getting any data when I type in something to the firstName JTextField and was wondering if someone could look at my code below. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class AddressBook { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { AddressBookFrame frame = new AddressBookFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open"); JMenuItem saveItem = new JMenuItem("Save"); JMenuItem saveAsItem = new JMenuItem("Save As"); JMenuItem printItem = new JMenuItem("Print"); JMenuItem exitItem = new JMenuItem("Exit"); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(saveAsItem); fileMenu.add(printItem); fileMenu.add(exitItem); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); JMenuItem newItem = new JMenuItem("New"); JMenuItem editItem = new JMenuItem("Edit"); JMenuItem deleteItem = new JMenuItem("Delete"); JMenuItem findItem = new JMenuItem("Find"); JMenuItem firstItem = new JMenuItem("First"); JMenuItem previousItem = new JMenuItem("Previous"); JMenuItem nextItem = new JMenuItem("Next"); JMenuItem lastItem = new JMenuItem("Last"); editMenu.add(newItem); editMenu.add(editItem); editMenu.add(deleteItem); editMenu.add(findItem); editMenu.add(firstItem); editMenu.add(previousItem); editMenu.add(nextItem); editMenu.add(lastItem); menuBar.add(editMenu); JMenu helpMenu = new JMenu("Help"); JMenuItem documentationItem = new JMenuItem("Documentation"); JMenuItem aboutItem = new JMenuItem("About"); helpMenu.add(documentationItem); helpMenu.add(aboutItem); menuBar.add(helpMenu); frame.setVisible(true); } }); } } class AddressBookFrame extends JFrame { public AddressBookFrame() { setLayout(new BorderLayout()); setTitle("Address Book"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); AddressBookToolBar toolBar = new AddressBookToolBar(); add(toolBar, BorderLayout.NORTH); AddressBookStatusBar aStatusBar = new AddressBookStatusBar("5"); add(aStatusBar, BorderLayout.SOUTH); AddressBookForm form = new AddressBookForm(); add(form, BorderLayout.CENTER); } public static final int DEFAULT_WIDTH = 500; public static final int DEFAULT_HEIGHT = 500; } /* Create toolbar buttons and add buttons to toolbar */ class AddressBookToolBar extends JPanel { public AddressBookToolBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); JToolBar bar = new JToolBar(); JButton newButton = new JButton("New"); JButton editButton = new JButton("Edit"); JButton deleteButton = new JButton("Delete"); JButton findButton = new JButton("Find"); JButton firstButton = new JButton("First"); JButton previousButton = new JButton("Previous"); JButton nextButton = new JButton("Next"); JButton lastButton = new JButton("Last"); bar.add(newButton); bar.add(editButton); bar.add(deleteButton); bar.add(findButton); bar.add(firstButton); bar.add(previousButton); bar.add(nextButton); bar.add(lastButton); add(bar); } } /* Creates the status bar string */ class AddressBookStatusBar extends JPanel { public AddressBookStatusBar(String statusBarString) { setLayout(new FlowLayout(FlowLayout.LEFT)); this.statusBarString = new JLabel("Total number of people: " + statusBarString); add(this.statusBarString); } private JLabel statusBarString; private int totalContacts; } class AddressBookForm extends JPanel { public AddressBookForm() { this.setLayout(new GridLayout(2, 1)); JPanel formPanel = new JPanel(); formPanel.setLayout(new GridLayout(4, 2)); JTextField firstName = new JTextField(20); JTextField lastName = new JTextField(20); JTextField telephone = new JTextField(20); JTextField email = new JTextField(20); JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT); formPanel.add(firstNameLabel); formPanel.add(firstName); JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT); formPanel.add(lastNameLabel); formPanel.add(lastName); JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT); formPanel.add(telephoneLabel); formPanel.add(telephone); JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT); formPanel.add(emailLabel); formPanel.add(email); add(formPanel); JPanel buttonPanel = new JPanel(); JButton insertButton = new JButton("Insert"); JButton displayButton = new JButton("Display"); // create button actions AddressBookManager insertAction = new AddressBookManager(firstName.getText()); insertButton.addActionListener(insertAction); buttonPanel.add(insertButton); buttonPanel.add(displayButton); add(buttonPanel); } private List<Person> addressList = new ArrayList<Person>(); private class AddressBookManager implements ActionListener { public AddressBookManager(String text) { // addressList.add( setName(text); System.out.println("Test" + text); } public void actionPerformed(ActionEvent e) { System.out.println("Hello" + name); } public void setName(String name) { this.name = name; } private String name; } } Second question is, how do I make my form not take up the whole center space. I don't like the stretch look and was hoping the JTextFields could be just one line long, not a big box. Same thing with the buttons. Any thoughts? Thanks.

    Read the article

  • Setting Mnemonics and Hot Keys for a JOptionPane Dialog

    - by Daniel Bingham
    Is it possible to assign hotkeys and mnemonics to the buttons in a JOptionPane Dialog? I'd like to be able, in a JOptionPane generated message dialog with the options Yes, No and Cancel, press Y to hit the Yes button, N to hit the No button and escape to activate the escape button. Similarly in a dialog with Okay and Cancel buttons I'd like to be able to activate them with enter and escape. I've attempted passing JButtons into the JOptionPane's button Object array with the Mnemonics set already. The mnemonics work and the buttons show up correctly in the dialogs, however, they do not act properly when they are activated. Most noticeably they do not dispose of the dialog. What is the correct way to add hotkeys and Mnemonics to a JOptionPane Dialog's buttons? As always, my apologies ahead of time if this is a duplicate - I searched both Google and Stackoverflow and found nothing.

    Read the article

  • Bad event on java panel

    - by LucaB
    Hi I have a java panel with 4 buttons. When I click on of these buttons, a new frame appears and the first is hidden with setVisibile(false). On that new window, I have another button, but when i click it, I got the event corresponding to the fourth button of the first window. Clicking the button again does the trick, but of course this is not acceptable. Am I missing something? I just show the frames with nameOfTheFrame.setVisible(true); and I have MouseListeners on every button. The code of the last button is simply: System.exit(0); EDIT Sample code: private void btn_joinGamePressed(java.awt.event.MouseEvent evt) { GraphicsTools.getInstance().getCreateGame().setVisible(false); GraphicsTools.getInstance().getMainPanel().setVisible(false); GraphicsTools.getInstance().getRegistration().setVisible(true); } GraphicsTools is a Singleton.

    Read the article

  • Problem with button addition when double clicking a command label

    - by mistique
    Hy, I got an intersting problem which I stumbled upon. When I double click a label in a JLabel I want to add another button in a JPanel, its a shorter way to make a dragg and drop. The problem is that the button doesn't appears only if i'll position the mouse on the area the button should appear. Why does it happens this way? Anyone got a clue? Are there some thread related issues involved? Thanks in advance

    Read the article

  • Why is it not saying I won?

    - by Itachi
    This is my if statement... The buttons show up like this: This is my if statement if((buttons[3].getName()=="x" && buttons[6].getName()=="x" && buttons[9].getText()=="x")||(buttons[2].getName()=="x" && buttons[5].getName()=="x" && buttons[8].getName()=="x")|| ((buttons[1].getName()=="x") && (buttons[4].getName()=="x") && (buttons[7].getName()=="x"))){ JOptionPane.showMessageDialog(null,"X Wins"); } So if I select the 1st, 4th and 7th buttons (the left most 3 buttons) why does it not say "X Wins"? As a sidenote, yes the buttons should have the name "x"

    Read the article

  • How to implement button in a vector

    - by user1880497
    In my table. I want to put some buttons into each row that I can press. But I do not know how to do it public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException { java.sql.ResultSetMetaData metaData = rs.getMetaData(); // names of columns Vector<String> columnNames = new Vector<String>(); int columnCount = metaData.getColumnCount(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); } // data of the table Vector<Vector<Object>> data = new Vector<Vector<Object>>(); while (rs.next()) { Vector<Object> vector = new Vector<Object>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(rs.getObject(columnIndex)); } data.add(vector); } return new DefaultTableModel(data, columnNames); }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >