Search Results

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

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

  • How to send audio data from Java Applet to Rails controller

    - by cooldude
    Hi, I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save. So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR : LAVF_header: av_open_input_stream() failed while playing with the mplayer. Here is the Java Code: package networksocket; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JApplet; import java.net.*; import java.io.*; import java.awt.event.*; import java.awt.*; import java.sql.*; import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.util.Properties; import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager; import sun.awt.HorizBagLayout; import sun.awt.VerticalBagLayout; import sun.misc.BASE64Encoder; /** * * @author mukand */ public class Urlconnection extends JApplet implements ActionListener { /** * Initialization method that will be called after the applet is loaded * into the browser. */ public BufferedInputStream in; public BufferedOutputStream out; public String line; public FileOutputStream file; public int bytesread; public int toread=1024; byte b[]= new byte[toread]; public String f="FINISH"; public String match; public File fileopen; public JTextArea jTextArea; public Button refreshButton; public HttpURLConnection urlConn; public URL url; OutputStreamWriter wr; BufferedReader rd; @Override public void init() { // TODO start asynchronous download of heavy resources //textField= new TextField("START"); //getContentPane().add(textField); JPanel p = new JPanel(); jTextArea= new JTextArea(1500,1500); p.setLayout(new GridLayout(1,1, 1,1)); p.add(new JLabel("Server Details")); p.add(jTextArea); Container content = getContentPane(); content.setLayout(new GridBagLayout()); // Used to center the panel content.add(p); jTextArea.setLineWrap(true); refreshButton = new java.awt.Button("Refresh"); refreshButton.reshape(287,49,71,23); refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12)); refreshButton.addActionListener(this); add(refreshButton); Properties properties = System.getProperties(); properties.put("http.proxyHost", "netmon.iitb.ac.in"); properties.put("http.proxyPort", "80"); } @Override public void actionPerformed(ActionEvent e) { try { url = new URL("http://localhost:3000/audio/audiorecieve"); urlConn = (HttpURLConnection)url.openConnection(); //String login = "mukandagarwal:rammstein$"; //String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes()); //urlConn.setRequestProperty("Proxy-Authorization",login); urlConn.setRequestMethod("POST"); // urlConn.setRequestProperty("Content-Type", //"application/octet-stream"); //urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded"); //urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded"); //urlConn.setRequestProperty("Content-Length", "" + // Integer.toString(urlParameters.getBytes().length)); urlConn.setRequestProperty("Content-Language", "UTF-8"); urlConn.setDoOutput(true); urlConn.setDoInput(true); byte bread[]=new byte[2048]; int iread; char c; String data=URLEncoder.encode("key1", "UTF-8")+ "="; //String data="key1="; FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3"); while((iread=fileread.read(bread))!=-1) { //data+=(new String()); /*for(int i=0;i<iread;i++) { //c=(char)bread[i]; System.out.println(bread[i]); }*/ data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));// // data+=new String(bread,iread); } //urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length)); System.out.println(data); //data+=URLEncoder.encode("mukand", "UTF-8"); //data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); //data="key1="; wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream(); //if((iread=fileread.read(bread))!=-1) // wr.write(bread,0,iread); wr.write(data); wr.flush(); fileread.close(); jTextArea.append("Send"); // Get the response rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while ((line = rd.readLine()) != null) { jTextArea.append(line); } wr.close(); rd.close(); //jTextArea.append("click"); } catch (MalformedURLException ex) { Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void start() { } @Override public void stop() { } @Override public void destroy() { } // TODO overwrite start(), stop() and destroy() methods } Here is the Rails controller function for recieving: def audiorecieve puts "///////////////////////////////////////******RECIEVED*******////" puts params[:key1]#+" "+params[:key2] data=params[:key1] #request.env('RAW_POST_DATA') file=File.new("audiodata.ogg", 'w') file.write(data) file.flush file.close puts "////**************DONE***********//////////////////////" end Please reply quickly

    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 to sort JTable by providing column index externally.

    - by user345940
    I would like to implement sorting on JTable by providing column index externally in program. Here is my sample code in which i have initialize JTable, Add one Column and 30 rows to JTable. After rows has been added i am sorting JTable by providing column index 0 but i could not get sorted data. how can i get my first column in sorted order? what's wrong with my code. **Why sortCTableonColumnIndex() method could not sort data for specify column index? ` public class Test { private JTable oCTable; private DefaultTableModel oDefaultTableModel; private JScrollPane oPane; private JTableHeader oTableHeader; private TableRowSorter sorter; public void adddata() { for (int i = 0; i < 30; i++) { Object[] row = new Object[1]; String sValueA = "A"; String sValueB = "A"; row[0] = ""; if (i % 2 == 0) { if (i < 15) { sValueA = sValueA + sValueA; row[1] = sValueA; } else { if (i == 16) { sValueB = "D"; row[1] = sValueA; } else { sValueB = sValueB + sValueB; row[1] = sValueA; } } } else { if (i < 15) { sValueB = sValueB + sValueB; row[1] = sValueB; } else { if (i == 17) { sValueB = "C"; row[1] = sValueB; } else { sValueB = sValueB + sValueB; row[1] = sValueB; } } } } } public void createTable() { oCTable = new JTable(); oDefaultTableModel = new DefaultTableModel(); oCTable.setModel(oDefaultTableModel); oTableHeader = oCTable.getTableHeader(); oCTable.setAutoResizeMode(oCTable.AUTO_RESIZE_OFF); oCTable.setFillsViewportHeight(true); JTable oTable = new LineNumberTable(oCTable); oPane = new JScrollPane(oCTable); oPane.setRowHeaderView(oTable); JPanel oJPanel = new JPanel(); oJPanel.setLayout(new BorderLayout()); oJPanel.add(oPane, BorderLayout.CENTER); JDialog oDialog = new JDialog(); oDialog.add(oJPanel); oDialog.setPreferredSize(new Dimension(500, 300)); oDialog.pack(); oDialog.setVisible(true); } public void insert() { oDefaultTableModel.addColumn("Name"); int iColumnPlace = ((DefaultTableModel) oCTable.getModel()).findColumn("Name"); CellRendererForRowHeader oCellRendererForRowHeader = new CellRendererForRowHeader(); TableColumn Column = oCTable.getColumn(oTableHeader.getColumnModel().getColumn(iColumnPlace).getHeaderValue()); Column.setPreferredWidth(300); Column.setMaxWidth(300); Column.setMinWidth(250); Column.setCellRenderer(oCellRendererForRowHeader); for (int i = 0; i < 30; i++) { Object[] row = new Object[1]; String sValueA = "A"; if (i % 2 == 0) { if (i < 15) { sValueA = sValueA + "a"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } else { if (i == 16) { sValueA = sValueA + "b"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } else { sValueA = sValueA + "c"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } } } else { if (i < 15) { sValueA = sValueA + "d"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } else { if (i == 17) { sValueA = sValueA + "e"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } else { sValueA = sValueA + "f"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } } } } } public void showTable() { createTable(); insert(); sortCTableonColumnIndex(0, true); } public void sortCTableonColumnIndex(int iColumnIndex, boolean bIsAsc) { sorter = new TableRowSorter(oDefaultTableModel); List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>(); if (bIsAsc) { sortKeys.add(new RowSorter.SortKey(iColumnIndex, SortOrder.ASCENDING)); } else { sortKeys.add(new RowSorter.SortKey(iColumnIndex, SortOrder.DESCENDING)); } sorter.setSortKeys(sortKeys); oDefaultTableModel.fireTableStructureChanged(); oCTable.updateUI(); } public static void main(String[] argu) { Test oTest = new Test(); oTest.showTable(); } class CellRendererForRowHeader extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = null; try { label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (column == 0) { label.setBackground(new JLabel().getBackground()); label.setForeground(Color.BLACK); } } catch (RuntimeException ex) { } return label; } } class LineNumberTable extends JTable { private JTable mainTable; public LineNumberTable(JTable table) { super(); mainTable = table; setAutoCreateColumnsFromModel(false); setModel(mainTable.getModel()); setAutoscrolls(false); addColumn(new TableColumn()); getColumnModel().getColumn(0).setCellRenderer(mainTable.getTableHeader().getDefaultRenderer()); getColumnModel().getColumn(0).setPreferredWidth(40); setPreferredScrollableViewportSize(getPreferredSize()); } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public Object getValueAt(int row, int column) { return Integer.valueOf(row + 1); } @Override public int getRowHeight(int row) { return mainTable.getRowHeight(); } } } `

    Read the article

  • Why a Swing app stops my Java servlet ?

    - by Frank
    I have a Swing runnable app which updates messages, then I have a Java servlet that gets messages from Paypal IPN (Instant Payment Notification), when the servlet starts up, in the init(), I starts the Swing runnable app which opens a desktop window, but 30 minutes later an error in the Swing caused the servlet to stop, how can that happen ? Because the runnable is running on it's own thread, servlet started that thread, why an error in that thread will cause the servlet to stop ? public class License_Manager extends JPanel implements Runnable { License_Manager() { Do_GUI(); ... start(); } public static void main(String[] args) { // Schedule a job for the event-dispatching thread : creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } }); } } public class PayPal_Servlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); License_Manager.main(null); } protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { } } And besides the error don't even have anything to do with my code, it looks like this : Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 17 = 0 at java.util.Vector.elementAt(Vector.java:427) at javax.swing.DefaultListModel.getElementAt(DefaultListModel.java:70) at javax.swing.plaf.basic.BasicListUI.paintCell(BasicListUI.java:191) at javax.swing.plaf.basic.BasicListUI.paintImpl(BasicListUI.java:304) at javax.swing.plaf.basic.BasicListUI.paint(BasicListUI.java:227) at javax.swing.plaf.ComponentUI.update(ComponentUI.java:143) at javax.swing.JComponent.paintComponent(JComponent.java:763) at javax.swing.JComponent.paint(JComponent.java:1029) at javax.swing.JComponent.paintChildren(JComponent.java:864) at javax.swing.JComponent.paint(JComponent.java:1038) at javax.swing.JViewport.paint(JViewport.java:747) at javax.swing.JComponent.paintChildren(JComponent.java:864) at javax.swing.JComponent.paint(JComponent.java:1038) at javax.swing.JComponent.paintToOffscreen(JComponent.java:5124) at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:278) at javax.swing.RepaintManager.paint(RepaintManager.java:1220) at javax.swing.JComponent._paintImmediately(JComponent.java:5072) at javax.swing.JComponent.paintImmediately(JComponent.java:4882) at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:803) at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714) at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694) at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    Read the article

  • How to right-justify icon in a JLabel?

    - by geoffreyzheng
    For a JLabel with icon, if you setHorizontalTextPosition(SwingConstants.LEADING), the icon is painted right after text, no matter how wide the label is. This is particularly bad for a list, as the icons would be all over the place depending on how long the text is for each item. I traced the code and it seems to be that in SwingUtilities#layoutCompoundLabelImpl, text width is simply set to SwingUtilities2.stringWidth(c, fm, text), and icon x is set to follow text without considering label width. Here is the simplest case: import java.awt.*; import javax.swing.*; public class TestJLabelIcon { public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { public void run() { JLabel c = new JLabel("abc"); c.setHorizontalTextPosition(SwingConstants.LEADING); c.setHorizontalAlignment(SwingConstants.LEADING); c.setIcon(UIManager.getIcon("FileChooser.detailsViewIcon")); c.setBorder(BorderFactory.createLineBorder(Color.RED)); JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.getContentPane().add(c); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } You can see that label always fills the frame but icon stays put. You'll get the mirror problem if you set both arguments to TRAILING. I know I can override the UI, or use a JPanel, etc. I just wonder if I'm missing something simple in JLabel. If not, it seems like a Java bug. FYI this is jdk1.6.0_06 on Windows XP.

    Read the article

  • How to use Guice in Swing application

    - by Gerco Dries
    I have a Swing application that I would like to convert from spaghetti to using dependency injection with Guice. Using Guice to provide services like configuration and task queues is going great but I'm now starting on the GUI of the app and am unsure of how to proceed. The application is basically a JFrame with a bunch of tabs in a JTabbedPane. Each of the tabs is a separate JPanel subclass that lays out the various components and needs services to perform actions when certain buttons are pressed. In the current application, this looks somewhat like this: @Inject public MainFrame(SomeService service, Executor ex, Configuration config) { tabsPane = new JTabbedPane(); // Create the panels for each tab and add them to the tabbedpane somePanel = new SomeTabPanel(service, ex, config); tabsPane.addTab("Panel 1", somePanel); someOtherPanel = new SomeOtherTabPanel(service, ex, config); tabsPane.addTab("Panel 2", someOtherPanel); ... do more stuff } Obviously, this doesn't exactly follow DI best practices. I don't want to have to @Inject the tabs because that would get me a constructor with dozens of parameters. I do want to use Guice to inject the required dependencies into whatever tab objects I need without me having to pass all of those dependencies to the tab constructors. All of the dependencies for the tab objects are services that my Module knows about, so basically all I think I want to do is to ask Guice for the required objects and have them constructed for me.

    Read the article

  • JLabel not greyed out when disabled, when HTML text displayed

    - by bguiz
    How do I get a JLabel displaying a HTML string to appear greyed out (which is the behaviour of JLabels that don't display HTML text)? Is there another way than actually changing the colour myself by modifying the foreground property? JLabel label1 = new JLabel("Normal text"); JLabel label2 = new JLabel("<html>HTML <b>text</b>"); // Both labels are now black in colour label1.setEnabled(false); label2.setEnabled(false); // label1 is greyed out, label2 is still black in colour Thank you very much for all of your responses. From what I gather, it seems that Java doesn't support automatic greying out of JLabels when they use HTML text. Suraj's solution has come closest to the fix considering the limitations. I have however, tried a different out-of-the box approach, where I have put the HTML text JLabels inside of an inner JPanel and did this: mInnerPanel.setEnabled(shouldShow); //shouldShow is a boolean value Which hasn't worked. Any suggestions for this way? EDIT: Added implemented solution.

    Read the article

  • Should I use a collection here?

    - by Eva
    So I have code set up like this: public interface IInterface { public void setField(Object field); } public abstract class AbstractClass extends JPanel implements IInterface { private Object field_; public void setField(Object field) { field_ = field; } } public class ClassA extends AbstractClass { public ClassA() { // unique ClassA constructor stuff } public Dimension getPreferredSize() { return new Dimension(1, 1); } } public class ClassB extends AbstractClass { public ClassB() { // unique ClassB constructor stuff } public Dimension getPreferredSize() { return new Dimension(42, 42); } } public class ConsumerA { public ConsumerA(Collection<AbstractClass> collection) { for (AbstractClass abstractClass : collection) { abstractClass.setField(this); abstractClass.repaint(); } } } All hunky-dory so far, until public class ConsumerB { // Option 1 public ConsumerB(ClassA a, ClassB b) { methodThatOnlyTakesA(a); methodThatOnlyTakesB(b); } // Option 2 public ConsumerB(Collection<AbstractClass> collection) { for (IInterface i : collection) { if (i instanceof ClassA) { methodThatOnlyTakesA((ClassA) i); else if (i instanceof ClassB) { methodThatOnlyTakesB((ClassB) i); } } } } public class UsingOption1 { public static void main(String[] args) { ClassA a = new ClassA(); ClassB b = new ClassB(); Collection<AbstractClass> collection = Arrays.asList(a, b); ConsumerA consumerA = new ConsumerA(collection); ConsumerB consumerB = new ConsumerB(a, b); } } public class UsingOption2 { public static void main(String[] args) { Collection<AbstractClass> collection = Arrays.asList(new ClassA(), new ClassB()); ConsumerA = new ConsumerA(collection); ConsumerB = new ConsumerB(collection); } } With a lot more classes extending AbstractClass, both options get unwieldly. Option1 would make the constructor of ConsumerB really long. Also UsingOption1 would get long too. Option2 would have way more if statements than I feel comfortable with. Is there a viable Option3? If it helps, ClassA and ClassB have all the same methods, they're just implemented differently. Thanks for slogging through my code!

    Read the article

  • Setting minimum size limit for a window in java swing

    - by shadyabhi
    I have a JFrame which has 3 JPanels in GridBagLayout.. Now, when I minimize a windows, after a certain limit, the third JPanel tends to disappear. I tried setting minimizing size of JFrame using setMinimumSize(new Dimension(int,int)) but no success. The windows can still be minimized. So, I actually want to make a threshhold, that my window cannot be minimized after a certain limit. How can I do so? Code:- import java.awt.Dimension; import javax.swing.JFrame; public class JFrameExample { public static void main(String[] args) { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setMinimumSize(new Dimension(400, 400)); frame.setVisible(true); } } Also: shadyabhi@shadyabhi-desktop:~/java$ java --showversion java version "1.5.0" gij (GNU libgcj) version 4.4.1 Copyright (C) 2007 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Usage: gij [OPTION] ... CLASS [ARGS] ... to invoke CLASS.main, or gij -jar [OPTION] ... JARFILE [ARGS] ... to execute a jar file Try `gij --help' for more information. shadyabhi@shadyabhi-desktop:~/java$ Gives me output like

    Read the article

  • How to draw a circle in java with a radius and points around the edge

    - by windopal
    Hi, I'm really stuck on how to go about programming this. I need to draw a circle within a JFrame with a radius and points around the circumference. i can mathematically calculate how to find the coordinates of the point around the edge but i cant seem to be able to program the circle. I am currently using a Ellipse2D method but that doesn't seem to work and doesn't return a radius, as under my understanding, it doesn't draw the circle from the center rather from a starting coordinate using a height and width. My current code is on a separate frame but i need to add it to my existing frame. import java.awt.*; import javax.swing.*; import java.awt.geom.*; public class circle extends JFrame { public circle() { super("circle"); setSize(410, 435); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Panel sp = new Panel(); Container content = getContentPane(); content.add(sp); setContentPane(content); setVisible(true); } public static void main (String args[]){ circle sign = new circle(); } } class Panel extends JPanel { public void paintComponent(Graphics comp) { super.paintComponent(comp); Graphics2D comp2D = (Graphics2D) comp; comp2D.setColor(Color.red); Ellipse2D.Float sign1 = new Ellipse2D.Float(0F, 0F, 350F, 350F); comp2D.fill(sign1); } }

    Read the article

  • How to use a linkedList and multiple classes with my Java GUI

    - by Asj
    How should I use a linked list with my GUI program? The program is supposed to have blocks with textareas and dropdown menus. The number of blocks depends on the number of times the user presses a button. It's supposed to be possible to put blocks within blocks. I want to store the information created, using a linked list and then saving to a file. I'm thinking, for the sub blocks, there would be linked lists within the linked list. Should I use Java.util.LinkedList? How do I add the information? A Node class? Should that be in a separate file? I started to try sitting up a linked list, but it's getting me confused. I'm still unsure about how a person is supposed to make GUI's. I've only seen really simple GUI's. Can anyone tell me how I should arrange things? At the moment, I have three files, one for the main GUI window, one for the question blocks to be inserted within that, and one for some tools to use within those two files to make the code easier to understand. But, there seems to be something wrong with the question block file, because I've been making the background white for each JPanel, and there's a gray outline around the question blocks when I run the program. I probably shouldn't paste a ton of code here... These are my files: http://asj127.webs.com/BuildAssessmentWindow.java http://asj127.webs.com/QuestionBlock.java http://asj127.webs.com/JPanelTools.java

    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

  • Implementing Drag and Drop using MouseListener for custom Components

    - by Chris Lieb
    I am working on a school assignment that requires me to be able to pick up a tile, drag it to a location, then drop it there. I was able to get this working using TransferHandler and a bunch of stuff from the dnd package, but this is not an acceptable way to perform this action for this assignment according to the professor. So, I am trying to achieve the same effect using the MouseListener interface. The basic setup is this: I have a JPanel-derived class called LocationView that contains JLabel-dervived instances of TileView. I need to get events that give me the LocationView that has the mouse pressed on and the LocationView that has the mouse released on. I am proxying mouse events through the TileView to its containing LocationView so that I can properly handle the mousePressed event. I added System.out.println()'s to the mouse listeners for mousePressed and mouseReleased to both LocationView and TileView so that I could observe the events that were being generated. To my surprise, pressing the mouse on Tile A in Location A, then dragging to Location B and releasing would generate a mouse released event for both Tile A and Location A, but not for Location B. I need the mouse released event triggered for only Location B. To try to work around this, I tried implementing a glass pane based off of the FinalGlassPane found at http://weblogs.java.net/blog/2006/09/20/well-behaved-glasspane. After adding the glass pane and adding an event listener for it, I can see that the mouse events are indeed filtering through the glass pane, but the mouse released event is still only being called on the item the mouse was clicked on. Is there a way to have mousePressed and mouseReleased events associated with the same drag action be called on separate components?

    Read the article

  • JCombobox containing enum values inside a table

    - by Edan
    Hello, I have a class containing Enum with values. (names) In other class I would like to enter inside a table a cell type of JCombobox that will use these enums values. my problem is to combain between string values and the enum. for example the enum class: enum item_Type {entree, main_Meal, Dessert, Drink} for example the table class: setTitle("Add new item" ); setSize(300, 80); setBackground( Color.gray ); // Create a panel to hold all other components topPanel = new JPanel(); topPanel.setLayout( new BorderLayout() ); getContentPane().add( topPanel ); //new JComboBox(item_Type.values()); JComboBox aaa = new JComboBox(); aaa = new JComboBox(item_Type.values()); TableColumn sportColumn = table.getColumnModel().getColumn(2); // Create columns names String columnNames[] = {"Item Description", "Item Type", "Item Price"}; // Create some data String dataValues[][] = {{ "0", aaa, "0" }}; // Create a new table instance table = new JTable( dataValues, columnNames ); // Add the table to a scrolling pane scrollPane = new JScrollPane( table ); topPanel.add( scrollPane, BorderLayout.CENTER ); I know that at the dataValues array I cant use aaa (the enum jcombobox). How can I do that? thanks in advance.

    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

  • Strategy game programming in Java, how the map and unit classes should work/relate each other.

    - by Gabriel A. Zorrilla
    As a way of learning Java i'm doing a little strategy game. You have a game map and military units. The gamemap and the units are Jpanels which are binded together in another class called GameWindow, which has a JLayeredPane where the gamepap is below the units. Every time i click a unit (and therefore, the JPane) I can get the unit's information. The problem comes when i want to move a unit... each unit is self drawn inside it's Jpanel, how do i represent the change in position over the gamemap? I'm thinking about reloading the whole game window based on a position change of a unit (because the JPAnels that represent the units are created in the GameWindow, not drawn in the gamemap). Another more elegant option, should be repainting the whole map, with the units. But that way the units would lose it's status of objects (no more JPAnels, just being drawn in the gamemap paint() method), and how would i tell if one unit is clicked? I dont know how people with more experience in games handle the class structure in strategy games. I believe i have the right structure (map, game units, each one an object) but I'm having difficulties making it work together. Here is a snapshot of the map with a couple of units:

    Read the article

  • Java KeyListener in separate class

    - by Chris
    So I have my main class here, where basically creates a new jframe and adds a world object to it. The world object is basically where all drawing and keylistening would take place... public class Blobs extends JFrame{ public Blobs() { super("Blobs :) - By Chris Tanaka"); setVisible(true); setResizable(false); setSize(1000, 1000); setIgnoreRepaint(true); setDefaultCloseOperation(EXIT_ON_CLOSE); add(new World()); } public static void main(String[] args) { new Blobs(); } } How exactly would you get key input from the world class? (So far I have my world class extending a jpanel and implementing a keylistener. In the constructor i addKeyListener(this). I also have these methods since they are auto implemented: public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_W) System.out.println("Hi"); } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} However this does not seem to work?

    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

  • How do I integrate GUI elements from different classes at runtime?

    - by thefourthdoctor
    I'm trying to "future-proof" an application that I'm writing by splitting out those elements that are likely to change over time. In my application I need to be able to adapt to changes in the output format (e.g. today I output to a CSV file, in the future I may need to output directly to a SQL Server database, or to a web service, etc.). I'm handling this by defining an abstract class ("OutputProvider") that I will subclass for each individual case. The one aspect of this that has me stumped is how to provide a configuration GUI that is specific to each concrete class. I have a settings dialog with a tab for output configuration. On that tab I intend to provide a drop-down to select the provider and a JPanel beneath it to hold the contents of the provider-specific GUI. How do I get the right GUI in that panel at runtime and have it behave correctly with respect to events? Also, a bonus would be if there was a way to do this such that in order to add support for new providers I could simply provide a new jar or class file to be dropped in a specific folder and the application could pick that up at startup. I'm using NetBeans and Swing.

    Read the article

  • Problem in setting backgound color to my TreeCellRenderer

    - by Sunil Kumar Sahoo
    Hi I have cretaed my own renderer. I want the back ground should be blue. I have set background color as blue also. But I donot know what is tha problem that the background color of my renderer always seems to be white. I have post the code. please help where I am wrong so that the background color becomes white. class CheckTreeCellRenderer extends JPanel implements TreeCellRenderer { private CheckTreeSelectionModel selectionModel; private MyRenderer delegate; private TristateCheckBox checkBox = new TristateCheckBox("", null, true); public static final State NOT_SELECTED = new State(); public static final State SELECTED = new State(); public static final State DONT_CARE = new State(); public CheckTreeCellRenderer(MyRenderer delegate, CheckTreeSelectionModel selectionModel) { this.delegate = delegate; this.selectionModel = selectionModel; setLayout(new BorderLayout()); setOpaque(true); setBackground(new Color(207, 219, 234)); checkBox.setState(Boolean.TRUE); checkBox.setOpaque(true); checkBox.setBackground(new Color(207, 219, 234)); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); TreePath path = tree.getPathForRow(row); if (path != null) { if (selectionModel.isPathSelected(path, true)) { checkBox.setState(Boolean.TRUE); } else { checkBox.setState(selectionModel.isPartiallySelected(path) ? null : Boolean.FALSE); } } renderer.setBackground(new Color(207, 219, 234)); tree.setOpaque(true); tree.setBackground(new Color(207, 219, 234)); this.setOpaque(true); this.setBackground(new Color(207, 219, 234)); add(checkBox, BorderLayout.WEST); add(renderer, BorderLayout.CENTER); return this; } }

    Read the article

  • How to display many SVGs in Java with high performance

    - by Oak
    What I want My goal is to be able to display a large number of SVG images on a single drawing area in Java, each with its own translation/rotation/scale values. I'm looking for the simplest solution allowing this, optionally even using OpenGL to speed things up. What I've Tried My initial naive approach was to use SVGSalamander to draw directly on a JPanel, but the performance was pathetic. I poked around around and learned that I should do something like manually convert each SVG into a BufferedImage created with createCompatibleImage, then do the transformations I want, then draw it using double buffering. I ran into some troubles here, and before I continued I tried looking for frameworks to simplify things. What I've Looked At I've been a bit overwhelmed by the available options, which is why I'm turning to SO for help. I've looked at: Cairo (with Glitz maybe?) Libart - not sure if this actually supports SVGs FengGUI Slick - looks promising but a bit of an overkill But couldn't decide what is best for me to start working with, and I hope someone here as experience with any of these doing similar things.

    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

  • How to keep Java Frame from waiting?

    - by pypmannetjies
    I am writing a genetic algorithm that approximates an image with a polygon. While going through the different generations, I'd like to output the progress to a JFrame. However, it seems like the JFrame waits until the GA's while loop finishes to display something. I don't believe it's a problem like repainting, since it eventually does display everything once the while loop exits. I want to GUI to update dynamically even when the while loop is running. Here is my code: while (some conditions) { //do some other stuff gui.displayPolygon(best); gui.displayFitness(fitness); gui.setVisible(true); } public void displayPolygon(Polygon poly) { BufferedImage bpoly = ImageProcessor.createImageFromPoly(poly); ImageProcessor.displayImage(bpoly, polyPanel); this.setVisible(true); } public static void displayImage(BufferedImage bimg, JPanel panel) { panel.removeAll(); panel.setBounds(0, 0, bimg.getWidth(), bimg.getHeight()); JImagePanel innerPanel = new JImagePanel(bimg, 25, 25); panel.add(innerPanel); innerPanel.setLocation(25, 25); innerPanel.setVisible(true); panel.setVisible(true); }

    Read the article

  • MouseListener fired without checking JCheckBox

    - by Morinar
    This one is pretty crazy: I've got an AppSight recording (for those not familiar, it's a recording of what they did including keyboard/mouse input + network traffic, etc) of a customer reproducing a bug. Basically, we've got a series of items listed on the screen with JCheckBox-es down the left side. We've got a MouseListener set for the JPanel that looks something like this: private MouseAdapter createMouseListener() { return new MouseAdapter(){ public void mousePressed( MouseEvent e ) { if( e.getComponent() instanceof JCheckBox ) { // Do stuff } } }; } Based on the recording, it appears very strongly that they click just above one of the checkboxes. After that, it's my belief that this listener fired and the "Do stuff" block happened. However, it did NOT check the box. The user then saw that the box was unchecked, so they clicked on it. This caused the "Do stuff" block to fire again, thus undoing what it had done the first time. This time, the box was checked. Therefore, the user thinks that the box is checked, and it looks like it is, but our client thinks that the box is unchecked as it was clicked twice. Is this possible at all? For the life of me, I can't reproduce it or see how it could be possible, but based on the recording and the data the client sent to the server, I can't see any other logical explanation. Any help, thoughts, and or ideas would be much appreciated.

    Read the article

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