Search Results

Search found 428 results on 18 pages for 'jpanel'.

Page 15/18 | < Previous Page | 11 12 13 14 15 16 17 18  | Next Page >

  • Java MVC - How to divide a done text game into MVC?

    - by Zopyrus
    Been sitting here for hours now trying to figure this out, so a bit sympathy for this large question. :) The Goal: I simply want to divide my done code into MVC (Model View Controller) parts. I have the game logics done and text based - the code works fine. The Problem: Well, I want to implement this code into MVC, but where do explain for the MODEL that it should use text-based? Because the VIEW is only for the layout (graphically) correct? I am having a REALLY hard time figuring out where to begin at all. Any pointers would be so nice! Here is my game logics code: import mind.*; import javax.swing.*; import java.util.*; import java.lang.*; import java.awt.*; public class Drive { String[] mellan; boolean gameEnd, checkempty, checkempty2, enemy, enemy2; String gr,rd,tom; int digits; public Drive() { // Gamepieces in textform gr="G"; rd="R"; tom=" "; mellan = new String[7]; String[] begin = {gr,gr,gr,tom,rd,rd,rd}; String[] end = {rd,rd,rd,tom,gr,gr,gr}; //input Scanner in = new Scanner(System.in); mellan=begin; gameEnd=false; while (gameEnd == false) { for(int i=0; i<mellan.length; i++) { System.out.print(mellan[i]); } System.out.print(" Choose 0-6: "); digits = in.nextInt(); move(); checkWin(); } } void move() { //BOOLEAN for gameruls!!! checkempty = digits<6 && mellan[digits+1]==tom; checkempty2 = digits>0 && mellan[digits-1]==tom; enemy = (mellan[digits]==gr && mellan[digits+1]==rd && mellan[digits+2]==tom); enemy2 = (mellan[digits]==rd && mellan[digits-1]==gr && mellan[digits-2]==tom); if(checkempty) { mellan[digits+1]=mellan[digits]; mellan[digits]=tom; } else if (checkempty2) { mellan[digits-1]=mellan[digits]; mellan[digits]=tom; } else if (enemy) { mellan[digits+2]=mellan[digits]; mellan[digits]=tom; } else if (enemy2) { mellan[digits-2]=mellan[digits]; mellan[digits]=tom; } } void checkWin() { String[] end = {rd,rd,rd,tom,gr,gr,gr}; for (int i=0; i<mellan.length; i++){ } if (Arrays.equals(mellan,end)) { for (int j=0; j<mellan.length; j++) { System.out.print(mellan[j]); } displayWin(); } } void displayWin() { gameEnd = true; System.out.println("\nNicely Done!"); return; } // Kör Drive! public static void main(String args[]) { new Drive(); } } Here is how I defined my DriveView thus far: (just trying to make one button to work) import mind.*; import javax.swing.*; import java.util.*; import java.lang.*; import java.awt.*; import java.awt.event.*; public class DriveView extends JFrame { JButton ruta1 = new JButton("Green"); JButton ruta2 = new JButton("Green"); JButton rutatom = new JButton(""); JButton ruta6 = new JButton("Red"); private DriveModel m_model; public DriveView(DriveModel model) { m_model = model; //Layout for View JPanel myPanel = new JPanel(); myPanel.setLayout(new FlowLayout()); myPanel.add(ruta1); myPanel.add(ruta2); myPanel.add(rutatom); myPanel.add(ruta6); this.setContentPane(myPanel); this.pack(); this.setTitle("Drive"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void addMouseListener(ActionListener mol) { ruta2.addActionListener(mol); } } And DriveController which gives me error at compile import mind.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.lang.*; public class DriveController { private DriveModel m_model; private DriveView m_view; public DriveController(DriveModel model, DriveView view) { m_model = model; m_view = view; view.addMouseListener(new MouseListener()); } class MouseListener implements ActionListener { public void actionPerformed(ActionEvent e) { String mening; mening = e.getActionCommand(); if (mening.equals("Green")) { setForeground(Color.red); } } } }

    Read the article

  • How should objects be in a Java game.

    - by Gabriel A. Zorrilla
    EDIT: i just deleted the entire post and reformulated the question to be more generic. I want to do a simple strategy game: map, units. Map: one class. Units: another class, self drawn. Simple questions: How does an unit should redraw itself on the map. A unit should be a JPanel or similar Swing component (just to be able to manage them as an entity with its own mousehandlers) or can be another thing, without neglecting the fact that it should be an autonomous object with its own action handlers and fields. Is this map-units model correct of a simple game that would help me to learn in a fun way Java and OOP fundamentals. Thats it!

    Read the article

  • JAVA: How to use paint() method to update the previously drawn object?

    - by GamDroid
    How to use paint() such that when repaint() is called the previously drawn object should not get deleted when drawing the new object. That is the drawing area must get UPDATED only and not REDRAWN. In my code when one of many button is clicked, some aplhabet get displayed. I want to have functionality such that when other buttons are clicked the previously drawn alhabets must be present.Take is as if a string of alphabets getting created as the buttons are clicked. Im using Java Swing for coding. Some piece of my code: if(source == btnAlpha[i] ) bollyDraw.repaint(); //bollydraw is an object of a JPanel extended class having implemented the paintComponent(Graphics g) method In the paint() method: if (word[i] == key) { g.drawChars(word, i, 1, x, y); }

    Read the article

  • Can I fix the width of JRadioButton?

    - by Roman
    I have sever JPanels which have to be ordered vertically. For that I want to fix the width of the JPanels. Because if they are too short in comparison with the windows width, they will go horizontally (one after another) and I do not want it. At the moment the width of the JPanel is not constant because the width of the JRadioButton (included into JPabel) is not constant. How can I make the width of the JRadioButton constant? At the moment it is not constant because of the label (which can be different).

    Read the article

  • Java 1.5.0_16 corrupted colours when saving jpg image

    - by Coder
    Hi, i have a loaded image from disk (stored as a BufferedImage), which i display correctly on a JPanel but when i try to re-save this image using the command below, the image is saved in a reddish hue. ImageIO.write(image, "jpg", fileName); Note! image is a BufferedImage and fileName is a File object pointing to the filename that will be saved which end in ".jpg". I have read that there were problems with ImageIO methods in earlier JDKs but i'm not on one of those versions as far as i could find. What i am looking for is a way to fix this issue without updating the JDK, however having said that i would still like to know in what JDK this issue was fixed in (if it indeed is still a bug with the JDK i'm using). Thanks.

    Read the article

  • How to set custom size for cursor in swing?

    - by swift
    I am using the below code to set a custom cursor for JPanel, but its enlarging the image which i set for cursor. Is there a way to set a customized cursor size ? Toolkit toolkit = Toolkit.getDefaultToolkit(); BufferedImage erasor=new BufferedImage(10,10, BufferedImage.TYPE_INT_RGB); Graphics2D g2d=(Graphics2D) erasor.createGraphics(); g2d.setPaint(Color.red); g2d.drawRect(e.getX(),e.getY() ,10, 10); toolkit.getBestCursorSize(10, 10); Cursor mcursor=toolkit.createCustomCursor(erasor, new Point(10,10), "Eraser"); setCursor(mcursor);

    Read the article

  • Javax Swing Timer Help

    - by kap
    Hello Guys, I am having some problems concerning starting javax.swing.Timer after a mouse click. I want to start the timer to perform some animation after the user clicks on a button but it is not working. Here are the code snippets: public class ShowMe extends JPanel{ private javax.swing.Timer timer; public ShowMe(){ timer = new javax.swing.Timer(20, new MoveListener()); } // getters and setters here private class MoveListener implements ActionListener { public void actionPerformed(ActionEvent e) { // some code here to perform the animation } } } This is the class which contains a button so that when the user clicks on the button the timer starts to begin the animation public class Test{ // button declarations go here and registering listeners also here public void actionPerformed(ActionEvent e) { if(e.getSource() == this.btnConnect){ ShowMe vis = new ShowMe(); vis.getTimer().start(); } } } I want to start the timer to begin the animation but it is not working. Need help how to make a timer start after button click. Thanks.

    Read the article

  • Question about layout in java.

    - by extro
    I have two panels main_panel and child_panel. I have set layout for main_panel by using "main_panel.setLayout(flowlayout)" and added child_panel in main_panel by using "main_panel.add(child_panel)". This child_panel gets added to main_panel but its position is at the cross-section of horizontal midpoint and top vertical section of screen. But I want child_panel to be at the top left corner, something I could have done by using "child_panel.setlocation(a,b)" method, if I have set the Layout of main_panel as NULL. I have used flowlayout here because I want components in the JPanel to keep adjusting with the size of JFrame. So question is, can I add child_panel to main_panel at the exact location I want, even if I set the Layout of main_panel as not NULL.

    Read the article

  • Unable to set mouse cursor JLayeredPane

    - by Ones3k2
    I'm running into a problem that I can't seem to figure out nor find the answer anywhere on the web. I've got a JLayeredPane and when it only has one child Panel I am able to correctly set the cursor using setCursor(). The cursor shows up and everything is fine. But when I add an additional JPanel into the JLayeredPane the cursor no longer shows up for example this works: m_layeredPane = new JLayeredPane(); m_layeredPane.setLayout(new WBLayoutManager()); m_layeredPane.add(m_mediaPanel, new Integer(0)); // m_layeredPane.add(m_whiteboardPanel, new Integer(1)); m_layeredPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); // WORKS but this doesn't: m_layeredPane = new JLayeredPane(); m_layeredPane.setLayout(new WBLayoutManager()); m_layeredPane.add(m_mediaPanel, new Integer(0)); m_layeredPane.add(m_whiteboardPanel, new Integer(1)); m_layeredPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); // FAILS Anyone know how i can get custom cursors working within a JLayeredPane

    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

  • java/Swing issue with paintComponent

    - by user310254
    The issue I'm having is issue with is I'm trying to get the paintComponent to draw the circle only when the mouse is clicked, dragged, then let go. However inside my paintPanel class I have to initialize the object I've created (ex. movedCircle myCircle = new movedCircle(0,0,0,0);) just creating the object movedCircle myCircle; gives an error until I actually fully initialize the object with a value. What I'm looking for: What's considered the best practice for this issue. I don't want to draw anything unnecessary before it is needed. The way I know how to fix it: boolean values inside of paintComponent so that way it doesn't draw until somethings actually there. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class drawCircle extends JFrame{ private JPanel myPanel = new paintPanel(); public drawCircle(){ add(myPanel); } private class paintPanel extends JPanel{ private int x1, y1, x2, y2; movedText myText = new movedText(0,0,0,0); movedCircle myCircle = new movedCircle(0,0,0,0); public paintPanel(){ addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ x1 = e.getX(); y1 = e.getY(); myCircle = new movedCircle(x1, y1, 0, 0); repaint(); } public void mouseReleased(MouseEvent e){ x2 = e.getX(); y2 = e.getY(); myCircle = new movedCircle(x1, y1, x2, y2); repaint(); } }); addMouseMotionListener(new MouseMotionAdapter(){ public void mouseDragged(MouseEvent e){ x2 = e.getX(); y2 = e.getY(); myText = new movedText(x1, y1, x2, y2); myCircle = new movedCircle(x1, y1, x2, y2); repaint(); } public void mouseMoved(MouseEvent e){ x1 = e.getX(); y1 = e.getY(); x2 = 0; y2 = 0; myText = new movedText(x1, y1, x2, y2); repaint(); } }); } protected void paintComponent(Graphics g){ super.paintComponent(g); //draw oval after mouse released myText.paintText(g); myCircle.paintCircle(g); } } class movedCircle{ private int x1, y1, x2, y2; public movedCircle(int x1, int y1, int x2, int y2){ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public void paintCircle(Graphics g){ g.drawOval(x1, y1, x2 - x1, y2 - y1); } } class movedText{ private int x1, y1, x2, y2; public movedText(int x1, int y1, int x2, int y2){ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public void paintText(Graphics g){ g.drawString("x1: "+x1+" y1: "+y1+" x2: "+x2+" y2: "+y2, x1, y1); } } class RedSquare{ private int xPos = 50; private int yPos = 50; private int width = 20; private int height = 20; public void setX(int xPos){ this.xPos = xPos; } public int getX(){ return xPos; } public void setY(int yPos){ this.yPos = yPos; } public int getY(){ return yPos; } public int getWidth(){ return width; } public int getHeight(){ return height; } public void paintSquare(Graphics g){ g.setColor(Color.RED); g.fillRect(xPos,yPos,width,height); g.setColor(Color.BLACK); g.drawRect(xPos,yPos,width,height); } } public static void main(String[] args){ JFrame frame = new drawCircle(); frame.setTitle("Is in ellipse? Demo"); frame.setSize(400, 400); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

    Read the article

  • Drawing multiple lines with Java Swing

    - by rize
    I'm learning drawing lines with Java Swing in order to draw a labyrinth. I can draw one line at a specified position and it shows just fine. But when I want to draw multiple lines, only the last one shows. My code: public class LabyrinthGUI extends JFrame { ... Line line1 = new Line(0, 0, 0, 50); this.getContentPane().add(line1); } public class Line extends JPanel{ private int x1, y1, x2, y2; public Line(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public void paintComponent (Graphics g) { g.drawLine(x1, y1, x2, y2); } I probably have to refresh something, to display all the lines drawn with for-loop, but don't know what.

    Read the article

  • How do I get a JComponent to resize after calling `setVisible(true)`?

    - by iWerner
    Our application displays a 2D view of our data (mainly maps) and then allows the user to change to a 3D view. The 2D and 3D views are generated by custom C++ code that is SWIG'ed into our Swing GUI and wrapped within a JComponent. These JComponents are then displayed within another parent JComponent. Our problem is that when we change from the 2D to the 3D view and then back to the 2D view, when we resize the window the 2D view does not get resized. The resize events don't get sent to the 2D view. Our application runs under Linux (Fedora 11). We're running Java version 1.6.0_12. Here is some sample code in which I've replaced the 2D view and 3D view with two 2 JButtons, that produces the same behaviour. Once you go to 3D and then back to 2D, resizing the window does not cause the 2D view to be resized. /* TestFrame.java * Compile with: $ javac TestFrame.java * Run with: $ java TestFrame */ import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JButton; public class TestFrame extends javax.swing.JFrame { private boolean mode2D = true; private JButton view2D = null; private JButton view3D = null; private Container parent = null; public TestFrame() { initComponents(); containerPanel.setLayout(new BorderLayout()); view2D = new JButton("2D View"); view2D.addComponentListener(new MyListener("2D VIEW")); containerPanel.add(view2D); } private void changerButtonActionPerformed(java.awt.event.ActionEvent evt) { if (parent == null) { parent = view2D.getParent(); } if (mode2D) { System.out.println("Going from 2D to 3D"); view2D.setVisible(false); if (view3D != null) { view3D.setVisible(true); } else { view3D = new JButton("3D View"); view3D.addComponentListener(new MyListener("3D VIEW")); parent.add(view3D); } ((JButton) evt.getSource()).setText("Change to 2D"); mode2D = false; } else { System.out.println("Going from 3D to 2D"); view3D.setVisible(false); view2D.setVisible(true); ((JButton) evt.getSource()).setText("Change to 3D"); mode2D = true; } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TestFrame().setVisible(true); } }); } private javax.swing.JPanel containerPanel; private javax.swing.JButton changerButton; private class MyListener implements ComponentListener { private String name; public MyListener(String name) { this.name = name; } @Override public void componentHidden(ComponentEvent event) { System.out.println("@@@ [" + name + "] component Hidden"); } @Override public void componentResized(ComponentEvent event) { System.out.println("@@@ [" + name + "] component Resized"); } @Override public void componentShown(ComponentEvent event) { System.out.println("@@@ [" + name + "] component Shown"); } @Override public void componentMoved(ComponentEvent event) { System.out.println("@@@ [" + name + "] component Moved"); } }; @SuppressWarnings("unchecked") private void initComponents() { containerPanel = new javax.swing.JPanel(); changerButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); containerPanel.setBorder(new javax.swing.border.MatteBorder(null)); javax.swing.GroupLayout containerPanelLayout = new javax.swing.GroupLayout(containerPanel); containerPanel.setLayout(containerPanelLayout); containerPanelLayout.setHorizontalGroup( containerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 374, Short.MAX_VALUE) ); containerPanelLayout.setVerticalGroup( containerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 239, Short.MAX_VALUE) ); changerButton.setText("Change to 3D"); changerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { changerButtonActionPerformed(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() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(containerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(changerButton)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(changerButton) .addContainerGap()) ); pack(); } } (My apologies for the Netbeans generated GUI code) I should mention that when we call parent.remove(view2D) and parent.add(view3D) to change the views the X Windows ID of our 3D view changes and we're unable to get our 3D view back. Therefore parent.remove(view2D) and parent.add(view3D) is not really a solution and we have to call setVisible(false) and setVisible(true) on the JComponents that contain our 2D and 3D views in order to hide and show them. Any help will be greatly appreciated.

    Read the article

  • Why I cannot see an image if I do not use the full name of an image?

    - by Roman
    I try to add an image to JPanel. It works if I specify the full name of the image (including name of all folders). But I want my software to be machine independent (another machine does not have the same folder structure as my machine has). So, I put my image to the same place where the source is and in my code I use just name of the image (no folders' names). It does not work. I put my image into the folder where my executables are. It does not work again. So, why it does not work and what can I do with that?

    Read the article

  • JButtons re-enable themselves after being disabled

    - by Anarchist
    I have an array of JButtons which form a keypad interface. After six numbers are entered I want to disable the keypad so that no further numbers can be entered by the user. I have written the code and the buttons do disable until the mouse hovers above any of them, then the buttons seem to re-enable themselves and run actionEvents added to them. The full code is available here. Possible things that I think are wrong. There is some sort of MouseListener which is ignoring when I set button.setEnabled(false); I haven't separated attributes from the buildGUI(); correctly, I only did this anyway so that the inner class could access them. Possibly something to do with the gridLayout as disabling the buttons seems to work for my services JPanel buttons.

    Read the article

  • Java programming accessing object variables

    - by Haxed
    Helo, there are 3 files, CustomerClient.java, CustomerServer.java and Customer.java PROBLEM: In the CustomerServer.java file, i get an error when I compile the CustomerServer.java at line : System.out.println(a[k].getName()); ERROR: init: deps-jar: Compiling 1 source file to C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\build\classes C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\src\CustomerServer.java:44: cannot find symbol symbol : method getName() location: class Customer System.out.println(a[k].getName()); 1 error BUILD FAILED (total time: 0 seconds) CustomerClient.java import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class CustomerClient extends JApplet { private JTextField jtfName = new JTextField(32); private JTextField jtfSeatNo = new JTextField(32); // Button for sending a student to the server private JButton jbtRegister = new JButton("Register to the Server"); // Indicate if it runs as application private boolean isStandAlone = false; // Host name or ip String host = "localhost"; public void init() { JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(2, 1)); p1.add(new JLabel("Name")); p1.add(jtfName); p1.add(new JLabel("Seat No.")); p1.add(jtfSeatNo); add(p1, BorderLayout.CENTER); add(jbtRegister, BorderLayout.SOUTH); // Register listener jbtRegister.addActionListener(new ButtonListener()); // Find the IP address of the Web server if (!isStandAlone) { host = getCodeBase().getHost(); } } /** Handle button action */ private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { // Establish connection with the server Socket socket = new Socket(host, 8000); // Create an output stream to the server ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream()); // Get text field String name = jtfName.getText().trim(); String seatNo = jtfSeatNo.getText().trim(); // Create a Student object and send to the server Customer s = new Customer(name, seatNo); toServer.writeObject(s); } catch (IOException ex) { System.err.println(ex); } } } /** Run the applet as an application */ public static void main(String[] args) { // Create a frame JFrame frame = new JFrame("Register Student Client"); // Create an instance of the applet CustomerClient applet = new CustomerClient(); applet.isStandAlone = true; // Get host if (args.length == 1) { applet.host = args[0]; // Add the applet instance to the frame } frame.add(applet, BorderLayout.CENTER); // Invoke init() and start() applet.init(); applet.start(); // Display the frame frame.pack(); frame.setVisible(true); } } CustomerServer.java import java.io.*; import java.net.*; public class CustomerServer { private String name; private int i; private ObjectOutputStream outputToFile; private ObjectInputStream inputFromClient; public static void main(String[] args) { new CustomerServer(); } public CustomerServer() { Customer[] a = new Customer[30]; try { // Create a server socket ServerSocket serverSocket = new ServerSocket(8000); System.out.println("Server started "); // Create an object ouput stream outputToFile = new ObjectOutputStream( new FileOutputStream("student.dat", true)); while (true) { // Listen for a new connection request Socket socket = serverSocket.accept(); // Create an input stream from the socket inputFromClient = new ObjectInputStream(socket.getInputStream()); // Read from input //Object object = inputFromClient.readObject(); for (int k = 0; k <= 2; k++) { if (a[k] == null) { a[k] = (Customer) inputFromClient.readObject(); // Write to the file outputToFile.writeObject(a[k]); //System.out.println("A new student object is stored"); System.out.println(a[k].getName()); break; } if (k == 2) { //fully booked outputToFile.writeObject("All seats are booked"); break; } } } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inputFromClient.close(); outputToFile.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } Customer.java public class Customer implements java.io.Serializable { private String name; private String seatno; public Customer(String name, String seatno) { this.name = name; this.seatno = seatno; } public String getName() { return name; } public String getSeatNo() { return seatno; } }

    Read the article

  • JAVA-I don't want clicking on my app make other apps lose focus

    - by Auxiliary
    Wow, what a stupid question you might say. But is it possible? I have a mouse move event in a Jpanel and it works even when the application is not in focus, now can I have something like that for the clicking event or something similar. And most importantly I don't want other apps (even something like the main menu) to lose focus when i click on my app. I was the system's event queue but i'm not sure where that would lead me to. Thanks in advance.

    Read the article

  • Java Swing - Problem in JSpinner

    - by Yatendra Goel
    I am developing a Java Desktop Application and designing the GUI with the help of Netbeans Swing GUI builder. I want to use a JSpinner in my app. I have dragged and dropped it to a JPanel. Now, I want to set its two properties: First, It should display numbers in the range of 1 to 50. Neither less than 1 nor greater than 50. How can I set that range? Second, when I try to get the value of it by spinner.getValue() it returns an Object. As my spinner's data type is Integer, would it be better to downcast the Object into Integer or Is there any other way to get that numeric value?

    Read the article

  • Manage multiple Jlabel's events

    - by IMAnis_tn
    I have a left Panel with multiples Jlabels which i use them as buttons to change a Main Panel's content which is layouted with a CardLayout. I cant work perfectly with these events: mouseEntered : to make highlight effect to the jlabel mouseExited : to take off the highlight effect. mouseClicked : to change the content of the main Panel and start some threads The problem here that can't found an event or a method tell me that another Jlabel has been clicked so i can stop my threads started in the mouseClicked event, OR an event or method tell me that a JPanel in the CardLayout has been displayed or hidden.

    Read the article

  • Java Program Compiles and Runs, but doesn't work

    - by Richard Long
    When I run this program I enter information in a text box, push the search button, but nothing happens. The program just sits there until I press Cntrl C to break it. It looks like it should work, but I can't figure out what is hanging the program up. Here is the code: First class: import java.io.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class NameGameFrame extends JFrame { public static String name; static JTextField textfield = new JTextField(20); static JTextArea textarea = new JTextArea(30,30); public static String num; public static String [] fields; public static int [] yearRank; public static boolean match; public static int getInts, marker, year, max; public static void main( String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Name Game"); frame.setLocation(500,400); frame.setSize(800,800); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JLabel label = new JLabel("Enter the Name or Partial Name to search:"); c.gridx = 0; c.gridy = 0; c.insets = new Insets(2,2,2,2); panel.add(label,c); c.gridx = 0; c.gridy = 1; panel.add(textarea,c); JButton button = new JButton("Search"); c.gridx = 1; c.gridy = 1; panel.add(button,c); c.gridx = 1; c.gridy = 0; panel.add(textfield,c); frame.getContentPane().add(panel, BorderLayout.NORTH); frame.pack(); frame.setVisible(true); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { name = textfield.getText(); java.io.File file = new java.io.File("namesdata.txt"); try { Scanner input = new Scanner(file); num = input.nextLine(); NameRecord nr = new NameRecord(name); while (input.hasNext()) { if(match = num.toLowerCase().contains(name.toLowerCase())) { nr.getRank(); nr.getBestYear(marker); } } } catch(FileNotFoundException e) { System.err.format("File does not exist\n"); } textarea.setText(fields[0]); } }); } } This is the second class: import java.io.*; import java.util.*; public class NameRecord { public NameRecord( String name) { } public static int getBestYear(int marker) { switch (marker) { case 1: year = 1900; break; case 2: year = 1910; break; case 3: year = 1920; break; case 4: year = 1930; break; case 5: year = 1940; break; case 6: year = 1950; break; case 7: year = 1960; break; case 8: year = 1970; break; case 9: year = 1980; break; case 10: year = 1990; break; case 11: year = 2000; break; } return year; } public static int getRank() { fields = num.split(" "); max = 0; for (int i = 1; i<12; i++) { getInts = Integer.parseInt(fields[i]); if(getInts>max) { max = getInts; marker = i; } } return max; } }

    Read the article

  • How to create GUI as inner class with WindowBuilder

    - by Tim Kemp
    I would like to use WindowBuilder in Eclipse to construct Swing GUIs. The JPanels I need to build will be inner classes in a non-GUI wrapper, like so: public class MyWrapper extends MyBaseClass { ... class MyPanel extends JPanel { ... } } So my question is this: can I construct MyPanel using WindowBuilder? If so, how should I set it up? If anyone is interested, the wrapper is an abstract base class which the plug-ins I am developing for my app must extend; deployment concerns mean that it's not really practical to put the GUIs in a separate JAR either so I pretty much have to do it this way. My current workflow, which is awful, is to build the GUI in NetBeans and paste the entire generated class into Eclipse where I connect it up to the methods in my wrapper. I am very hopeful that WindowBuilder will let me work more reliably and efficiently if I can trick it into generating code in MyPanel, not MyWrapper. Thanks

    Read the article

  • how do i close a frame yet open a new frame?(revisited)

    - by altvali
    I'm new at Java and I'm trying to do what the title says, my application has page A, a jpanel with some controls and a specific button, and when the user clicks the button i want page A to disappear and page B to appear (page B has controls that depend on the choices that are made by the user on page A). This has been asked before but there was no satisfactory answer. In the ActionListener implementation, namely public void ActionPerformed(ActionEvent e) from my jpanelForPageA class i can comfortably write this.setVisible(false), but how can i set page B to a visible state?

    Read the article

  • How to draw a filled circle in Java?

    - by Roman
    I have a JPanel with a Grid Layout. In the "cells" of the grid I can put different elements (for example JButtons). There is no problems with that. But now I want to put a filled circle in some of the cells. I also would like to relate an ActionListener with these circles. In more details, if I click the circle it disappears from the current cell and appears in another one. How can I do it in Java? I am using Swing.

    Read the article

  • Positioning child panels using FlowLayout

    - by extro
    I have two panels: main_panel child_panel The main_panel layout is set using: main_panel.setLayout(flowlayout) I then added child_panel to main_panel: main_panel.add(child_panel) The child_panel gets added to main_panel but its position is at the cross-section of horizontal midpoint and top vertical section of screen. I want child_panel to be at the top left corner, something I could have done by using child_panel.setlocation(a,b) method, if I have set the layout of main_panel as null. I have used FlowLayout here because I want components in the JPanel to keep adjusting with the size of JFrame. So can I add child_panel to main_panel at the exact location I want, even if I set the Layout of main_panel as not null?

    Read the article

  • GridBagConstraints problem-moved to left and size isn't the same

    - by Damir
    I have in Java two panels which need to have same layout, there is my functions for initializations panels. private void InitializePanelCom(){ pnlCom=new JPanel(); pnlCom.setSize(300,160); pnlCom.setLocation(10, 60); add(pnlCom); GridBagLayout gb=new GridBagLayout(); GridBagConstraints gc=new GridBagConstraints(); pnlCom.setLayout(gb); jLabelcommPort = setJLabel("Com Port : "); jLabelbaudRate = setJLabel("Baud Rate : "); jLabelplcAddress = setJLabel("Plc Address : "); jLabelsendTime = setJLabel("Send Time : "); jLabelx50 = setJLabel(" x 50 ms (2 - 99)"); jComboBoxcommPort = setJComboBox(commPortList); jComboBoxbaudRate = setJComboBox(bitRateList); jTextAreaPlcAddress = setJTextField(""); jTextAreaSendTime = setJTextField(""); gc.insets = new Insets(10,0,0,0); gc.ipadx = 120; gc.weightx = 1; gc.gridx = 0; gc.gridy = 0; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jLabelcommPort,gc); gc.insets = new Insets(10,0,0,0); gc.ipadx = 120; gc.weightx = 1; gc.gridx = 1; gc.gridy = 0; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jComboBoxcommPort,gc); gc.insets=new Insets(10,0,0,0); gc.ipadx=120; gc.weightx=1; gc.gridx=0; gc.gridy=1; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jLabelbaudRate,gc); gc.insets=new Insets(10,0,0,0); gc.ipadx=120; gc.weightx=1; gc.gridx=1; gc.gridy=1; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jComboBoxbaudRate,gc); gc.insets=new Insets(10,0,0,0); gc.ipadx=120; gc.weightx=1; gc.gridx=0; gc.gridy=2; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jLabelplcAddress,gc); gc.insets=new Insets(10,0,0,0); gc.ipadx=120; gc.weightx=1; gc.gridx=1; gc.gridy=2; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jTextAreaPlcAddress,gc); gc.insets=new Insets(10,0,0,0); gc.ipadx=120; gc.weightx=1; gc.gridx=0; gc.gridy=3; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jLabelsendTime,gc); gc.insets=new Insets(10,0,0,0); gc.ipadx=120; gc.weightx=1; gc.gridx=1; gc.gridy=3; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jTextAreaSendTime,gc); gc.insets=new Insets(10,0,0,0); gc.ipadx=120; gc.weightx=1; gc.gridx=2; gc.gridy=3; gc.anchor=GridBagConstraints.EAST; pnlCom.add(jLabelx50,gc); } ![alt text][1] private void InitializePanelTcp(){ pnlTcp=new JPanel(); pnlTcp.setSize(300,160); pnlTcp.setLocation(10, 60); add(pnlTcp); GridBagLayout gb=new GridBagLayout(); GridBagConstraints gc=new GridBagConstraints(); pnlTcp.setLayout(gb); lblIPAddress=setJLabel("IP Address : "); txtIPAddress=setJTextField(""); lblPort=setJLabel("Port : "); txtPort=setJTextField(""); cmbBaudRateTCP = setJComboBox(bitRateList); lblBaudRateTCP = setJLabel("Baud Rate : "); lblParityCheck=setJLabel("Parity check : "); txtParityCheck=setJTextField(""); gc.insets = new Insets(10,0,0,0); //gc.ipadx = 20; gc.weightx = 0.3; gc.gridx = 0; gc.gridy = 0; gc.anchor=GridBagConstraints.WEST; pnlTcp.add(lblIPAddress,gc); gc.insets = new Insets(10,0,0,0); //gc.ipadx = 80; gc.weightx = 0.7; gc.gridx = 1; gc.gridy = 0; gc.anchor=GridBagConstraints.WEST; pnlTcp.add(txtIPAddress,gc); gc.insets=new Insets(10,0,0,0); //gc.ipadx=120; gc.weightx=0.3; gc.gridx=0; gc.gridy=1; gc.anchor=GridBagConstraints.WEST; pnlTcp.add(lblPort,gc); gc.insets=new Insets(10,0,0,0); //gc.ipadx=80; gc.weightx=0.7; gc.gridx=1; gc.gridy=1; gc.anchor=GridBagConstraints.WEST; pnlTcp.add(txtPort,gc); gc.insets=new Insets(10,0,0,0); //gc.ipadx=120; gc.weightx=0.3; gc.gridx=0; gc.gridy=2; gc.anchor=GridBagConstraints.WEST; pnlTcp.add(lblBaudRateTCP,gc); gc.insets=new Insets(10,0,0,0); //gc.ipadx=0; gc.weightx=0.7; gc.gridx=1; gc.gridy=2; gc.anchor=GridBagConstraints.WEST; pnlTcp.add(cmbBaudRateTCP,gc); gc.insets=new Insets(10,0,0,0); //gc.ipadx=120; gc.weightx=0.3; gc.gridx=0; gc.gridy=3; gc.anchor=GridBagConstraints.WEST; pnlTcp.add(lblParityCheck,gc); gc.insets=new Insets(10,0,0,0); //gc.ipadx=0; gc.weightx=1.7; gc.gridx=1; gc.gridy=3; gc.anchor=GridBagConstraints.WEST; pnlTcp.add(txtParityCheck,gc); } Problem is that second panel (initializetcp, second picture doesn't look the same, labels are moved at left , it is different ). Can anybody help, I am new with GridBagContsraints at all ?

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18  | Next Page >