Search Results

Search found 269 results on 11 pages for 'actionlistener'.

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

  • Timer in Java swing

    - by Yesha
    I'm trying to replace Thread.sleep with a java swing timer as I hear that is much better for graphics. Before, I had something set up like this, but it was interfering with the graphics. while(counter < array.size){ Thread.sleep(array.get(counter).startTime); //do first task Thread.sleep(array.get(counter).secondTime); //do second task Thread.sleep(array.get(counter).thirdTime); //do third task counter++ } Now, I'm trying to replace each Thread.sleep with one of these and then I have the actual events that happen after this, but it does not seem to be waiting at all. int test = array.get(counter).time; ActionListener taskPerformer = new ActionListener(){ public void actionPerformed(ActionEvent evt){ } }; Timer t = new Timer(test, taskPerformer); t.setRepeats(false); t.start(); Basically, how do I ensure that the program will wait without giving it any code to execute inside of the timer? Thank you!

    Read the article

  • How can I communicate with an Object created in another JFrame?

    - by user3093422
    so my program basically consists of two frames. As I click a button on Frame1, Frame2 pops up, and when I click a button on Frame2, and Object is created and the window closes. Now, I need to be able to use the methods of Object in my Frame1, how can this be achieved? I am kind of new to Object-Oriented Programming, sorry, but it's hard to me to explain the situation. Thanks! I will try to put a random code for pure example below. JFrame 1: public class JFrame1 extends JFrame{ variables.. public JFrame1(){ GUIcomponents.... } public static void main(String[] args) { JFrame1 aplicacion = new JFrame1(); aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private class ActList implements ActionListener { public void actionPerformed(ActionEvent event) { new JFrame2(); } } } JFrame 2: public class JFrame2 extends JFrame{ variables.. public JFrame2(){ GUIcomponents.... } private class ActList implements ActionListener { public void actionPerformed(ActionEvent event) { Object object = new Object(); setVisible(false); } } } Sorry if it's messy, I made it in the moment. So yeah, basically I want to JFrame1 to be able to use the getters and settes from Object, which was created in JFrame2. What should I do? Once again, thanks!

    Read the article

  • login form whith java/sqlite

    - by tuxou
    hi I would like to create a login form for my application with the possibility to add or remove users for an sqlite database, i have created the table users(nam, pass) but i can't unclud it in my login form, it someone could help me this is my login code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class login extends JFrame { // Variables declaration private JLabel jLabel1; private JLabel jLabel2; private JTextField jTextField1; private JPasswordField jPasswordField1; private JButton jButton1; private JPanel contentPane; // End of variables declaration public login() { super(); create(); this.setVisible(true); } private void create() { jLabel1 = new JLabel(); jLabel2 = new JLabel(); jTextField1 = new JTextField(); jPasswordField1 = new JPasswordField(); jButton1 = new JButton(); contentPane = (JPanel)this.getContentPane(); // // jLabel1 // jLabel1.setHorizontalAlignment(SwingConstants.LEFT); jLabel1.setForeground(new Color(0, 0, 255)); jLabel1.setText("username:"); // // jLabel2 // jLabel2.setHorizontalAlignment(SwingConstants.LEFT); jLabel2.setForeground(new Color(0, 0, 255)); jLabel2.setText("password:"); // // jTextField1 // jTextField1.setForeground(new Color(0, 0, 255)); jTextField1.setSelectedTextColor(new Color(0, 0, 255)); jTextField1.setToolTipText("Enter your username"); jTextField1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jTextField1_actionPerformed(e); } }); // // jPasswordField1 // jPasswordField1.setForeground(new Color(0, 0, 255)); jPasswordField1.setToolTipText("Enter your password"); jPasswordField1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jPasswordField1_actionPerformed(e); } }); // // jButton1 // jButton1.setBackground(new Color(204, 204, 204)); jButton1.setForeground(new Color(0, 0, 255)); jButton1.setText("Login"); jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jButton1_actionPerformed(e); } }); // // contentPane // contentPane.setLayout(null); contentPane.setBorder(BorderFactory.createEtchedBorder()); contentPane.setBackground(new Color(204, 204, 204)); addComponent(contentPane, jLabel1, 5,10,106,18); addComponent(contentPane, jLabel2, 5,47,97,18); addComponent(contentPane, jTextField1, 110,10,183,22); addComponent(contentPane, jPasswordField1, 110,45,183,22); addComponent(contentPane, jButton1, 150,75,83,28); // // login // this.setTitle("Login To Members Area"); this.setLocation(new Point(76, 182)); this.setSize(new Dimension(335, 141)); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setResizable(false); } /** Add Component Without a Layout Manager (Absolute Positioning) */ private void addComponent(Container container,Component c,int x,int y,int width,int height) { c.setBounds(x,y,width,height); container.add(c); } private void jTextField1_actionPerformed(ActionEvent e) { } private void jPasswordField1_actionPerformed(ActionEvent e) { } private void jButton1_actionPerformed(ActionEvent e) { System.out.println("\njButton1_actionPerformed(ActionEvent e) called."); String username = new String(jTextField1.getText()); String password = new String(jPasswordField1.getText()); if(username.equals("") || password.equals("")) // If password and username is empty Do this { jButton1.setEnabled(false); JLabel errorFields = new JLabel("You must enter a username and password to login."); JOptionPane.showMessageDialog(null,errorFields); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); this.setVisible(true); } else { JLabel optionLabel = new JLabel("You entered "+username+" as your username. Is this correct?"); int confirm =JOptionPane.showConfirmDialog(null,optionLabel); switch(confirm){ // Switch Case case JOptionPane.YES_OPTION: // Attempt to Login user jButton1.setEnabled(false); // Set button enable to false to prevent 2 login attempts break; case JOptionPane.NO_OPTION: // No Case.(Go back. Set text to 0) jButton1.setEnabled(false); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); break; case JOptionPane.CANCEL_OPTION: // Cancel Case.(Go back. Set text to 0) jButton1.setEnabled(false); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); break; } // End Switch Case } } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception ex) { System.out.println("Failed loading L&F: "); System.out.println(ex); } new login(); }; }

    Read the article

  • JSF composite component - weird behavior when trying to save state

    - by jc12
    I'm using Glassfish 3.2.2 and JSF 2.1.11 I'm trying to create a composite component that will take as parameters a string and a max number of characters and then will show only the max amount of characters, but it will have a "more" link next to it, that when clicked will expand the text to the full length and will then have a "less" link next to it to take it back to the max number of characters. I'm seeing some weird behavior, so I'm wondering if I'm doing something wrong. Here is my composite component definition: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:composite="http://java.sun.com/jsf/composite" xmlns:h="http://java.sun.com/jsf/html" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:p="http://primefaces.org/ui"> <composite:interface componentType="expandableTextComponent"> <composite:attribute name="name" required="true"/> <composite:attribute name="maxCharacters" required="true"/> <composite:attribute name="value" required="true"/> </composite:interface> <composite:implementation> <h:panelGroup id="#{cc.attrs.name}"> <h:outputText value="#{fn:substring(cc.attrs.value, 0, cc.attrs.maxCharacters)}" rendered="#{fn:length(cc.attrs.value) le cc.attrs.maxCharacters}"/> <h:outputText value="#{fn:substring(cc.attrs.value, 0, cc.attrs.maxCharacters)}" rendered="#{fn:length(cc.attrs.value) gt cc.attrs.maxCharacters and !cc.expanded}" style="margin-right: 5px;"/> <h:outputText value="#{cc.attrs.value}" rendered="#{fn:length(cc.attrs.value) gt cc.attrs.maxCharacters and cc.expanded}" style="margin-right: 5px;"/> <p:commandLink actionListener="#{cc.toggleExpanded()}" rendered="#{fn:length(cc.attrs.value) gt cc.attrs.maxCharacters}" update="#{cc.attrs.name}"> <h:outputText value="#{__commonButton.more}..." rendered="#{!cc.expanded}"/> <h:outputText value="#{__commonButton.less}" rendered="#{cc.expanded}"/> </p:commandLink> </h:panelGroup> </composite:implementation> </html> And here is the Java component: @FacesComponent("expandableTextComponent") public class ExpandableTextComponent extends UINamingContainer { boolean expanded; public boolean isExpanded() { return expanded; } public void toggleExpanded() { expanded = !expanded; } } Unfortunately expanded is always false every time the toggleExpanded function is called. However if I change the composite component to the following then it works. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:composite="http://java.sun.com/jsf/composite" xmlns:h="http://java.sun.com/jsf/html" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:p="http://primefaces.org/ui"> <composite:interface componentType="expandableTextComponent"> <composite:attribute name="name" required="true"/> <composite:attribute name="maxCharacters" required="true"/> <composite:attribute name="value" required="true"/> </composite:interface> <composite:implementation> <h:panelGroup id="#{cc.attrs.name}"> <h:outputText value="#{fn:substring(cc.attrs.value, 0, cc.attrs.maxCharacters)}" rendered="#{fn:length(cc.attrs.value) le cc.attrs.maxCharacters}"/> <h:outputText value="#{fn:substring(cc.attrs.value, 0, cc.attrs.maxCharacters)}" rendered="#{fn:length(cc.attrs.value) gt cc.attrs.maxCharacters and !cc.expanded}" style="margin-right: 5px;"/> <p:commandLink actionListener="#{cc.toggleExpanded()}" rendered="#{fn:length(cc.attrs.value) gt cc.attrs.maxCharacters and !cc.expanded}" update="#{cc.attrs.name}" process="@this"> <h:outputText value="#{__commonButton.more}..."/> </p:commandLink> <h:outputText value="#{cc.attrs.value}" rendered="#{fn:length(cc.attrs.value) gt cc.attrs.maxCharacters and cc.expanded}" style="margin-right: 5px;"/> <p:commandLink actionListener="#{cc.toggleExpanded()}" rendered="#{fn:length(cc.attrs.value) gt cc.attrs.maxCharacters and cc.expanded}" update="#{cc.attrs.name}" process="@this"> <h:outputText value="#{__commonButton.less}"/> </p:commandLink> </h:panelGroup> </composite:implementation> </html> If I place a breakpoint in the toggleExpanded function, it only gets called on the "more" link and not the "less" link. So the question is why doesn't it get called when I click on the "less" link? Shouldn't this code be equivalent to the code above? Is there a better way to save state in a component?

    Read the article

  • Problem creating calculations 'engine' in two class java calculator

    - by tokee
    i have hit a brick wall whilst attempting to create a two class java calculator but have been unsuccessful so far in getting it working. i have the code for an interface which works and displays ok but creating a seperate class 'CalcEngine' to do the actual calculations has proven to be beyond me. I'd appreciate it if someone could kick start things for me and create a class calcEngine which works with the interface class and allows input when from single button i.e. if one is pressed on the calc then 1 displays onscreen. please note i'm not asking someone to do the whole thing for me as i want to learn and i'm confident i can do the rest including addition subtraction etc. once i get over the obstacle of getting the two classes to communicate. any and all assistance would be very much appreciated. Please see the calcInterface class code below - import java.awt.*; import javax.swing.*; import javax.swing.border.*; import java.awt.event.*; /** *A Class that operates as the framework for a calculator. *No calculations are performed in this section */ public class CalcFrame implements ActionListener { private CalcEngine calc; private JFrame frame; private JTextField display; private JLabel status; /** * Constructor for objects of class GridLayoutExample */ public CalcFrame() { makeFrame(); //calc = engine; } /** * 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, "Group Project", "About Calculator Group Project", JOptionPane.INFORMATION_MESSAGE); } 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(); contentPane.add(display, BorderLayout.NORTH); //Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(4, 4)); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); contentPane.add(new JButton("1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("3")); contentPane.add(new JButton("4")); contentPane.add(new JButton("5")); contentPane.add(new JButton("6")); contentPane.add(new JButton("7")); contentPane.add(new JButton("8")); contentPane.add(new JButton("9")); 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(buttonPanel, BorderLayout.CENTER); //status = new JLabel(calc.getAuthor()); //contentPane.add(status, BorderLayout.SOUTH); 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); } /** * An interface action has been performed. * Find out what it was and handle it. * @param event The event that has occured. */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if(command.equals("0") || command.equals("1") || command.equals("2") || command.equals("3") || command.equals("4") || command.equals("5") || command.equals("6") || command.equals("7") || command.equals("8") || command.equals("9")) { int number = Integer.parseInt(command); calc.numberPressed(number); } else if(command.equals("+")) { calc.plus(); } else if(command.equals("-")) { calc.minus(); } else if(command.equals("=")) { calc.equals(); } else if(command.equals("C")) { calc.clear(); } else if(command.equals("?")) { } // else unknown command. redisplay(); } /** * Update the interface display to show the current value of the * calculator. */ private void redisplay() { display.setText("" + calc.getDisplayValue()); } /** * Toggle the info display in the calculator's status area between the * author and version information. */ }

    Read the article

  • creating a pre-menu level select screen

    - by Ephiras
    Hi I am working on creating a tower Defence java applet game and have come to a road block about implementing a title screen that i can select the level and difficulty of the rest of the game. my title screen class is called Menu. from this menu class i need to pass in many different variables into my Main class. i have used different classes before and know how to run them and such. but if both classes extend applet and each has its individual graphics method how can i run things from Main even though it was created in Menu. what i essentially want to do is run the Menu class withits action listeners and graphics until a Difficulty button has been selected, run the main class (which 100% works without having to have the Menu class) and pretty much terminate Menu so that i cannot go back to it, do not see its buttons or graphics menus. can i run one applet annd when i choose a button close that one and launch the other one? IF you would like to download the full project you can find it here, i had to comment out all the code that wasn't working my Menu class import java.awt.*; import java.awt.event.*; import java.applet.*; public class Menu extends Applet implements ActionListener{ Button bEasy,bMed,bHard; Main m; public void init(){ bEasy= new Button("Easy"); bEasy.setBounds(140,200,100,50); add(bEasy); bMed = new Button("Medium");bMed.setBounds(280,200,100,50); add(bMed); bHard= new Button("Hard");bHard.setBounds(420,200,100,50); add(bHard); setLayout(null); } public void actionPerformed(ActionEvent e){ Main m = new Main(20,10,3000,mapMed);//break; switch (e.getSource()){ case bEasy: Main m = new Main(6000,20,"levels/levelEasy.png");break;//enimies tower money world case bMed: Main m = new Main(4000,15,"levels/levelMed.png");break; case bHard: Main m = new Main(2000,10,"levels/levelEasy.png");break; default: break; } } public void paint(){ //m.draw(g) } } and here is my main class initialising code. import java.awt.*; import java.awt.event.*; import java.applet.*; import java.io.IOException; public class Main extends Applet implements Runnable, MouseListener, MouseMotionListener, ActionListener{ Button startButton, UpgRange, UpgDamage; //set up the buttons Color roadCol,startCol,finCol,selGrass,selRoad; //set up the colors Enemy e[][]; Tower t[]; Image towerpic,backpic,roadpic,levelPic; private Image i; private Graphics doubleG; //here is the world 0=grass 1=road 2=start 3=end int world[][],eStartX,eStartY; boolean drawMouse,gameEnd; static boolean start=false; static int gridLength=15; static int round=0; int Mx,My,timer=1500; static int sqrSize=31; int towers=0,towerSelected=-10; static int castleHealth=2000; String levelPath; //choose the level Easy Med or Hard int maxEnemy[] = {5,7,12,20,30,15,50,30,40,60};//number of enimies per round int maxTowers=15;//maximum number of towers allowed static int money =2000,damPrice=600,ranPrice=350,towerPrice=700; //money = the intial ammount of money you start of with //damPrice is the price to increase the damage of a tower //ranPrice is the price to increase the range of a tower public void main(int cH,int mT,int mo,int dP,int rP,int tP,String path,int[] mE)//constructor 1 castleHealth=cH; maxTowers=mT; money=mo; damPrice=dP; ranPrice=rP; towerPrice=tP; String levelPath=path; maxEnemy = mE; buildLevel(); } public void main(int cH,int mT,String path)//basic constructor castleHealth=cH; maxTowers=mT; String levelPath=path; maxEnemy = mE; buildLevel(); } public void init(){ setSize(sqrSize*15+200,sqrSize*15);//set the size of the screen roadCol = new Color(255,216,0);//set the colors for the different objects startCol = new Color(0,38,255); finCol = new Color(255,0,0); selRoad = new Color(242,204,155);//selColor is the color of something when your mouse hovers over it selGrass = new Color(0,190,0); roadpic = getImage(getDocumentBase(),"images/road.jpg"); towerpic = getImage(getDocumentBase(),"images/tower.png"); backpic = getImage(getDocumentBase(),"images/grass.jpg"); levelPic = getImage(getDocumentBase(),"images/level.jpg"); e= new Enemy[maxEnemy.length][];//activates all of the enimies for (int r=0;r<e.length;r++) e[r] = new Enemy[maxEnemy[r]]; t= new Tower[maxTowers]; for (int i=0;i<t.length;i++) t[i]= new Tower();//activates all the towers for (int i=0;i<e.length; i++)//sets all of the enimies starting co ordinates for (int j=0;j<e[i].length;j++) e[i][j] = new Enemy(eStartX,eStartY,world); initButtons();//initialise all the buttons addMouseMotionListener(this); addMouseListener(this); }

    Read the article

  • usage of setPropertyListener and setActionListener

    - by Vijay Mohan
    The incorrect usage could lead to hard-to-debug problems so better to understand the fundamentals behind it's working.setpropertyListener queues an event on the server side, so if for a command component you have a showPopup behavior/actionListner as well as setPropertyListener then fwk does the queuing correctly and raises further event on the component. While, the setactionListener simply raises an event on the server side instead of queueing it, so any further event on command component gets cancelled.Also, if you use an ActionListener and showPopup behavior together on a command component, then the order of their invocation is undetermined and also one of event gets cancelled on the component. So, either use only actionListner and do the popup invocation stuff progrmmatically in your bean or use the declarative stuff logically so that no clash of event happens.

    Read the article

  • How should I access frame buttons from a controller in an MVC approach?

    - by Loris
    I'm developing an italian card game using the mvc pattern. I have the class GameFrame that contains the view. The user's card are buttons (JButton objects). I have 3 controllers: GameController: to control the game in general. Contains the game loop. HumanPlayerController: to control the user input ComputerPlayerController: contains the AI of the computer PlayerController: is an interface with the makeTurn() method. It's implemented by HumanP.C. and ComputerP.C. HumanPlayerController implements ActionListener too. But what is the right way to access to the GameFrame buttons? I need it for understand which card was chosen. GameFrame and HumanPlayerController are in different packages. Should i make the JButtons public?

    Read the article

  • JLabel animation in JPanel

    - by Trizicus
    After scratching around I found that it's best to implement a custom image component by extending a JLabel. So far that has worked great as I can add multiple "images" (jlabels without the layout breaking. I just have a question that I hope someone can answer for me. I noticed that in order to animate JLabels across the screen I need to setlayout(null); and setbounds of the component and then to animate eventually setlocation(x,y);. Is this a best practice or a terrible way to animate a component? I plan on eventually making an animation class but I don't want to do so and end up having to chuck it. I have included relevant code for a quick review check. import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel { private Timer timer; private long startTime = 0; private int numFrames = 0; private float fps = 0.0f; private int x = 0; GraphicsPanel() { final Entity ent1 = new Entity(); ent1.setBounds(x, 0, ent1.getWidth(), ent1.getHeight()); add(ent1); //ESSENTIAL setLayout(null); //GAMELOOP timer = new Timer(30, new ActionListener() { public void actionPerformed(ActionEvent e) { getFPS(); incX(); ent1.setLocation(x, 0); repaint(); } }); timer.start(); } public void incX() { x++; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setClip(0, 0, getWidth(), getHeight()); g2.setColor(Color.BLACK); g2.drawString("FPS: " + fps, 1, 15); } public void getFPS() { ++numFrames; if (startTime == 0) { startTime = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long delta = (currentTime - startTime); if (delta > 1000) { fps = (numFrames * 1000) / delta; numFrames = 0; startTime = currentTime; } } } } Thank you!

    Read the article

  • Please Critique Code (Java, Java2D, javax.swing.Timer)

    - by Trizicus
    Learn by practice right? Please critique and suggest anything! Thanks :) import java.awt.EventQueue; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } JFrame frame; GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gp.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); gp.addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} }); frame.add(gp); } }); } } GraphicsPanel: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel { Test t; Timer test; GraphicsPanel() { t = new Test(); setLayout(new BorderLayout()); add(t, BorderLayout.CENTER); test = new Timer(17, new Gameloop(this)); test.start(); } class Gameloop implements ActionListener { GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { t.incX(); gp.repaint(); } catch (Exception ez) { } } } } Test: import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JComponent; public class Test extends JComponent { Toolkit tk; Image img; int x, y; Test() { tk = Toolkit.getDefaultToolkit(); img = tk.getImage(getClass().getResource("images.jpg")); this.setPreferredSize(new Dimension(15, 15)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.red); g2d.drawString("x: " + x, 350, 50); g2d.drawImage(img, x, 80, null); g2d.dispose(); } public void incX() { x++; } }

    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

  • Jpanel didn't show rest of it's component

    - by Ali Amiri
    I have jfarame with a button and a JPanel as I named panel, I want after I clicked the button add an inner JPanel to my panel. But this but there is a problem with this! because after adding second panel it didn't add any other panel. my code is: import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.GridLayout; import javax.swing.JTextField; public class DrawImages extends JFrame{ int i; public DrawImages() { JButton btnNewButton = new JButton("New button"); i = 0; getContentPane().add(btnNewButton, BorderLayout.SOUTH); setMinimumSize(new Dimension(1000,150)); final JPanel panel = new JPanel(); panel.setSize(995, 145); getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(null); final JLabel lblNewLabel = new JLabel("New label"); lblNewLabel.setBounds(0, 0, 46, 14); panel.add(lblNewLabel); btnNewButton.addActionListener(new ActionListener() public void actionPerformed(ActionEvent paramActionEvent) { JPanel panel_1 = new JPanel(); //getContentPane().add(panel_1, BorderLayout.NORTH); panel_1.setLayout(null); JLabel imagelable = new JLabel(new ImageIcon("c:\\good.jpg")); imagelable.setBounds(70, 5, 105, 65); panel_1.add(imagelable); JLabel lblNewLabel_4 = new JLabel("Up Label"); lblNewLabel_4.setBounds(5, 5, 65, 35); panel_1.add(lblNewLabel_4); JLabel lblNewLabel_2 = new JLabel("Down Label"); lblNewLabel_2.setBounds(5, 25, 65, 65); panel_1.add(lblNewLabel_2); lblNewLabel.setText(""+i); panel_1.setBounds(5+170*i, 5, 170+170*i, 70); panel.add(panel_1); i++; } }); panel.setMinimumSize(new Dimension(995,150)); } public static void main(String[]args) { DrawImages drawImages = new DrawImages(); drawImages.setVisible(true); } }

    Read the article

  • do I need to close an audio Clip?

    - by Michael
    have an application that processes real-time data and is supposed to beep when a certain event occurs. The triggering event can occur multiple times per second, and if the beep is already playing when another event triggers the code is just supposed to ignore it (as opposed to interrupting the current beep and starting a new one). Here is the basic code: Clip clickClip public void prepareProcess() { super.prepareProcess(); clickClip = null; try { clipFile = new File("C:/WINDOWS/Media/CHIMES.wav"); ais = AudioSystem.getAudioInputStream(clipFile); clickClip = AudioSystem.getClip(); clickClip.open(ais); fileIsLoaded = true; } catch (Exception ex) { clickClip = null; fileIsLoaded = false; } } public void playSound() { if (fileIsLoaded) { if ((clickClip==null) || (!clickClip.isRunning())) { try { clickClip.setFramePosition(0); clickClip.start(); } catch (Exception ex) { System.out.println("Cannot play click noise"); ex.printStackTrace(); } } } The prepareProcess method gets run once in the beginning, and the playSound method is called every time a triggering event occurs. My question is: do I need to close the clickClip object? I know I could add an actionListener to monitor for a Stop event, but since the event occurs so frequently I'm worried the extra processing is going to slow down the real-time data collection. The code seems to run fine, but my worry is memory leaks. The code above is based on an example I found while searching the net, but the example used an actionListener to close the Clip specifically "to eliminate memory leaks that would occur when the stop method wasn't implemented". My program is intended to run for hours so any memory leaks I have will cause problems. I'll be honest: I have no idea how to verify whether or not I've got a problem. I'm using Netbeans, and running the memory profiler just gave me a huge list of things that I don't know how to read. This is supposed to be the simple part of the program, and I'm spending hours on it. Any help would be greatly appreciated! Michael

    Read the article

  • login form with java/sqlite

    - by tuxou
    hi I would like to create a login form for my application with the possibility to add or remove users for an sqlite database, i have created the table users(nam, pass) but i can't unclud it in my login form, it someone could help me this is my login code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class login extends JFrame{ // Variables declaration private JLabel jLabel1; private JLabel jLabel2; private JTextField jTextField1; private JPasswordField jPasswordField1; private JButton jButton1; private JPanel contentPane; // End of variables declaration public login(){ super(); create(); this.setVisible(true); } private void create(){ jLabel1 = new JLabel(); jLabel2 = new JLabel(); jTextField1 = new JTextField(); jPasswordField1 = new JPasswordField(); jButton1 = new JButton(); contentPane = (JPanel)this.getContentPane(); // // jLabel1 // jLabel1.setHorizontalAlignment(SwingConstants.LEFT); jLabel1.setForeground(new Color(0, 0, 255)); jLabel1.setText("username:"); // // jLabel2 // jLabel2.setHorizontalAlignment(SwingConstants.LEFT); jLabel2.setForeground(new Color(0, 0, 255)); jLabel2.setText("password:"); // // jTextField1 // jTextField1.setForeground(new Color(0, 0, 255)); jTextField1.setSelectedTextColor(new Color(0, 0, 255)); jTextField1.setToolTipText("Enter your username"); jTextField1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ jTextField1_actionPerformed(e); } }); // // jPasswordField1 // jPasswordField1.setForeground(new Color(0, 0, 255)); jPasswordField1.setToolTipText("Enter your password"); jPasswordField1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ jPasswordField1_actionPerformed(e); } }); // // jButton1 // jButton1.setBackground(new Color(204, 204, 204)); jButton1.setForeground(new Color(0, 0, 255)); jButton1.setText("Login"); jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ jButton1_actionPerformed(e); } }); // // contentPane // contentPane.setLayout(null); contentPane.setBorder(BorderFactory.createEtchedBorder()); contentPane.setBackground(new Color(204, 204, 204)); addComponent(contentPane, jLabel1, 5,10,106,18); addComponent(contentPane, jLabel2, 5,47,97,18); addComponent(contentPane, jTextField1, 110,10,183,22); addComponent(contentPane, jPasswordField1, 110,45,183,22); addComponent(contentPane, jButton1, 150,75,83,28); // // login // this.setTitle("Login To Members Area"); this.setLocation(new Point(76, 182)); this.setSize(new Dimension(335, 141)); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setResizable(false); } /** Add Component Without a Layout Manager (Absolute Positioning) */ private void addComponent(Container container,Component c,int x,int y,int width,int height){ c.setBounds(x,y,width,height); container.add(c); } private void jTextField1_actionPerformed(ActionEvent e){ } private void jPasswordField1_actionPerformed(ActionEvent e){ } private void jButton1_actionPerformed(ActionEvent e){ System.out.println("\njButton1_actionPerformed(ActionEvent e) called."); String username = new String(jTextField1.getText()); String password = new String(jPasswordField1.getText()); if(username.equals("") || password.equals("")){// If password and username is empty > Do this >>> jButton1.setEnabled(false); JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>You must enter a username and password to login.</FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); this.setVisible(true); } else{ JLabel optionLabel = new JLabel("<HTML><FONT COLOR = Blue>You entered</FONT><FONT COLOR = RED> <B>"+username+"</B></FONT> <FONT COLOR = Blue>as your username.<BR> Is this correct?</FONT></HTML>"); int confirm =JOptionPane.showConfirmDialog(null,optionLabel); switch(confirm){ // Switch > Case case JOptionPane.YES_OPTION: // Attempt to Login user jButton1.setEnabled(false); // Set button enable to false to prevent 2 login attempts break; case JOptionPane.NO_OPTION: // No Case.(Go back. Set text to 0) jButton1.setEnabled(false); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); break; case JOptionPane.CANCEL_OPTION: // Cancel Case.(Go back. Set text to 0) jButton1.setEnabled(false); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); break; } // End Switch > Case } } public static void main(String[] args){ JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); try{ UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); }catch (Exception ex){ System.out.println("Failed loading L&F: "); System.out.println(ex); } new login(); }; } my connectDb class : public class Connectdb { private static Connection connect; private static String url ="jdbc:sqlite:data.db"; private static Statement st; private static ResultSet rs; /** * Constructeur privé d'une connection à la bd unique */ private ConnectionBd(){ try { Class.forName("org.sqlite.JDBC"); connect = DriverManager.getConnection(url); } catch (ClassNotFoundException ex) { Logger.getLogger(ex.getName()).log(Level.SEVERE, null, ex); } catch (SQLException e) { System.exit(e.getErrorCode()); } } public static Connection getInstance(){ if(connect == null){ new Connectdb(); }else{ } return connect; } /** * @return */ public static void initTable(String query){ try { Statement state = getInstance().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet res = state.executeQuery(query); res.close(); state.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "ERROR ! ", JOptionPane.ERROR_MESSAGE); } }

    Read the article

  • using Inheritence with GUI (graphical user interfaces) in Java

    - by maya
    hi everyone, I work on inheritence with GUI (graphical user interfaces) let me explain for example I made super class which is vehicle and the subclass is car, so the code to make inheritence will be public class Car extends Vehicle then I want to build the class Car as JFrame like public class Car JFrame implements ActionListener { so the problem is that I couldn't put both codes in the same class, and I need to do that. anyone help me. thanks in advance I wish that the question would be clear

    Read the article

  • Read / write program in java using JChooser

    - by Casper Marcussen
    Hello everyone Didn't want to bother people in here, but since i am under a time pressure, i am desperate to get help. My questions is how to link the file choosen from a JChooser to a file, and how to converte it to stringm being able to display and edit it in a TextArea. i hav ethe GUI set up using swing, but the link between actionListener and the Jchooser is not complete Any help would be much appreciated code: http://pastebin.com/p3fb17Wi

    Read the article

  • lwuit container

    - by user267674
    i have added a container named btnBar with boxlayout(x-axis) on a form. the container has 4 buttons of custom class MyButton that extends from Button itself.when i add actionlistener to one of the buttons in the container it gets invoked for each n every button.Even the actionevent.getsource.gettext method returns the same value irrespective of the focus.i hav added the buttons thru an array and m trying to use is smthng lyk dis....btns[0].addActionListener(......)......where m i going wrong...plz lemme kw..

    Read the article

  • A "Trig" Calculating Class

    - by Clinton Scott
    I have been trying to create a gui that calculates trigonometric functions based off of the user's input. I have had success in the GUI part, but my class that I wrote to hold information using inheritance seems to be messed up, because when I run it gives an error saying: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constructor ArcTrigCalcCon in class TrigCalc.ArcTrigCalcCon cannot be applied to given types; required: double,double,double,double,double,double found: java.lang.Double,java.lang.Double,java.lang.Double reason: actual and formal argument lists differ in length at TrigCalc.TrigCalcGUI.(TrigCalcGUI.java:31) at TrigCalc.TrigCalcGUI.main(TrigCalcGUI.java:87) Java Result: 1 and says it is the object causing the problem. Below Will be my code. First I will put up my inheritance class with cosecant secant and cotangent and then my original class with the original 3 trig functions: { public ArcTrigCalcCon(double s, double cs, double t, double csc, double sc, double ct) { // Inherit from the Trig Calc class super(s, cs, t); cosecant = 1/s; secant = 1/cs; cotangent = 1/t; } public void setCsc(double csc) { cosecant = csc; } public void setSec(double sc) { secant = sc; } public void setCot(double ct) { cotangent = ct; } } Here is the first Trigonometric class: public class TrigCalcCon { public double sine; public double cosine; public double tangent; public TrigCalcCon(double s, double cs, double t) { sine = s; cosine = cs; tangent = t; } public void setSin(double s) { sine = s; } public void setCos(double cs) { cosine = cs; } public void setTan(double t) { tangent = t; } public void set(double s, double cs, double t) { sine = s; cosine = cs; tangent = t; } public double getSin() { return Math.sin(sine); } public double getCos() { return Math.cos(cosine); } public double getTan() { return Math.tan(tangent); } } and here is the demo class to run the gui: public class TrigCalcGUI extends JFrame implements ActionListener { // Instance Variables private String input; private Double s, cs, t, csc, sc, ct; private JPanel mainPanel, sinPanel, cosPanel, tanPanel, cscPanel, secPanel, cotPanel, buttonPanel, inputPanel, displayPanel; // Panel Display private JLabel sinLabel, cosLabel, tanLabel, secLabel, cscLabel, cotLabel, inputLabel; private JTextField sinTF, cosTF, tanTF, secTF, cscTF, cotTF, inputTF; //Text Fields for sin, cos, and tan, and inverse private JButton calcButton, clearButton; // Calculate and Exit Buttons // Object ArcTrigCalcCon trC = new ArcTrigCalcCon(s, cs, t); public TrigCalcGUI() { // title bar text. super("Trig Calculator"); // Corner exit button action. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create main panel to add each panel to mainPanel = new JPanel(); mainPanel.setLayout(new GridLayout(3,2)); displayPanel = new JPanel(); displayPanel.setLayout(new GridLayout(3,2)); // Assign Panel to each variable inputPanel = new JPanel(); sinPanel = new JPanel(); cosPanel = new JPanel(); tanPanel = new JPanel(); cscPanel = new JPanel(); secPanel = new JPanel(); cotPanel = new JPanel(); buttonPanel = new JPanel(); // Call each constructor buildInputPanel(); buildSinCosTanPanels(); buildCscSecCotPanels(); buildButtonPanel(); // Add each panel to content pane displayPanel.add(sinPanel); displayPanel.add(cscPanel); displayPanel.add(cosPanel); displayPanel.add(secPanel); displayPanel.add(tanPanel); displayPanel.add(cotPanel); // Add three content panes to GUI mainPanel.add(inputPanel, BorderLayout.NORTH); mainPanel.add(displayPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); //add mainPanel this.add(mainPanel); // size of window to content this.pack(); // display window setVisible(true); } public static void main(String[] args) { new TrigCalcGUI(); } private void buildInputPanel() { inputLabel = new JLabel("Enter a Value: "); inputTF = new JTextField(5); inputPanel.add(inputLabel); inputPanel.add(inputTF); } // Building Constructor for sinPanel cosPanel, and tanPanel private void buildSinCosTanPanels() { // Set layout and border for sinPanel sinPanel.setLayout(new GridLayout(2,2)); sinPanel.setBorder(BorderFactory.createTitledBorder("Sine")); // sinTF = new JTextField(5); sinTF.setEditable(false); sinPanel.add(sinTF); // Set layout and border for cosPanel cosPanel.setLayout(new GridLayout(2,2)); cosPanel.setBorder(BorderFactory.createTitledBorder("Cosine")); cosTF = new JTextField(5); cosTF.setEditable(false); cosPanel.add(cosTF); // Set layout and border for tanPanel tanPanel.setLayout(new GridLayout(2,2)); tanPanel.setBorder(BorderFactory.createTitledBorder("Tangent")); tanTF = new JTextField(5); tanTF.setEditable(false); tanPanel.add(tanTF); } // Building Constructor for cscPanel secPanel, and cotPanel private void buildCscSecCotPanels() { // Set layout and border for cscPanel cscPanel.setLayout(new GridLayout(2,2)); cscPanel.setBorder(BorderFactory.createTitledBorder("Cosecant")); // cscTF = new JTextField(5); cscTF.setEditable(false); cscPanel.add(cscTF); // Set layout and border for secPanel secPanel.setLayout(new GridLayout(2,2)); secPanel.setBorder(BorderFactory.createTitledBorder("Secant")); secTF = new JTextField(5); secTF.setEditable(false); secPanel.add(secTF); // Set layout and border for cotPanel cotPanel.setLayout(new GridLayout(2,2)); cotPanel.setBorder(BorderFactory.createTitledBorder("Cotangent")); cotTF = new JTextField(5); cotTF.setEditable(false); cotPanel.add(cotTF); } private void buildButtonPanel() { // Create buttons and add events calcButton = new JButton("Calculate"); calcButton.addActionListener(new CalcButtonListener()); clearButton = new JButton("Clear"); clearButton.addActionListener(new ClearButtonListener()); buttonPanel.add(calcButton); buttonPanel.add(clearButton); } @Override public void actionPerformed(ActionEvent e) { } private class CalcButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae) { // Declare boolean variable boolean incorrect = true; // Set input variable to input text field text input = inputTF.getText(); ImageIcon newIcon; ImageIcon frowny = new ImageIcon(TrigCalcGUI.class.getResource("/Sad_Face.png")); Image gm = frowny.getImage(); Image newFrowny = gm.getScaledInstance(100, 100, java.awt.Image.SCALE_FAST); newIcon = new ImageIcon(newFrowny); // If boolean is true, throw exception if(incorrect) { try{Double.parseDouble(input); incorrect = false;} catch(NumberFormatException nfe) { String s = "Invalid Input " + "/n Input Must Be a Numerical value." + "/nPlease Press Ok and Try Again"; JOptionPane.showMessageDialog(null, s, "Invalid", JOptionPane.ERROR_MESSAGE, newIcon); inputTF.setText(""); inputTF.requestFocus(); } } // If boolean is not true, proceed with output if (incorrect != true) { /* Set each text field's output to the String double value * of inputTF */ sinTF.setText(input); cosTF.setText(input); tanTF.setText(input); cscTF.setText(input); secTF.setText(input); cotTF.setText(input); } } } /** * Private inner class that handles the event when * the user clicks the Exit button. */ private class ClearButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae) { // Clear field sinTF.setText(""); cosTF.setText(""); tanTF.setText(""); cscTF.setText(""); secTF.setText(""); cotTF.setText(""); // Clear textfield and set cursor focus to field inputTF.setText(""); inputTF.requestFocus(); } } }

    Read the article

  • Unable to resize a button using java.awt

    - by asm_debuger
    this is my code: import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Maapp extends Applet implements ActionListener { private int flag=0; Panel p1=new Panel(); Panel p2=new Panel(); Button[] arr=new Button[12]; TextField textf=new TextField("",25); public void init() { this.setLayout(new BorderLayout()); this.p2.setBackground(Color.DARK_GRAY); this.p2.setLayout(new GridLayout(2,30)); textf.setBackground(Color.BLACK); textf.setForeground(Color.YELLOW); this.p1.setLayout(new GridLayout(4,10)); p2.add(textf); for(int i=0; i<10 ;i++) { arr[i]=new Button(""+i); arr[i].setForeground(Color.WHITE); arr[i].setBackground(Color.DARK_GRAY); p1.add(arr[i]); this.arr[i].addActionListener(this); } arr[10]=new Button("="); p1.add(arr[10]); arr[10].setPreferredSize(new Dimension(20,40)); this.arr[10].addActionListener(this); this.add(p2,BorderLayout.NORTH); this.add(p1,BorderLayout.CENTER); } public void actionPerformed(ActionEvent arg0) { for(int i=0;i<10;i++) { if(arg0.getSource()==arr[i]) { this.textf.setText(this.textf.getText()+i); } } } } i`m want to resize 1 of the buttons i tried to write: arr[10].setPreferredSize(new Dimension(20,40)); ist do not works i tried to write : arr[10].resize(10,20); ist do not works so how can i resize button arr[10]?

    Read the article

  • JProgressBar.stringPainted(true); is not working

    - by Mirza Ghalib
    This is a part of my java code, in this code I have written that when I click the button the value of JProgressBar should becomes 0 and stringPainted(); becomes true, but "string painted" is not visible when I click the button, please help. import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JProgressBar; public class R implements ActionListener { static int y; CustomProgressBar b = new CustomProgressBar(); public static void main(String arg[]) throws Exception { new R(); } public R() throws Exception { JFrame f = new JFrame(); JButton btn = new JButton("Click"); f.setExtendedState(JFrame.MAXIMIZED_BOTH); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setUndecorated(true); f.setLayout(new FlowLayout()); btn.addActionListener(this); f.add(b); f.add(btn); f.setVisible(true); } class CustomProgressBar extends JProgressBar{ private static final long serialVersionUID = 1L; private boolean isStringToBePainted = false; public CustomProgressBar() { super(JProgressBar.VERTICAL,0,100); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if(isStringToBePainted ) { Dimension size = CustomProgressBar.this.getSize(); if( CustomProgressBar.this.getPercentComplete()<0.9 ) R.y = (int)( size.height - size.height * CustomProgressBar.this.getPercentComplete() ); String text = getString(); g.setColor(Color.BLACK ); g.drawString(text, 0, R.y); } } @Override public void setStringPainted(boolean b) { isStringToBePainted=b; } } @Override public void actionPerformed(ActionEvent e) { b.setValue(0); b.setStringPainted(true); } }

    Read the article

  • Swing: does DefaultBoundedRangeModel coalesce multiple events?

    - by Jason S
    I have a JProgressBar displaying a BoundedRangeModel which is extremely fine grained and I was concerned that updating it too often would slow down my computer. So I wrote a quick test program (see below) which has a 10Hz timer but each timer tick makes 10,000 calls to microtick() which in turn increments the BoundedRangeModel. Yet it seems to play nicely with a JProgressBar; my CPU is not working hard to run the program. How does JProgressBar or DefaultBoundedRangeModel do this? They seem to be smart about how much work it does to update the JProgressBar, so that as a user I don't have to worry about updating the BoundedRangeModel's value. package com.example.test.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoundedRangeModel; import javax.swing.DefaultBoundedRangeModel; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.Timer; public class BoundedRangeModelTest1 extends JFrame { final private BoundedRangeModel brm = new DefaultBoundedRangeModel(); final private Timer timer = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { tick(); } }); public BoundedRangeModelTest1(String title) { super(title); JPanel p = new JPanel(); p.add(new JProgressBar(this.brm)); getContentPane().add(p); this.brm.setMaximum(1000000); this.brm.setMinimum(0); this.brm.setValue(0); } protected void tick() { for (int i = 0; i < 10000; ++i) { microtick(); } } private void microtick() { this.brm.setValue(this.brm.getValue()+1); } public void start() { this.timer.start(); } static public void main(String[] args) { BoundedRangeModelTest1 f = new BoundedRangeModelTest1("BoundedRangeModelTest1"); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(EXIT_ON_CLOSE); f.start(); } }

    Read the article

  • How can I update a Jtextarea once? (mysql side-?)

    - by user1294196
    Ok what I've been trying to do is figure out how to make it so when I press the search button on my program the code that is currently just being printed to the console will print to the text area I have. I can't figure out how to do this and I've searched google and still found no answer. And while I'm at it if anyone could help me figure out how to send this same line of information to a mysql database that would help greatly. package GTE; import java.awt.EventQueue; public class GTE { private JFrame frmGte; public String hashq = "..."; public String twtresults; public int refresh = 1; public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { GTE window = new GTE(); window.frmGte.setVisible(true); } catch (Exception e) {} } }); } /** * Create the application. * @throws IOException * @throws FontFormatException */ public GTE(){ try { initialize(); } catch (FontFormatException e) {} catch (IOException e) {} } /** * Initialize the contents of the frame. * @throws IOException * @throws FontFormatException */ private void initialize() throws FontFormatException, IOException { frmGte = new JFrame(); frmGte.setResizable(false); frmGte.setTitle("GTE"); frmGte.setBounds(100, 100, 450, 390); frmGte.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[]{434, 0}; gridBagLayout.rowHeights = new int[]{21, 0, 0, 0, 0, 0, 0, 0, 0}; gridBagLayout.columnWeights = new double[]{0.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; frmGte.getContentPane().setLayout(gridBagLayout); JLabel GTETitle = new JLabel("Personal Tweet Extractor"); InputStream is = this.getClass().getResourceAsStream("ultraviolentbb_reg.ttf"); Font GTEFont = Font.createFont(Font.TRUETYPE_FONT,is); Font f = GTEFont.deriveFont(24f); GTETitle.setFont(f); GTETitle.setHorizontalAlignment(SwingConstants.CENTER); GridBagConstraints gbc_GTETitle = new GridBagConstraints(); gbc_GTETitle.insets = new Insets(0, 0, 5, 0); gbc_GTETitle.anchor = GridBagConstraints.NORTH; gbc_GTETitle.fill = GridBagConstraints.HORIZONTAL; gbc_GTETitle.gridx = 0; gbc_GTETitle.gridy = 0; frmGte.getContentPane().add(GTETitle, gbc_GTETitle); Label label_2 = new Label("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); GridBagConstraints gbc_label_2 = new GridBagConstraints(); gbc_label_2.insets = new Insets(0, 0, 5, 0); gbc_label_2.gridx = 0; gbc_label_2.gridy = 1; frmGte.getContentPane().add(label_2, gbc_label_2); JLabel SearchTweets = new JLabel("Search For Tweets With" + hashq + ":"); GridBagConstraints gbc_SearchTweets = new GridBagConstraints(); gbc_SearchTweets.insets = new Insets(0, 0, 5, 0); gbc_SearchTweets.gridx = 0; gbc_SearchTweets.gridy = 2; frmGte.getContentPane().add(SearchTweets, gbc_SearchTweets); JLabel label = new JLabel("#"); GridBagConstraints gbc_label = new GridBagConstraints(); gbc_label.insets = new Insets(0, 0, 5, 0); gbc_label.gridx = 0; gbc_label.gridy = 3; frmGte.getContentPane().add(label, gbc_label); JButton Search = new JButton("Start Search"); Search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { TS(hashq); GTE.this.refresh = 0; try { nulll dialog = new nulll(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) {} } public void TS(String hashtag){ Twitter twitter = new TwitterFactory().getInstance(); try { System.out.println(hashtag); QueryResult result = twitter.search(new Query("#" + hashtag)); List<Tweet> tweets = result.getTweets(); for (Tweet tweet : tweets) { System.out.println("@" + tweet.getFromUser() + " : " + tweet.getText()); GTE.this.twtresults = ("@" + tweet.getFromUser() + " : " + tweet.getText()); } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } } }); TextField textField = new TextField(); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { GTE.this.hashq = evt.getActionCommand(); } }); GridBagConstraints gbc_textField = new GridBagConstraints(); gbc_textField.ipadx = 99; gbc_textField.insets = new Insets(0, 0, 5, 0); gbc_textField.gridx = 0; gbc_textField.gridy = 4; frmGte.getContentPane().add(textField, gbc_textField); GridBagConstraints gbc_Search = new GridBagConstraints(); gbc_Search.insets = new Insets(0, 0, 5, 0); gbc_Search.gridx = 0; gbc_Search.gridy = 5; frmGte.getContentPane().add(Search, gbc_Search); Label label_1 = new Label("Search Results For Tweets With"); GridBagConstraints gbc_label_1 = new GridBagConstraints(); gbc_label_1.insets = new Insets(0, 0, 5, 0); gbc_label_1.gridx = 0; gbc_label_1.gridy = 6; frmGte.getContentPane().add(label_1, gbc_label_1); TextArea textArea = new TextArea(); textArea.setText(twtresults); textArea.setEditable(false); GridBagConstraints gbc_textArea = new GridBagConstraints(); gbc_textArea.gridx = 0; gbc_textArea.gridy = 7; frmGte.getContentPane().add(textArea, gbc_textArea); JMenuBar menuBar = new JMenuBar(); frmGte.setJMenuBar(menuBar); JMenu Filemenu = new JMenu("File"); menuBar.add(Filemenu); JMenuItem Exititem = new JMenuItem("Exit"); Exititem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.exit(0); } }); Filemenu.add(Exititem); JMenu Helpmenu = new JMenu("Help"); menuBar.add(Helpmenu); JMenuItem Aboutitem = new JMenuItem("About"); Helpmenu.add(Aboutitem); } }

    Read the article

  • form inside tabview doesn't work

    - by user3536737
    i am working with jsf and primefaces , and here is what 've tried well i want to creat a tabview that get data from an arraylist in my bean i get for exemple 4 tabs , and inside each one i've created a hidden panel where i have a form with 2 input text to update informations , do i display the panel when i click on the second button Update , after that my panel is not hidden anymore , and i set the new values and click on the second button to update the informations , the problem is that the updating and the execution is working only for the first tab , it means when i try to update the new informations it works for the first one and for the other tabs it doesn't here is the code <p:tab title="#{rr.nom_ressource}"> <h:panelGrid> <h:graphicImage value="Ressources/images/emp.jpg" style="vertical-align:middle" /> <span style="font-size:15px; width:170px; display:inline-block;"> Nom : #{rr.nom_ressource} Type: #{rr.type_ressource} Specification: #{rr.experience} </span> <h:commandButton image="Ressources/images/delete.jpg" actionListener="#{SelectBean.act}" update=":form" style="vertical-align:middle" > Update </h:commandButton> <h:commandButton update=":outPanel" actionListener="#{SelectBean.mod1()}" image="Ressources/images/update.png" style="vertical-align:middle" > Modifier </h:commandButton> <h:form id="form111"> <p:growl id="growl" showDetail="true" sticky="true" /> <p:panel rendered ="#{SelectBean.bol}" closable="true" toggleable="true" id="outPanel" styleClass="outPanel" widgetVar="outpanel"> <h:outputLabel value="Nom " /> <h:inputText value="#{SelectBean.nom}" /> <br/> <h:outputLabel value="Experience " /> <h:inputText value="#{SelectBean.exp}" /> <br/> <h:commandButton value="Update" action="#{SelectBean.done}"/> </p:panel> </h:form> </h:panelGrid> </p:tab> for my managedbean the code is correct i think the problem is here

    Read the article

  • p:commandButton update doesn't work in ui:include

    - by Roberto de Santis
    Hi guys. I want to update a part of a page by PPR. This is the part of page that i want to update: <h:panelGroup id="aggiungiAuto" rendered="#{!autoBean.operazioneOk}"> <ui:include src="../component/aggiungi_auto.xhtml"/> </h:panelGroup> While this is the commandButton present in aggiungi_auto.xhtml <p:commandButton value="Submit" update="growl aggiungiAuto aggiungiFoto" actionListener="#{autoBean.insert}"/> Any Idea?

    Read the article

  • activating the class need help.... :)

    - by asm_debuger
    this is my code... i dont anderstend way the class dont work... import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.GridLayout; import java.awt.Panel; public class Caldesinger { public Panel p1=new Panel(); public Button[] arr=new Button[20]; public String[] name = {"9","8","7","6","5","4","3","2","1","0","+","-","*","/",".","cos","sin","=","pow"}; public Caldesinger() { for (int i = 0; i < arr.length; i++) { this.arr[i]=new Button(""+name[i]); } } public Panel getP1() { return p1; } public void setP1(Panel p1) { this.p1 = p1; } public Button[] getArr() { return arr; } public void setArr(Button[] arr) { this.arr = arr; } public Object c() { this.p1.setLayout(new GridLayout(4,15)); for (int i = 0; i < arr.length; i++) { arr[i].setBackground(Color.LIGHT_GRAY); arr[i].setForeground(Color.orange); p1.add(arr[i]); } this.p1.setLayout(new GridLayout(4,15)); return this; } } the class desinge the applet this is the main: import java.applet.Applet; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Mainapp extends Applet implements ActionListener { Caldesinger desinge=new Caldesinger (); public void init() { this.setLayout(new BorderLayout()); this.desinge.c(); } public void ActionPerformed(ActionEvent arg0) { for (int i = 0; i <20; i++) { if(arg0.getSource()== this.desinge.arr[i]); } } } way the method c does not work? the method desinge the applet

    Read the article

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