Search Results

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

Page 9/10 | < Previous Page | 5 6 7 8 9 10  | Next Page >

  • Netbeans Java SE GUI Builder: private initComponents() problem

    - by maSnun
    When I build a GUI for my Java SE app with Netbeans GUI builder, it puts all the codes in the initComponents() method which is private. I could not change it to public. So, all the components are accessible only to the class containing the UI. I want to access those components from another class so that I can write custom event handlers and everything. Most importantly I want to separate my GUI code and non-GUI from each other. I can copy paste the GUI code and later make them public by hand to achieve what I want. But thats a pain. I have to handcraft a portion whenever I need to re-design the UI. What I tried to do: I used the variable identifier to make the text box public. Now how can I access the text box from the Main class? I think I need the component generated in a public method as well. I am new to Java. Any helps? Here's the sample classes: The UI (uiFrame.java) /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * uiFrame.java * * Created on Jun 3, 2010, 9:33:15 PM */ package barcode; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import net.sourceforge.barbecue.output.OutputException; /** * * @author masnun */ public class uiFrame extends javax.swing.JFrame { /** Creates new form uiFrame */ public uiFrame() { try { try { // Set cross-platform Java L&F (also called "Metal") UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } } finally { } initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { label1 = new javax.swing.JLabel(); textBox = new javax.swing.JTextField(); saveButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); label1.setFont(label1.getFont().deriveFont(label1.getFont().getStyle() | java.awt.Font.BOLD, 13)); label1.setText("Type a text:"); label1.setName("label1"); // NOI18N saveButton.setText("Save"); saveButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { saveButtonMousePressed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(textBox, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(72, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(154, Short.MAX_VALUE) .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(144, 144, 144)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(140, Short.MAX_VALUE) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(127, 127, 127)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(saveButton) .addContainerGap(193, Short.MAX_VALUE)) ); pack(); }// </editor-fold> @SuppressWarnings("static-access") private void saveButtonMousePressed(java.awt.event.MouseEvent evt) { JFileChooser file = new JFileChooser(); file.showSaveDialog(null); String data = file.getSelectedFile().getAbsolutePath(); String text = textBox.getText(); BarcodeGenerator barcodeFactory = new BarcodeGenerator(); try { barcodeFactory.generateBarcode(text, data); } catch (OutputException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } } /** * @param args the command line arguments */ // Variables declaration - do not modify private javax.swing.JLabel label1; private javax.swing.JButton saveButton; public javax.swing.JTextField textBox; // End of variables declaration } The Main Class (Main.java) package barcode; import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame ui = new uiFrame(); ui.pack(); ui.show(); } }

    Read the article

  • Wanting a type of grid for a pixel editor

    - by wiggles
    Hi, I am currently trying to develop a basic pixel editor application to build up my programming experience with Java. I am designing it so the user has several colour options on, they click on an option and then they can drag over the cells in the grid and they change colour (like a typical image editor, but with a sort of snap on to each grid cell) Any idea of what Java component, if any, is able to implement this type of grid in Java? I had thought of each cell being a JButton, but this seemed terribly inefficient and I don't think it would be possible to change the colour of each cell(button) with out individually clicking on each one. Any help appreciated.

    Read the article

  • Panel is not displaying in JFrame

    - by mallikarjun
    I created a chat panel and added to Jframe but the panel is not displaying. But my sop in the chat panel are displaying in the console. Any one please let me know what could be the problem My Frame public class MyFrame extends JFrame { MyPanel chatClient; String input; public MyFrame() { input = (String)JOptionPane.showInputDialog(null, "Name:", "Connect to chat server", JOptionPane.QUESTION_MESSAGE, null,null, "Test"); input=input.trim(); chatClient = new MyPanel("localhost",input); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(chatClient); } public static void main(String...args){ new MyFrame(); } } MyPanel: public class MyPanel extends JPanel{ ChatClient chatClient; public MyPanel(String host, String uid) { chatClient= new ChatClient(host,uid); add(chatClient.getChatPanel()); this.setVisible(true); } } chat panel: public class ChatClient { Client client; String name; ChatPanel chatPanel; String hostid; public ChatClient(String host,String uid){ client = new Client(); client.start(); System.out.println("in constructor"); Network.register(client); client.addListener(new Listener(){ public void connected(Connection connection){ System.out.println("in client connected method"); Network.RegisterName registerName = new Network.RegisterName(); registerName.name=name; client.sendTCP(registerName); } public void received(Connection connection,Object object){ System.out.println("in client received method"); if (object instanceof Network.UpdateNames) { Network.UpdateNames updateNames = (Network.UpdateNames)object; //chatFrame.setNames(updateNames.names); System.out.println("got it message"); return; } if (object instanceof Network.ChatMessage) { Network.ChatMessage chatMessage = (Network.ChatMessage)object; //chatFrame.addMessage(chatMessage.text); System.out.println("send it message"); return; } } }); // end of listner name=uid.trim(); hostid=host.trim(); chatPanel = new ChatPanel(hostid,name); chatPanel.setSendListener(new Runnable(){ public void run(){ Network.ChatMessage chatMessage = new Network.ChatMessage(); chatMessage.chatMessage=chatPanel.getSendText(); client.sendTCP(chatMessage); } }); new Thread("connect"){ public void run(){ try{ client.connect(5000, hostid,Network.port); }catch(IOException e){ e.printStackTrace(); } } }.start(); }//end of constructor static public class ChatPanel extends JPanel{ CardLayout cardLayout; JList messageList,nameList; JTextField sendText; JButton sendButton; JPanel topPanel,bottomPanel,panel; public ChatPanel(String host,String user){ setSize(600, 200); this.setVisible(true); System.out.println("Chat panel "+host+"user: "+user); { panel = new JPanel(new BorderLayout()); { topPanel = new JPanel(new GridLayout(1,2)); panel.add(topPanel); { topPanel.add(new JScrollPane(messageList=new JList())); messageList.setModel(new DefaultListModel()); } { topPanel.add(new JScrollPane(nameList=new JList())); nameList.setModel(new DefaultListModel()); } DefaultListSelectionModel disableSelections = new DefaultListSelectionModel() { public void setSelectionInterval (int index0, int index1) { } }; messageList.setSelectionModel(disableSelections); nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } { bottomPanel = new JPanel(new GridBagLayout()); panel.add(bottomPanel,BorderLayout.SOUTH); bottomPanel.add(sendText=new JTextField(),new GridBagConstraints(0,0,1,1,1,0,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,0),0,0)); bottomPanel.add(sendButton=new JButton(),new GridBagConstraints(1,0,1,1,0,0,GridBagConstraints.CENTER,0,new Insets(0,0,0,0),0,0)); } } sendText.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ sendButton.doClick(); } }); } public void setSendListener (final Runnable listener) { sendButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { if (getSendText().length() == 0) return; listener.run(); sendText.setText(""); sendText.requestFocus(); } }); } public String getSendText () { return sendText.getText().trim(); } public void setNames (final String[] names) { EventQueue.invokeLater(new Runnable(){ public void run(){ DefaultListModel model = (DefaultListModel)nameList.getModel(); model.removeAllElements(); for(String name:names) model.addElement(name); } }); } public void addMessage (final String message) { EventQueue.invokeLater(new Runnable() { public void run () { DefaultListModel model = (DefaultListModel)messageList.getModel(); model.addElement(message); messageList.ensureIndexIsVisible(model.size() - 1); } }); } } public JPanel getChatPanel(){ return chatPanel; } }

    Read the article

  • Is there a version of postActionEvent for KeyEvent (specifically for a JTextArea)?

    - by Brian Pelc
    I'm writing a program that contains multiple JTextFields and 2 JTextAreas within an input panel. I have a submit button on the bottom. I have it set up so when a user types something into each field (including the JTextAreas) and hits the Enter key, it updates a text file, and when they press the submit button it updates the file then outputs a new version of it in the local directory. If the user presses Enter in any of the fields, it validates their input, however, I want to re-validate all fields when they press the submit button. Each field (again, JTextAreas included) has it's own validation check within its ActionListener or KeyListener (for the JTextAreas). It's easy enough to use postActionEvent() for the JTextFields, but is there a similar method for the JTextAreas to force fire a KeyEvent? I don't want to duplicate code and consume memory by re-writing the validation for those 2 Components inside the ActionEvent for the JButton. Unfortunately, I can't provide a sample because I'm writing the program on a classified machine (PC).

    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 code for capture the image by webcam

    - by Navneet
    I am using windows7 64 bit operating system. The source code is for capturing the image by webcam: import javax.swing.*; import javax.swing.event.*; import java.io.*; import javax.media.*; import javax.media.format.*; import javax.media.util.*; import javax.media.control.*; import javax.media.protocol.*; import java.util.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import com.sun.image.codec.jpeg.*; public class SwingCapture extends Panel implements ActionListener { public static Player player = null; public CaptureDeviceInfo di = null; public MediaLocator ml = null; public JButton capture = null; public Buffer buf = null; public Image img = null; public VideoFormat vf = null; public BufferToImage btoi = null; public ImagePanel imgpanel = null; public SwingCapture() { setLayout(new BorderLayout()); setSize(320,550); imgpanel = new ImagePanel(); capture = new JButton("Capture"); capture.addActionListener(this); String str1 = "vfw:Logitech USB Video Camera:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; di = CaptureDeviceManager.getDevice(str2); ml = di.getLocator(); try { player = Manager.createRealizedPlayer(ml); player.start(); Component comp; if ((comp = player.getVisualComponent()) != null) { add(comp,BorderLayout.NORTH); } add(capture,BorderLayout.CENTER); add(imgpanel,BorderLayout.SOUTH); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Frame f = new Frame("SwingCapture"); SwingCapture cf = new SwingCapture(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { playerclose(); System.exit(0);}}); f.add("Center",cf); f.pack(); f.setSize(new Dimension(320,550)); f.setVisible(true); } public static void playerclose() { player.close(); player.deallocate(); } public void actionPerformed(ActionEvent e) { JComponent c = (JComponent) e.getSource(); if (c == capture) { // Grab a frame FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl"); buf = fgc.grabFrame(); // Convert it to an image btoi = new BufferToImage((VideoFormat)buf.getFormat()); img = btoi.createImage(buf); // show the image imgpanel.setImage(img); // save image saveJPG(img,"c:\\test.jpg"); } } class ImagePanel extends Panel { public Image myimg = null; public ImagePanel() { setLayout(null); setSize(320,240); } public void setImage(Image img) { this.myimg = img; repaint(); } public void paint(Graphics g) { if (myimg != null) { g.drawImage(myimg, 0, 0, this); } } } public static void saveJPG(Image img, String s) { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, null, null); FileOutputStream out = null; try { out = new FileOutputStream(s); } catch (java.io.FileNotFoundException io) { System.out.println("File Not Found"); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi); param.setQuality(0.5f,false); encoder.setJPEGEncodeParam(param); try { encoder.encode(bi); out.close(); } catch (java.io.IOException io) { System.out.println("IOException"); } } } This code is sucessfully compiled. On running the code, the following runtime error occurs: Exception in thread "VFW Request Thread" java.lang.UnsatisfiedLinkError:JMFSecurityManager: java.lang.UnsatisfiedLinkError:no jmvfw in java.library.path at com.sun.media.JMFSecurityManager.loadLibrary(JMFSecurityManager.java:206) at com.sun.media.protocol.vfw.VFWCapture.<clinit><VFWCapture.java:19> at com.sun.media.protocol.vfw.VFWSourceStream.doConnect(VFWSourceStream.java:241) at com.sun.media.protocol.vfw.VFWSourceStream.run(VFWSourceStream.java:763) at java.cdlang.Thread.run(Thread.java:619) Please send me solution of this problem/

    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

  • Take input through Buttons in java

    - by stash211
    I understand that the title might not be descriptive enough, but I'm making a magic square game in Java and basically, I'm trying to replicate user input as found in the sudoku game here: http://www.websudoku.com/. What I have is a n x n grid of Buttons (not JButton) as the board and what I want the user to be able to do is when the user clicks on one of the buttons, similar to the game above, it allows the user to type in his guess in the button itself instead of popping up a dialog box with an input field of some sort. I don't know where to start, I am a beginner in Java (not very beginner, but my knowledge with the various Java APIs is very limited), so I'm trying to find out if this would be possible and if it is, how would I go about doing it? Thanks for any help.

    Read the article

  • Image not getting displayed on a JPanel.

    - by Myth17
    class Deal implements ActionListener { public void actionPerformed(ActionEvent e) { dl.setDeck(); dl.shuffle(); dl.firstDraw(pl); for(Card c:pl.showHand()) panelplay.add(new JLabel(c.getImageIcon())); panelplay.validate(); } } This is an event handler for a Jbutton. The method pl.showHand() returns a ArrayList of a user defined class 'Card'. Inserting a println() inside the loop shows the print, so the code is being executed but the Panel panelplay isnt showing card Images.

    Read the article

  • setCursor on container without it changing cursor of sub components

    - by Mike
    JPanel panel = new JPanel(null); panel.setSize(400, 400); panel.add(new JButton("Test")); panel.setCursor(Cursor.getCursor(Cursor.SOMETHING_SOMETHING_CURSOR)); The panel will have a custom cursor, but I don't want the button to have a custom cursor. I don't want to have to set the cursor of every sub component, because in my application I have many and I don't want to litter the code with setCursor statements. Is there a way, like overriding a method on the JPanel or something? A "contains" method somewhere is used to determine if a cursor needs to be set. Could I fool it into thinking the mouse is not in the container if it's really in a sub component? Any other nifty little trick?

    Read the article

  • Add Method to Built In Class

    - by Evorlor
    I am pretty sure this is not doable, but I will go ahead and cross my fingers and ask. I am trying to add a method to a built in class. I want this method to be callable by all of the built in class's subclasses. Specifically: I have a JButton, a JTextPane, and other JComponents. I want to be able to pass in a JDom Element instead of a Rectangle to setBounds(). My current solution is to extend each JComponent subclass with the desired methods, but that is a LOT of duplicate code. Is there a way I can write the following method just one time, and have it callable on all JComponent objects? Or is it required that I extend each subclass individually, and copy and paste the method below? public void setBounds(Element element) { this.setBounds(Integer.parseInt(element.getAttribute( "x").toString()), Integer.parseInt(element .getAttribute("y").toString()), Integer .parseInt(element.getAttribute("width").toString()), Integer.parseInt(element.getAttribute("height") .toString())); }

    Read the article

  • JButtons don't imediatly change on mouse event

    - by out_sider
    I'm using the java swing library to develop a board game called DAO. The problem is that after the human player makes its move, by clicking on the JButton with the piece image that he wants to play, I call the computer AI routine but inside the mouse event function. By doing this only when the function returns, the computer ends its turn, do the JButtons refresh their Images (setIcon comes in). I'd like to know how can I force the JButtons to change their image at the moment they are clicked and not only when the mouse event function ends (as I need to handle data inside it). I've tried all of this myButtons[i][j].setIcon(xIcon); myButtons[i][j].revalidate(); myButtons[i][j].repaint(); myButtons[i][j].validate(); None worked. Thx in advance

    Read the article

  • Open a new panel via a button Java Swing

    - by abuteau
    I saw a lot of post on StackOverflow relating to this, but unable to solve my problem. I want to open a new Panel by clicking a button. Here is how i try to do it parameterButton = new JButton("Parametres"); parameterButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ createParameterPanel = new DisplayParameterPanel(); createParameterPanel.setVisible(true); add(createParameterPanel); }; }); add(parameterButton); When I click the parameterButton it doesn't open. How can I open a new panel. Thanks,

    Read the article

  • problem in login in yahoo massanger

    - by khoyendra
    package session; import java.io.FileWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.JOptionPane; import org.openymsg.network.FireEvent; import org.openymsg.network.Session; import org.openymsg.network.SessionState; import org.openymsg.network.event.SessionListener; public class BotGUI extends javax.swing.JFrame implements SessionListener{ /** Creates new form BotGUI */ FileWriter fw; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public BotGUI() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); uNameTextField = new javax.swing.JTextField(); uPassPasswordField = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel3.setBackground(new java.awt.Color(51, 51, 51)); jLabel1.setBackground(new java.awt.Color(0, 0, 255)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Yahoo Login Panel"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(38, 38, 38) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(532, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) ); jPanel2.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 710, 30)); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setText("Username"); jPanel4.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 20, 60, 20)); jLabel3.setText("Password"); jPanel4.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 20, 60, 20)); jPanel4.add(uNameTextField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 20, 140, 20)); jPanel4.add(uPassPasswordField, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 20, 140, -1)); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("Login"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel4.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 15, 90, -1)); jPanel2.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 30, 710, 60)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(293, Short.MAX_VALUE)) ); jMenu1.setText("Option"); jMenuItem1.setText("Logout"); jMenu1.add(jMenuItem1); jMenuItem2.setText("Load CSV"); jMenu1.add(jMenuItem2); jMenuItem3.setText("Exit"); jMenu1.add(jMenuItem3); jMenuBar1.add(jMenu1); jMenu2.setText("Help"); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold> public void handleConnectionClosed() { connectionClosed = true; loggedIn = false; } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { if(!uNameTextField.getText().equals("") && !uPassPasswordField.getText().equals("")){ Yahoo_login(uNameTextField.getText(),uPassPasswordField.getText()); }else{ JOptionPane.showMessageDialog(null, "Plese Enter User Id and Password"); } } Session yahooMessengerSession; MySessionListener mySessionListener; boolean loggedIn = false; boolean connectionClosed = false; public void Yahoo_login(String uName, String pass) { connectionClosed = false; if (loggedIn == false) { yahooMessengerSession = new Session(); mySessionListener = new MySessionListener(this); yahooMessengerSession.addSessionListener(mySessionListener); try { if ((uName.equals("")) || (pass.equals(""))) { System.out.println("User name/password is blank"); } else{ //initialized a file writer for log file System.out.println("Login start........"); yahooMessengerSession.login(uName, pass, true); //checks whether user was succesful in login in if (yahooMessengerSession!=null && yahooMessengerSession.getSessionStatus()== SessionState.LOGGED_ON) { //this loop is reached when the user has been successfully logined System.out.println("Login Success"); fw.write("User (" + uName + ") logged in at : " + dateFormat.format("09.05.10") + " \n"); fw.close(); } else { yahooMessengerSession.reset(); } } } catch(Exception e){ } } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BotGUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JTextField uNameTextField; private javax.swing.JPasswordField uPassPasswordField; // End of variables declaration public void dispatch(FireEvent fe) { throw new UnsupportedOperationException("Not supported yet."); } } i have to find the error SEVERE: error during the dispatch of event: FireEvent [org.openymsg.network.event.SessionListEvent to:null from:null message:null timestamp:0 status:0 list type:Friends size:2 LIST] java.lang.UnsupportedOperationException: Not supported yet. at yahoomessangerbot.MySessionListener.dispatch(MySessionListener.java:131) at org.openymsg.network.EventDispatcher.runEventNOW(EventDispatcher.java:133) at org.openymsg.network.EventDispatcher.run(EventDispatcher.java:114)

    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

  • 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

  • Filling combobox from database by using hibernate in Java

    - by denny
    Heyy; I am developing a small swing based application with hibernate in java. And I want fill combobox from database coloumn.How i can do that ? And I don't know in where(under initComponents, buttonActionPerformd) i need to do. For saving i'am using jbutton and it's code is here : private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int idd=Integer.parseInt(jTextField1.getText()); String name=jTextField2.getText(); String description=jTextField3.getText(); Session session = null; SessionFactory sessionFactory = new Configuration().configure() .buildSessionFactory(); session = sessionFactory.openSession(); Transaction transaction = session.getTransaction(); try { ContactGroup con = new ContactGroup(); con.setId(idd); con.setGroupName(name); con.setGroupDescription(description); transaction.begin(); session.save(con); transaction.commit(); } catch (Exception e) { e.printStackTrace(); } finally{ session.close(); } }

    Read the article

  • Loosing Textbox value on postback

    - by Dusty Roberts
    Hi Peeps i have an href that once clicking on it, it opens a dialog and sets a textbox value for that dialog. however, once i click on submit in that dialog, the textbox value is null. Link: <a href="#" onclick="javascript:expand('https://me.yahoo.com'); jQuery('#openiddialog').dialog('open'); return false;"><img id="yahoo" class="spacehw" src="/Content/Images/spacer.gif" /></a> Script: <script type="text/javascript"> jQuery(document).ready(function () { jQuery("#openiddialog").dialog({ autoOpen: false, width: 600, modal: true, buttons: { "Cancel": function () { $(this).dialog("close"); } } }); }); function expand(obj) { $("#<%=openIdBox.ClientID %>").val(obj); } </script> Dialog:<div id="openiddialog" title="Log in using OpenID"> <p> <asp:Label ID="Label1" runat="server" Text="OpenID Login" /> <asp:TextBox ID="openIdBox" EnableViewState="true" runat="server" /> <asp:JButton Icon="ui-icon-key" ID="loginButton" runat="server" Text="Authenticate" OnClick="loginButton_Click" /> <asp:CustomValidator runat="server" ID="openidValidator" ErrorMessage="Invalid OpenID Identifier" ControlToValidate="openIdBox" EnableViewState="false" OnServerValidate="openidValidator_ServerValidate" /> <br /> <asp:Label ID="loginFailedLabel" runat="server" EnableViewState="False" Text="Login failed" Visible="False" /> <asp:Label ID="loginCanceledLabel" runat="server" EnableViewState="False" Text="Login canceled" Visible="False" /> </p> </div> ... sorry... can't fix formatting ?!?

    Read the article

  • Netbeans GUI building on pre-defined code

    - by deliriumtremens
    I am supposed edit some code for an assignment, and he gave us the framework and wants us to implement code for it. I load the project into netbeans and can't figure out how I'm supposed to edit the swing components. I don't see how to edit source vs. design. import javax.swing.*; import java.util.*; import java.io.*; public class CurrencyConverterGUI extends javax.swing.JFrame { /************************************************************************************************************** insert your code here - most of this will be generated by NetBeans, however, you must write code for the event listeners and handlers for the two ComboBoxes, the two TextBoxes, and the Button. Please note you must also poulate the ComboBoxes withe currency symbols (which are contained in the KeyList attribute of CurrencyConverter CC) ***************************************************************************************************************/ private CurrencyConverter CC; private javax.swing.JTextField Currency1Field; private javax.swing.JComboBox Currency1List; private javax.swing.JTextField Currency2Field; private javax.swing.JComboBox Currency2List; private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; } class CurrencyConverter{ private HashMap HM; // contains the Currency symbols and conversion rates private ArrayList KeyList; // contains the list of currency symbols public CurrencyConverter() { /************************************************** Instantiate HM and KeyList and load data into them. Do this by reading the data from the Rates.txt file ***************************************************/ } public double convert(String FromCurrency, String ToCurrency, double amount){ /*************************************************************************** Will return the converted currency value. For example, to convert 100 USD to GBP, FromCurrency is USD, ToCurrency is GBP and amount is 100. The rate specified in the file represent the amount of each currency which is equivalent to one Euro (EUR). Therefore, 1 Euro is equivalent to 1.35 USD Use the rate specified for USD to convert to equivalent GBP: amount / USD_rate * GBP_rate ****************************************************************************/ } public ArrayList getKeys(){ // return KeyList } } This is what we were given, but I can't do anything with it inside the GUI editor. (Can't even get to the GUI editor). I have been staring at this for about an hour. Any ideas?

    Read the article

  • How to get a handle to all JCheckBox objects in order to loop?

    - by EmmyS
    I'm very new to Java and am having some issues looping through JCheckBoxes on a UI. The idea is that I have a bunch of checkboxes (not in a group because more than one can be selected.) When I click a JButton, I want to build a string containing the text from each selected checkbox. The issue I'm having is that our instructor told us that the checkboxes need to be created via a method, which means (see code below) that there isn't a discrete instance name for each checkbox. If there were, I could say something like if(checkBox1.isSelected()) { myString.append(checkBox.getText()); } That would repeat for checkBox2, checkBox3, and so on. But the method provided to us for adding checkboxes to a panel looks like this: public class CheckBoxPanel extends JPanel { private static final long serialVersionUID = 1L; public CheckBoxPanel(String title, String... options) { setBorder(BorderFactory.createTitledBorder(BorderFactory .createEtchedBorder(), title)); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // make one checkbox for each option for (String option : options) { JCheckBox b = new JCheckBox(option); b.setActionCommand(option); add(b); } } } This is called like this: toppingPanel = new CheckBoxPanel("Each Topping $1.50", "Tomato", "Green Pepper", "Black Olives", "Mushrooms", "Extra Cheese", "Pepperoni", "Sausage"); So I now have a panel that contains a border with the title "Each Topping $1.50", and 7 visible checkboxes. What I need to do is get a list of all the selected toppings. We are not supposed to use an ActionListener for each checkbox, but rather get the list when a button is clicked. I'm feeling really clueless here, but I just can't figure out how to get the isSelected property of the checkboxes when the individual checkboxes don't have instance names. Ideally I'd like to somehow add all the checkboxes to an array and loop through the array in the button's action listener to determine which ones are checked, but if I have to check each one individually I will. I just can't figure out how to refer to an individual checkbox when they've been created dynamically.

    Read the article

  • Gui problem after rewriting to MVC

    - by trevor_nise
    I'm practicing MVC style programming. I have a Mastermind game in a single file, working with no problems (maybe apart of the fact that "Check" button is invisible at start). http://paste.pocoo.org/show/226726/ But when I've rewritten it to model, view, controller files - when I click on empty Pin (that should be updated, and repainted with new color) - noting happens. Can anybody see any problems here ? I've tried placing repaint() in different places, but it simply does not work at all :/ Main : public class Main { public static void main(String[] args){ Model model = new Model(); View view = new View("Mastermind", 400, 590, model); Controller controller = new Controller(model, view); view.setVisible(true); } } Model : import java.util.Random; public class Model{ static final int LINE = 5, SCORE = 10, OPTIONS = 20; Pin pins[][] = new Pin[21][LINE]; int combination[] = new int[LINE]; int curPin = 0; int turn = 1; Random generator = new Random(); int repaintPin; boolean pinsRepaint=false; int pinsToRepaint; boolean isUpdate = true, isPlaying = true, isRowFull = false; static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516}; public Model(){ for ( int i=0; i < SCORE; i++ ){ for ( int j = 0; j < LINE; j++ ){ pins[i][j] = new Pin(20,0); pins[i][j].setPosition(j*50+30,510-i*50); pins[i+SCORE][j] = new Pin(8,0); pins[i+SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50); } } for ( int i=0; i < LINE; i++ ){ pins[OPTIONS][i] = new Pin( 20, i+2 ); pins[OPTIONS][i].setPosition( 370,i * 50 + 56); } } void fillHole(int color) { pins[turn-1][curPin].setColor(color+1); pinsRepaint = true; pinsToRepaint = turn; curPin = (curPin+1) % LINE; if (curPin == 0){ isRowFull = true; } pinsRepaint = false; pinsToRepaint = 0; } void check() { int junkPins[] = new int[LINE], junkCode[] = new int[LINE]; int pinCount = 0, pico = 0; for ( int i = 0; i < LINE; i++ ) { junkPins[i] = pins[turn-1][i].getColor(); junkCode[i] = combination[i]; } for ( int i = 0; i < LINE; i++ ){ if (junkPins[i]==junkCode[i]) { pins[turn+SCORE][pinCount].setColor(1); pinCount++; pico++; junkPins[i] = 98; junkCode[i] = 99; } } for ( int i = 0; i < LINE; i++ ){ for ( int j = 0; j < LINE; j++ ) if (junkPins[i]==junkCode[j]) { pins[turn+SCORE][pinCount].setColor(2); pinCount++; junkPins[i] = 98; junkCode[j] = 99; j = LINE; } } pinsRepaint = true; pinsToRepaint = turn + SCORE; pinsRepaint = false; pinsToRepaint=0; if ( pico == LINE ){ isPlaying = false; } else if ( turn >= 10 ){ isPlaying = false; } else{ curPin = 0; isRowFull = false; turn++; } } void combination() { for ( int i = 0; i < LINE; i++ ){ combination[i] = generator.nextInt(6) + 1; } } } class Pin{ private int color, X, Y, radius; public Pin(){ X = 0; Y = 0; radius = 0; color = 0; } public Pin( int r,int c ){ X = 0; Y = 0; radius = r; color = c; } public int getX(){ return X; } public int getY(){ return Y; } public int getRadius(){ return radius; } public void setRadius(int r){ radius = r; } public void setPosition( int x,int y ){ this.X = x ; this.Y = y ; } public void setColor( int c ){ color = c; } public int getColor() { return color; } } View: import java.awt.*; import javax.swing.*; public class View extends Frame{ Model model; JButton checkAnswer; private JPanel button; private static final Color COLORS[] = {Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)}; public View(String name, int w, int h, Model m){ model = m; setTitle( name ); setSize( w,h ); setResizable( false ); this.setLayout(new BorderLayout()); button = new JPanel(); button.setSize( new Dimension(400, 100)); button.setVisible(true); checkAnswer = new JButton("Check"); checkAnswer.setSize( new Dimension(200, 30)); button.add( checkAnswer ); this.add( button, BorderLayout.SOUTH); button.setVisible(true); } @Override public void paint( Graphics g ) { g.setColor( new Color(238, 238, 238)); g.fillRect( 0,0,400,590); for ( int i=0; i < model.pins.length; i++ ) { paintPins(model.pins[i][0],g); paintPins(model.pins[i][1],g); paintPins(model.pins[i][2],g); paintPins(model.pins[i][3],g); paintPins(model.pins[i][4],g); } } @Override public void update( Graphics g ) { if ( model.isUpdate ) { paint(g); } else { model.isUpdate = true; paintPins(model.pins[model.repaintPin-1][0],g); paintPins(model.pins[model.repaintPin-1][1],g); paintPins(model.pins[model.repaintPin-1][2],g); paintPins(model.pins[model.repaintPin-1][3],g); paintPins(model.pins[model.repaintPin-1][4],g); } } void repaintPins( int pin ) { model.repaintPin = pin; model.isUpdate = false; repaint(); } public void paintPins(Pin p, Graphics g ){ int X = p.getX(); int Y = p.getY(); int color = p.getColor(); int radius = p.getRadius(); int x = X-radius; int y = Y-radius; if (color > 0){ g.setColor( COLORS[color]); g.fillOval( x,y,2*radius,2*radius ); } else{ g.setColor( new Color(238, 238, 238) ); g.drawOval( x,y,2*radius-1,2*radius-1 ); } g.setColor( Color.black ); g.drawOval( x,y,2*radius,2*radius ); } } Controller: import java.awt.*; import java.awt.event.*; public class Controller implements MouseListener, ActionListener { private Model model; private View view; public Controller(Model m, View v){ model = m; view = v; view.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); view.addMouseListener(this); view.checkAnswer.addActionListener(this); model.combination(); } public void actionPerformed( ActionEvent e ) { if(e.getSource() == view.checkAnswer){ if(model.isRowFull){ model.check(); } } } public void mousePressed(MouseEvent e) { Point mouse = new Point(); mouse = e.getPoint(); if (model.isPlaying){ if (mouse.x > 350) { int button = 1 + (int)((mouse.y - 32) / 50); if ((button >= 1) && (button <= 5)){ model.fillHole(button); if(model.pinsRepaint){ view.repaintPins( model.pinsToRepaint ); } } } } } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }

    Read the article

  • how to execute two thread simultaneously in java swing?

    - by jcrshankar
    My aim is to select all the files named with MANI.txt which is present in their respective folders and then load path of the MANI.txt files different location in table. After I load the path in the table,I used to select needed path and modifiying those. To load the MANI.txt files taking more time,because it may present more than 30 times in my workspace or etc. until load the files I want to give alarm to the user with help of ProgessBar.Once the list size has been populated I need to disable ProgressBar. Could anyone please help me out on this? import java.awt.*; import javax.swing.*; import javax.swing.table.*; import java.awt.event.*; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class JTableHeaderCheckBox extends JFrame implements ActionListener { Object colNames[] = {"", "Path"}; Object[][] data = {}; DefaultTableModel dtm; JTable table; JButton but; java.util.List list; public void buildGUI() { dtm = new DefaultTableModel(data,colNames); table = new JTable(dtm); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); int vColIndex = 0; TableColumn col = table.getColumnModel().getColumn(vColIndex); int width = 10; col.setPreferredWidth(width); int vColIndex1 = 1; TableColumn col1 = table.getColumnModel().getColumn(vColIndex1); int width1 = 500; col1.setPreferredWidth(width1); JFileChooser chooser = new JFileChooser(); //chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle("Choose workSpace Path"); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){ System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile().getAbsolutePath()); } String path= chooser.getSelectedFile().getAbsolutePath(); File folder = new File(path); Here I need progress bar GatheringFiles ob = new GatheringFiles(); list=ob.returnlist(folder); for(int x = 0; x < list.size(); x++) { dtm.addRow(new Object[]{new Boolean(false),list.get(x).toString()}); } JPanel pan = new JPanel(); JScrollPane sp = new JScrollPane(table); TableColumn tc = table.getColumnModel().getColumn(0); tc.setCellEditor(table.getDefaultEditor(Boolean.class)); tc.setCellRenderer(table.getDefaultRenderer(Boolean.class)); tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener())); but = new JButton("REMOVE"); JFrame f = new JFrame(); pan.add(sp); but.move(650, 50); but.addActionListener(this); pan.add(but); f.add(pan); f.setSize(700, 100); f.pack(); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } class MyItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { Object source = e.getSource(); if (source instanceof AbstractButton == false) return; boolean checked = e.getStateChange() == ItemEvent.SELECTED; for(int x = 0, y = table.getRowCount(); x < y; x++) { table.setValueAt(new Boolean(checked),x,0); } } } public static void main (String[] args) { SwingUtilities.invokeLater(new Runnable(){ public void run(){ new JTableHeaderCheckBox().buildGUI(); } }); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==but) { System.err.println("table.getRowCount()"+table.getRowCount()); for(int x = 0, y = table.getRowCount(); x < y; x++) { if("true".equals(table.getValueAt(x, 0).toString())) { System.err.println(table.getValueAt(x, 0)); System.err.println(list.get(x).toString()); delete(list.get(x).toString()); } } } } public void delete(String a) { String delete = "C:"; System.err.println(a); try { File inFile = new File(a); if (!inFile.isFile()) { System.out.println("Parameter is not an existing file"); return; } //Construct the new file that will later be renamed to the original filename. File tempFile = new File(inFile.getAbsolutePath() + ".tmp"); BufferedReader br = new BufferedReader(new FileReader(inFile)); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String line = null; //Read from the original file and write to the new //unless content matches data to be removed. while ((line = br.readLine()) != null) { System.err.println(line); line = line.replace(delete, " "); pw.println(line); pw.flush(); } pw.close(); br.close(); //Delete the original file if (!inFile.delete()) { System.out.println("Could not delete file"); return; } //Rename the new file to the filename the original file had. if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener { protected CheckBoxHeader rendererComponent; protected int column; protected boolean mousePressed = false; public CheckBoxHeader(ItemListener itemListener) { rendererComponent = this; rendererComponent.addItemListener(itemListener); } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { rendererComponent.setForeground(header.getForeground()); rendererComponent.setBackground(header.getBackground()); rendererComponent.setFont(header.getFont()); header.addMouseListener(rendererComponent); } } setColumn(column); rendererComponent.setText("Check All"); setBorder(UIManager.getBorder("TableHeader.cellBorder")); return rendererComponent; } protected void setColumn(int column) { this.column = column; } public int getColumn() { return column; } protected void handleClickEvent(MouseEvent e) { if (mousePressed) { mousePressed=false; JTableHeader header = (JTableHeader)(e.getSource()); JTable tableView = header.getTable(); TableColumnModel columnModel = tableView.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = tableView.convertColumnIndexToModel(viewColumn); if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) { doClick(); } } } public void mouseClicked(MouseEvent e) { handleClickEvent(e); ((JTableHeader)e.getSource()).repaint(); } public void mousePressed(MouseEvent e) { mousePressed = true; } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } ****************** import java.io.File; import java.util.*; public class GatheringFiles { public static List returnlist(File folder) { List<File> list = new ArrayList<File>(); List<File> list1 = new ArrayList<File>(); getFiles(folder, list); return list; } private static void getFiles(File folder, List<File> list) { folder.setReadOnly(); File[] files = folder.listFiles(); for(int j = 0; j < files.length; j++) { if( "MANI.txt".equals(files[j].getName())) { list.add(files[j]); } if(files[j].isDirectory()) getFiles(files[j], list); } } }

    Read the article

  • Cnoverting application to MVC architecture

    - by terence6
    I'm practicing writing MVC applications. I have a Mastermind game, that I would like to rewrite as MVC app. I have divided my code to parts, but instead of working game I'm getting empty Frame and an error in "public void paint( Graphics g )". Error comes from calling this method in my view with null argument. But how to overcome this ? MVC was quite simple with swing but awt and it's paint methods are much more complicated. Code of working app : http://paste.pocoo.org/show/224982/ App divided to MVC : Main : public class Main { public static void main(String[] args){ Model model = new Model(); View view = new View("Mastermind", 400, 590, model); Controller controller = new Controller(model, view); view.setVisible(true); } } Controller : import java.awt.*; import java.awt.event.*; public class Controller implements MouseListener, ActionListener { private Model model; private View view; public Controller(Model m, View v){ model = m; view = v; view.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); view.addMouseListener(this); } public void actionPerformed( ActionEvent e ) { if(e.getSource() == view.checkAnswer){ if(model.isRowFull){ model.check(); } } } public void mousePressed(MouseEvent e) { Point mouse = new Point(); mouse = e.getPoint(); if (model.isPlaying){ if (mouse.x > 350) { int button = 1 + (int)((mouse.y - 32) / 50); if ((button >= 1) && (button <= 5)){ model.fillHole(button); } } } } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } View : import java.awt.*; import javax.swing.*; import java.awt.event.*; public class View extends Frame implements ActionListener { Model model; JButton checkAnswer; private JPanel button; static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516}; public View(String name, int w, int h, Model m){ model = m; setTitle( name ); setSize( w,h ); setResizable( false ); this.setLayout(new BorderLayout()); button = new JPanel(); button.setSize( new Dimension(400, 100)); button.setVisible(true); checkAnswer = new JButton("Check"); checkAnswer.addActionListener(this); checkAnswer.setSize( new Dimension(200, 30)); button.add( checkAnswer ); this.add( button, BorderLayout.SOUTH); button.setVisible(true); for ( int i=0; i < model.SCORE; i++ ){ for ( int j = 0; j < model.LINE; j++ ){ model.pins[i][j] = new Pin(20,0); model.pins[i][j].setPosition(j*50+30,510-i*50); model.pins[i+model.SCORE][j] = new Pin(8,0); model.pins[i+model.SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50); } } for ( int i=0; i < model.LINE; i++ ){ model.pins[model.OPTIONS][i] = new Pin( 20, i+2 ); model.pins[model.OPTIONS][i].setPosition( 370,i * 50 + 56); } model.combination(); model.paint(null); } public void actionPerformed( ActionEvent e ) { } } Model: import java.awt.*; public class Model extends Frame{ static final int LINE = 5, SCORE = 10, OPTIONS = 20; Pin pins[][] = new Pin[21][LINE]; int combination[] = new int[LINE]; int curPin = 0; int turn = 1; int repaintPin; boolean isUpdate = true, isPlaying = true, isRowFull = false; public Model(){ } void fillHole(int color) { pins[turn-1][curPin].setColor(color+1); repaintPins( turn ); curPin = (curPin+1) % LINE; if (curPin == 0){ isRowFull = true; } } public void paint( Graphics g ) { g.setColor( new Color(238, 238, 238)); g.fillRect( 0,0,400,590); for ( int i=0; i < pins.length; i++ ) { pins[i][0].paint(g); pins[i][1].paint(g); pins[i][2].paint(g); pins[i][3].paint(g); pins[i][4].paint(g); } } public void update( Graphics g ) { if ( isUpdate ) { paint(g); } else { isUpdate = true; pins[repaintPin-1][0].paint(g); pins[repaintPin-1][1].paint(g); pins[repaintPin-1][2].paint(g); pins[repaintPin-1][3].paint(g); pins[repaintPin-1][4].paint(g); } } void repaintPins( int pin ) { repaintPin = pin; isUpdate = false; repaint(); } void check() { int junkPegs[] = new int[LINE], junkCode[] = new int[LINE]; int pegCount = 0, pico = 0; for ( int i = 0; i < LINE; i++ ) { junkPegs[i] = pins[turn-1][i].getColor(); junkCode[i] = combination[i]; } for ( int i = 0; i < LINE; i++ ){ if (junkPegs[i]==junkCode[i]) { pins[turn+SCORE][pegCount].setColor(1); pegCount++; pico++; junkPegs[i] = 98; junkCode[i] = 99; } } for ( int i = 0; i < LINE; i++ ){ for ( int j = 0; j < LINE; j++ ) if (junkPegs[i]==junkCode[j]) { pins[turn+SCORE][pegCount].setColor(2); pegCount++; junkPegs[i] = 98; junkCode[j] = 99; j = LINE; } } repaintPins( turn+SCORE ); if ( pico == LINE ){ isPlaying = false; } else if ( turn >= 10 ){ isPlaying = false; } else{ curPin = 0; isRowFull = false; turn++; } } void combination() { for ( int i = 0; i < LINE; i++ ){ combination[i] = 1 + (int)(Math.random()*5); System.out.print(i+","); } } } class Pin{ private int color, X, Y, radius; private static final Color COLORS[] = { Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)}; public Pin(){ X = 0; Y = 0; radius = 0; color = 0; } public Pin( int r,int c ){ X = 0; Y = 0; radius = r; color = c; } public void paint( Graphics g ){ int x = X-radius; int y = Y-radius; if (color > 0){ g.setColor( COLORS[color]); g.fillOval( x,y,2*radius,2*radius ); } else{ g.setColor( new Color(238, 238, 238) ); g.drawOval( x,y,2*radius-1,2*radius-1 ); } g.setColor( Color.black ); g.drawOval( x,y,2*radius,2*radius ); } public void setPosition( int x,int y ){ this.X = x ; this.Y = y ; } public void setColor( int c ){ color = c; } public int getColor() { return color; } } Any clues on how to overcome this would be great. Have I divided my code improperly ?

    Read the article

  • Converting application to MVC architecture

    - by terence6
    I'm practicing writing MVC applications. I have a Mastermind game, that I would like to rewrite as MVC app. I have divided my code to parts, but instead of working game I'm getting empty Frame and an error in "public void paint( Graphics g )". Error comes from calling this method in my view with null argument. But how to overcome this ? MVC was quite simple with swing but awt and it's paint methods are much more complicated. Code of working app : http://paste.pocoo.org/show/224982/ App divided to MVC : Main : public class Main { public static void main(String[] args){ Model model = new Model(); View view = new View("Mastermind", 400, 590, model); Controller controller = new Controller(model, view); view.setVisible(true); } } Controller : import java.awt.*; import java.awt.event.*; public class Controller implements MouseListener, ActionListener { private Model model; private View view; public Controller(Model m, View v){ model = m; view = v; view.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); view.addMouseListener(this); } public void actionPerformed( ActionEvent e ) { if(e.getSource() == view.checkAnswer){ if(model.isRowFull){ model.check(); } } } public void mousePressed(MouseEvent e) { Point mouse = new Point(); mouse = e.getPoint(); if (model.isPlaying){ if (mouse.x > 350) { int button = 1 + (int)((mouse.y - 32) / 50); if ((button >= 1) && (button <= 5)){ model.fillHole(button); } } } } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } View : import java.awt.*; import javax.swing.*; import java.awt.event.*; public class View extends Frame implements ActionListener { Model model; JButton checkAnswer; private JPanel button; static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516}; public View(String name, int w, int h, Model m){ model = m; setTitle( name ); setSize( w,h ); setResizable( false ); this.setLayout(new BorderLayout()); button = new JPanel(); button.setSize( new Dimension(400, 100)); button.setVisible(true); checkAnswer = new JButton("Check"); checkAnswer.addActionListener(this); checkAnswer.setSize( new Dimension(200, 30)); button.add( checkAnswer ); this.add( button, BorderLayout.SOUTH); button.setVisible(true); for ( int i=0; i < model.SCORE; i++ ){ for ( int j = 0; j < model.LINE; j++ ){ model.pins[i][j] = new Pin(20,0); model.pins[i][j].setPosition(j*50+30,510-i*50); model.pins[i+model.SCORE][j] = new Pin(8,0); model.pins[i+model.SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50); } } for ( int i=0; i < model.LINE; i++ ){ model.pins[model.OPTIONS][i] = new Pin( 20, i+2 ); model.pins[model.OPTIONS][i].setPosition( 370,i * 50 + 56); } model.combination(); model.paint(null); } public void actionPerformed( ActionEvent e ) { } } Model: import java.awt.*; public class Model extends Frame{ static final int LINE = 5, SCORE = 10, OPTIONS = 20; Pin pins[][] = new Pin[21][LINE]; int combination[] = new int[LINE]; int curPin = 0; int turn = 1; int repaintPin; boolean isUpdate = true, isPlaying = true, isRowFull = false; public Model(){ } void fillHole(int color) { pins[turn-1][curPin].setColor(color+1); repaintPins( turn ); curPin = (curPin+1) % LINE; if (curPin == 0){ isRowFull = true; } } public void paint( Graphics g ) { g.setColor( new Color(238, 238, 238)); g.fillRect( 0,0,400,590); for ( int i=0; i < pins.length; i++ ) { pins[i][0].paint(g); pins[i][1].paint(g); pins[i][2].paint(g); pins[i][3].paint(g); pins[i][4].paint(g); } } public void update( Graphics g ) { if ( isUpdate ) { paint(g); } else { isUpdate = true; pins[repaintPin-1][0].paint(g); pins[repaintPin-1][1].paint(g); pins[repaintPin-1][2].paint(g); pins[repaintPin-1][3].paint(g); pins[repaintPin-1][4].paint(g); } } void repaintPins( int pin ) { repaintPin = pin; isUpdate = false; repaint(); } void check() { int junkPegs[] = new int[LINE], junkCode[] = new int[LINE]; int pegCount = 0, pico = 0; for ( int i = 0; i < LINE; i++ ) { junkPegs[i] = pins[turn-1][i].getColor(); junkCode[i] = combination[i]; } for ( int i = 0; i < LINE; i++ ){ if (junkPegs[i]==junkCode[i]) { pins[turn+SCORE][pegCount].setColor(1); pegCount++; pico++; junkPegs[i] = 98; junkCode[i] = 99; } } for ( int i = 0; i < LINE; i++ ){ for ( int j = 0; j < LINE; j++ ) if (junkPegs[i]==junkCode[j]) { pins[turn+SCORE][pegCount].setColor(2); pegCount++; junkPegs[i] = 98; junkCode[j] = 99; j = LINE; } } repaintPins( turn+SCORE ); if ( pico == LINE ){ isPlaying = false; } else if ( turn >= 10 ){ isPlaying = false; } else{ curPin = 0; isRowFull = false; turn++; } } void combination() { for ( int i = 0; i < LINE; i++ ){ combination[i] = 1 + (int)(Math.random()*5); System.out.print(i+","); } } } class Pin{ private int color, X, Y, radius; private static final Color COLORS[] = { Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)}; public Pin(){ X = 0; Y = 0; radius = 0; color = 0; } public Pin( int r,int c ){ X = 0; Y = 0; radius = r; color = c; } public void paint( Graphics g ){ int x = X-radius; int y = Y-radius; if (color > 0){ g.setColor( COLORS[color]); g.fillOval( x,y,2*radius,2*radius ); } else{ g.setColor( new Color(238, 238, 238) ); g.drawOval( x,y,2*radius-1,2*radius-1 ); } g.setColor( Color.black ); g.drawOval( x,y,2*radius,2*radius ); } public void setPosition( int x,int y ){ this.X = x ; this.Y = y ; } public void setColor( int c ){ color = c; } public int getColor() { return color; } } Any clues on how to overcome this would be great. Have I divided my code improperly ?

    Read the article

  • Java Swing: How to add a CellRenderer for displaying a Date?

    - by HansDampf
    I have a Table: public class AppointmentTableModel extends AbstractTableModel { private int columns; private int rows; ArrayList<Appointment> appointments;... So each row of the table contains one Appointment. public class Appointment { private Date date; private Sample sample; private String comment; private ArrayList<Action> history; public Appointment(Date date, Sample sample, String comment) { this.date = date; this.sample = sample; this.comment = comment; this.history = new ArrayList<Action>(); } public Object getByColumn(int columnIndex) { switch (columnIndex) { case 0: return date;//Date: dd:mm:yyyy case 1: return date;//Time mm:hh case 2: return sample;//sample.getID() int (sampleID) case 3: return sample;//sample.getNumber string (telephone number) case 4: return sample;//sample.getName string (name of the person) case 5: return history;//newst element in history as a string case 6: return comment;//comment as string } return null; I added in comments what this one is going to mean. How would I create CellRenderers to display it like this. table.getColumnModel().getColumn(1).setCellRenderer(new DateRenderer()); I also want to add the whole row to be painted in red when the date is later then the current date. And then another column that holds a JButton to open up another screen with the corresponding Appointment as parameter.

    Read the article

< Previous Page | 5 6 7 8 9 10  | Next Page >