Search Results

Search found 47 results on 2 pages for 'jfilechooser'.

Page 2/2 | < Previous Page | 1 2 

  • image upload-showing image on a form

    - by mnmyles
    hi guyz; i am using netbeans6.7.1 and phpmyadmin for my db to develop a java application to manage students records i want to upload students photos through browsing by clicking a browse buton which i have included in my interface I mean when i click on that button a JFilechooser pops up which filter only images(i have acomplished this) 1.) what i need is when i click on the "Attach button" of the JFilechooser, i want the image i chose to be attached to a jtextArea on the form i'm working with and the JFilechooser be diposed off. 2.) Also how i can save this form together with the image to a database table Is there a place where i can find a good guide/tutorial about that

    Read the article

  • Java File manipulation

    - by user69514
    So I have an application with a JFileChooser from which I select a file to read. Then I change some words and write a new file. The problem that I am having is that when I write the new file it's saved in the project directory. How do I save it in the same directory as the file that I chose using the JFileChooser. Note: I don't want to use the JFileChooser to choose the location. I just need to save the file in the same directory as the original file that I read.

    Read the article

  • save as .txt format

    - by user1180492
    I made a NotePad program. The problem is it doesn't save in .txt format, It save as a file with no format. But it can open .txt files. How can i fix it? Here is my work. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Scanner; import java.io.*; public class NotePad extends JFrame { private JTextArea noteArea; public static void main(String[] args) { NotePad p = new NotePad(); p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); p.setSize(500,300); p.setVisible(true); } public NotePad() { super("Java Notepad"); setLayout(new BorderLayout()); noteArea = new JTextArea("",20,20); noteArea.setWrapStyleWord(true); noteArea.setLineWrap(true); Font font = new Font("sanserif", Font.BOLD,14); noteArea.setFont(font); JScrollPane scroller = new JScrollPane(noteArea); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); add(scroller,BorderLayout.CENTER); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem openMenu = new JMenuItem("Open"); openMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser openFile = new JFileChooser(); openFile.showOpenDialog(new NotePad()); loadFile(openFile.getSelectedFile()); } }); JMenuItem saveMenu = new JMenuItem("Save"); saveMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser saveFile = new JFileChooser(); saveFile.showSaveDialog(new NotePad()); fileSaved(saveFile.getSelectedFile()); } }); JMenuItem exitMenu = new JMenuItem("Close"); exitMenu.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { System.exit(0); } }); fileMenu.add(openMenu); fileMenu.add(saveMenu); fileMenu.add(exitMenu); menuBar.add(fileMenu); this.setJMenuBar(menuBar); } public void loadFile(File file) { noteArea.setText(""); try { BufferedReader read = new BufferedReader(new FileReader(file)); String line = null; while((line =read.readLine())!=null) { noteArea.append(line +"\n"); } read.close(); } catch (Exception e) { System.out.println("Error " + e.toString()); } } public void fileSaved(File file) { try { PrintWriter writer = new PrintWriter(file); String[] lines = noteArea.getText().split("\\n"); for (String ) { writer.println(words); } writer.close(); } catch (Exception e) { System.out.println("Error " + e.toString()); } } } btw I can't post my question because of not explaning the scenario according to the site. So there. Thanks for the help

    Read the article

  • What is the wrong of this converted code?

    - by Gum Slashy
    I'm developing shape identification project using javacv and I have found some opencv code to identify U shapes in particular image and I have try to convert it in to javacv but it doesn't provide same out put. Can you please help me to convert this opencv code into javacv? This is Opencv code import cv2 import numpy as np img = cv2.imread('sofud.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(gray,127,255,1) contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) if 10 < w/float(h) or w/float(h) < 0.1: cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2) cv2.imshow('res',img) cv2.waitKey(0) cv2.destroyAllWindows() This is the expected output This is the code that I have converted import com.googlecode.javacpp.Loader; import com.googlecode.javacv.CanvasFrame; import static com.googlecode.javacpp.Loader.*; import static com.googlecode.javacv.cpp.opencv_core.*; import static com.googlecode.javacv.cpp.opencv_imgproc.*; import static com.googlecode.javacv.cpp.opencv_highgui.*; import java.io.File; import javax.swing.JFileChooser; public class TestBeam { public static void main(String[] args) { CvMemStorage storage=CvMemStorage.create(); CvSeq squares = new CvContour(); squares = cvCreateSeq(0, sizeof(CvContour.class), sizeof(CvSeq.class), storage); JFileChooser f=new JFileChooser(); int result=f.showOpenDialog(f);//show dialog box to choose files File myfile=null; String path=""; if(result==0){ myfile=f.getSelectedFile();//selected file taken to myfile path=myfile.getAbsolutePath();//get the path of the file } IplImage src = cvLoadImage(path);//hear path is actual path to image IplImage grayImage = IplImage.create(src.width(), src.height(), IPL_DEPTH_8U, 1); cvCvtColor(src, grayImage, CV_RGB2GRAY); cvThreshold(grayImage, grayImage, 127, 255, CV_THRESH_BINARY); CvSeq cvSeq=new CvSeq(); CvMemStorage memory=CvMemStorage.create(); cvFindContours(grayImage, memory, cvSeq, Loader.sizeof(CvContour.class), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); System.out.println(cvSeq.total()); for (int i = 0; i < cvSeq.total(); i++) { CvRect rect=cvBoundingRect(cvSeq, i); int x=rect.x(),y=rect.y(),h=rect.height(),w=rect.width(); if (10 < (w/h) || (w/h) < 0.1){ cvRectangle(src, cvPoint(x, y), cvPoint(x+w, y+h), CvScalar.RED, 1, CV_AA, 0); //cvSeqPush(squares, rect); } } CanvasFrame cnvs=new CanvasFrame("Beam"); cnvs.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); cnvs.showImage(src); //cvShowImage("Final ", src); } } This is the out put that I got please can some one help me to solve this problem ?

    Read the article

  • How to rectify this program?

    - by user1430719
    This is a program to display a pie chart. I also have a button. But the program I have written, creates two separate frames and one frame is for the pie chart and the other is for the button. How do I put both button and pie chart on the same frame?? Can you please rectify my program. import java.awt.*; import org.jfree.chart.*; import org.jfree.chart.title.*; import org.jfree.data.general.DefaultPieDataset; import org.jfree.ui.*; import java.io.*; import javax.swing.*; import java.awt.event.*; import javax.swing.filechooser.*; public class Pie{ public static void getFile(File f) { System.out.println("File is: "+f.getName()); } public static void main(String[] args) { JPanel panel=new JPanel(); panel.setLayout(null); JButton b=new JButton("Open File"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser=new JFileChooser(); int ret = chooser.showDialog(null, "Open file"); if (ret == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); getFile(file); } } } ); b.setBounds(50,40,100,35); panel.add(b); DefaultPieDataset pieDataset = new DefaultPieDataset(); pieDataset.setValue("A", new Integer(10)); pieDataset.setValue("B", new Integer(20)); pieDataset.setValue("C", new Integer(30)); pieDataset.setValue("D", new Integer(10)); pieDataset.setValue("E", new Integer(20)); pieDataset.setValue("F", new Integer(10)); JFreeChart chart = ChartFactory.createPieChart("Pie Chart using JFreeChart", pieDataset, true,true,true); ChartFrame frame1=new ChartFrame("Pie Chart",chart); frame1.add(panel); frame1.setVisible(true); frame1.setSize(600,600); } }

    Read the article

  • Java JTextPane JScrollPane Display Issue

    - by ikurtz
    The following class implements a chatGUI. When it runs okay the screen looks like this: Fine ChatGUI The problem is very often when i enter text of large length ie. 50 - 100 chars the gui goes crazy. the chat history box shrinks as shown in this image. Any ideas regarding what is causing this? Thank you. package Sartre.Connect4; import javax.swing.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.text.StyledDocument; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.BadLocationException; import java.io.BufferedOutputStream; import javax.swing.text.html.HTMLEditorKit; import java.io.FileOutputStream; import java.io.IOException; import java.io.FileNotFoundException; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.JFileChooser; /** * Chat form class * @author iAmjad */ public class ChatGUI extends JDialog implements ActionListener { /** * Used to hold chat history data */ private JTextPane textPaneHistory = new JTextPane(); /** * provides scrolling to chat history pane */ private JScrollPane scrollPaneHistory = new JScrollPane(textPaneHistory); /** * used to input local message to chat history */ private JTextPane textPaneHome = new JTextPane(); /** * Provides scrolling to local chat pane */ private JScrollPane scrollPaneHomeText = new JScrollPane(textPaneHome); /** * JLabel acting as a statusbar */ private JLabel statusBar = new JLabel("Ready"); /** * Button to clear chat history pane */ private JButton JBClear = new JButton("Clear"); /** * Button to save chat history pane */ private JButton JBSave = new JButton("Save"); /** * Holds contentPane */ private Container containerPane; /** * Layout GridBagLayout manager */ private GridBagLayout gridBagLayout = new GridBagLayout(); /** * GridBagConstraints */ private GridBagConstraints constraints = new GridBagConstraints(); /** * Constructor for ChatGUI */ public ChatGUI(){ setTitle("Chat"); // set up dialog icon URL url = getClass().getResource("Resources/SartreIcon.jpg"); ImageIcon imageIcon = new ImageIcon(url); Image image = imageIcon.getImage(); this.setIconImage(image); this.setAlwaysOnTop(true); setLocationRelativeTo(this.getParent()); //////////////// End icon and placement ///////////////////////// // Get pane and set layout manager containerPane = getContentPane(); containerPane.setLayout(gridBagLayout); ///////////////////////////////////////////////////////////// //////////////// Begin Chat History ////////////////////////////// textPaneHistory.setToolTipText("Chat History Window"); textPaneHistory.setEditable(false); textPaneHistory.setPreferredSize(new Dimension(350,250)); scrollPaneHistory.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneHistory.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // fill Chat History GridBagConstraints constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 10; constraints.gridheight = 10; constraints.weightx = 100; constraints.weighty = 100; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(10,10,10,10); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(scrollPaneHistory, constraints); // add to the pane containerPane.add(scrollPaneHistory); /////////////////////////////// End Chat History /////////////////////// ///////////////////////// Begin Home Chat ////////////////////////////// textPaneHome.setToolTipText("Home Chat Message Window"); textPaneHome.setPreferredSize(new Dimension(200,50)); textPaneHome.addKeyListener(new MyKeyAdapter()); scrollPaneHomeText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneHomeText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // fill Chat History GridBagConstraints constraints.gridx = 0; constraints.gridy = 10; constraints.gridwidth = 6; constraints.gridheight = 1; constraints.weightx = 100; constraints.weighty = 100; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(10,10,10,10); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(scrollPaneHomeText, constraints); // add to the pane containerPane.add(scrollPaneHomeText); ////////////////////////// End Home Chat ///////////////////////// ///////////////////////Begin Clear Chat History //////////////////////// JBClear.setToolTipText("Clear Chat History"); // fill Chat History GridBagConstraints constraints.gridx = 6; constraints.gridy = 10; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.weightx = 100; constraints.weighty = 100; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(10,10,10,10); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(JBClear, constraints); JBClear.addActionListener(this); // add to the pane containerPane.add(JBClear); ///////////////// End Clear Chat History //////////////////////// /////////////// Begin Save Chat History ////////////////////////// JBSave.setToolTipText("Save Chat History"); constraints.gridx = 8; constraints.gridy = 10; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.weightx = 100; constraints.weighty = 100; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(10,10,10,10); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(JBSave, constraints); JBSave.addActionListener(this); // add to the pane containerPane.add(JBSave); ///////////////////// End Save Chat History ///////////////////// /////////////////// Begin Status Bar ///////////////////////////// constraints.gridx = 0; constraints.gridy = 11; constraints.gridwidth = 10; constraints.gridheight = 1; constraints.weightx = 100; constraints.weighty = 50; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(0,10,5,0); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(statusBar, constraints); // add to the pane containerPane.add(statusBar); ////////////// End Status Bar //////////////////////////// // set resizable to false this.setResizable(false); // pack the GUI pack(); } /** * Deals with necessary menu click events * @param event */ public void actionPerformed(ActionEvent event) { Object source = event.getSource(); // Process Clear button event if (source == JBClear){ textPaneHistory.setText(null); statusBar.setText("Chat History Cleared"); } // Process Save button event if (source == JBSave){ // process only if there is data in history pane if (textPaneHistory.getText().length() > 0){ // process location where to save the chat history file JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML Documents", "htm", "html"); chooser.setFileFilter(filter); int option = chooser.showSaveDialog(ChatGUI.this); if (option == JFileChooser.APPROVE_OPTION) { // Set up document to be parsed as HTML StyledDocument doc = (StyledDocument)textPaneHistory.getDocument(); HTMLEditorKit kit = new HTMLEditorKit(); BufferedOutputStream out; try { // add final file name and extension String filePath = chooser.getSelectedFile().getAbsoluteFile() + ".html"; out = new BufferedOutputStream(new FileOutputStream(filePath)); // write out the HTML document kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength()); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(ChatGUI.this, "Application will now close. \n A restart may cure the error!\n\n" + e.getMessage(), "Fatal Error", JOptionPane.WARNING_MESSAGE, null); System.exit(2); } catch (IOException e){ JOptionPane.showMessageDialog(ChatGUI.this, "Application will now close. \n A restart may cure the error!\n\n" + e.getMessage(), "Fatal Error", JOptionPane.WARNING_MESSAGE, null); System.exit(3); } catch (BadLocationException e){ JOptionPane.showMessageDialog(ChatGUI.this, "Application will now close. \n A restart may cure the error!\n\n" + e.getMessage(), "Fatal Error", JOptionPane.WARNING_MESSAGE, null); System.exit(4); } statusBar.setText("Chat History Saved"); } } } } /** * Process return key for sending the message */ private class MyKeyAdapter extends KeyAdapter { @Override @SuppressWarnings("static-access") public void keyPressed(KeyEvent ke) { DateTime dateTime = new DateTime(); String nowdateTime = dateTime.getDateTime(); int kc = ke.getKeyCode(); if (kc == ke.VK_ENTER) { try { // Process only if there is data if (textPaneHome.getText().length() > 0){ // Add message origin formatting StyledDocument doc = (StyledDocument)textPaneHistory.getDocument(); Style style = doc.addStyle("HomeStyle", null); StyleConstants.setBold(style, true); String home = "Home [" + nowdateTime + "]: "; doc.insertString(doc.getLength(), home, style); StyleConstants.setBold(style, false); doc.insertString(doc.getLength(), textPaneHome.getText() + "\n", style); // update caret location textPaneHistory.setCaretPosition(doc.getLength()); textPaneHome.setText(null); statusBar.setText("Message Sent"); } } catch (BadLocationException e) { JOptionPane.showMessageDialog(ChatGUI.this, "Application will now close. \n A restart may cure the error!\n\n" + e.getMessage(), "Fatal Error", JOptionPane.WARNING_MESSAGE, null); System.exit(1); } ke.consume(); } } } }

    Read the article

  • How do I get my code to read the spaces between longs?

    - by WahtsUpWorld
    I apologize for any inconvenience that may occur in answering my question, I'm fairly new to programming and I'm so far only in the last weeks of my community college Java I class. The problem I am facing is in my code of which I cannot seem to get the PrintWriter to address the spaces in between my longs' phone number and social security I.D. The entire code consists of two classes in which one pulls from the other the information needed to parse and present the file writer/print writer. Here is the entire code w/ the second class after it: public class FinalProjectGroup1 { public static void main(String[] args) { } public String name; public long ssid; public double pay; public String address; public long number; public void cleanUpConstructor() {} public FinalProjectGroup1(String name, String address, double pay, long ssid, long number){ this.name = name; this.pay = pay; this.ssid = ssid; this.address = address; this.number = number; cleanUpConstructor(); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setPay(double pay) { this.pay = pay; } public double getPay() { return pay; } public void setSSID(long ssid) { this.ssid = ssid; } public long getSSID() { return ssid; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } public void setNumber(long number) { this.number = number; } public long getNumber() { return number; } } SECOND CLASS import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JFileChooser; import javax.swing.JButton; import javax.swing.JTextField; import FinalProjectGroup1; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.FileWriter; import java.io.PrintWriter; public class FinalProjectGroup1Window { public JFrame frmTheBosssSecretary; public JTextField txtName; public JTextField txtSSID; public JTextField txtAddress; public JTextField txtNumber; public JTextField txtPay; public JTextField txtFindName; public JTextField txtFindSSID; public JTextField txtFindPay; public JTextField txtFolder; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FinalProjectGroup1Window window = new FinalProjectGroup1Window(); window.frmTheBosssSecretary.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public FinalProjectGroup1Window() { initialize(); } private void initialize() { frmTheBosssSecretary = new JFrame(); frmTheBosssSecretary.setFont(new Font("Times New Roman", Font.PLAIN, 12)); frmTheBosssSecretary.setTitle("The Boss's Secretary: Employee Generator/Finder"); frmTheBosssSecretary.setBounds(100, 100, 547, 302); frmTheBosssSecretary.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmTheBosssSecretary.getContentPane().setLayout(null); JLabel lblFile = new JLabel("Employee Folder:"); lblFile.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblFile.setBounds(10, 10, 93, 14); frmTheBosssSecretary.getContentPane().add(lblFile); JLabel lblFindEmployee = new JLabel("Employee Finder"); lblFindEmployee.setFont(new Font("Times New Roman", Font.BOLD, 18)); lblFindEmployee.setBounds(194, 159, 142, 20); frmTheBosssSecretary.getContentPane().add(lblFindEmployee); JLabel lblEmployeeName = new JLabel("Employee Name:"); lblEmployeeName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblEmployeeName.setBounds(10, 35, 93, 14); frmTheBosssSecretary.getContentPane().add(lblEmployeeName); JLabel lblSSID = new JLabel("Employee SSID:"); lblSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblSSID.setBounds(10, 135, 85, 14); frmTheBosssSecretary.getContentPane().add(lblSSID); JLabel lblAddress = new JLabel("Employee Address:"); lblAddress.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblAddress.setBounds(10, 60, 105, 14); frmTheBosssSecretary.getContentPane().add(lblAddress); JLabel lblPhoneNumber = new JLabel("Employee Phone Number:"); lblPhoneNumber.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblPhoneNumber.setBounds(10, 85, 134, 14); frmTheBosssSecretary.getContentPane().add(lblPhoneNumber); JLabel lblPayRate = new JLabel("Employee Pay Rate:"); lblPayRate.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblPayRate.setBounds(10, 110, 105, 14); frmTheBosssSecretary.getContentPane().add(lblPayRate); JLabel lblFindEmployeeName = new JLabel("Find Employee Name:"); lblFindEmployeeName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblFindEmployeeName.setBounds(10, 183, 115, 14); frmTheBosssSecretary.getContentPane().add(lblFindEmployeeName); JLabel lblFindSSID = new JLabel("Find Employee SSID:"); lblFindSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblFindSSID.setBounds(10, 208, 105, 14); frmTheBosssSecretary.getContentPane().add(lblFindSSID); JLabel lblFindPay = new JLabel("Find Employee Address:"); lblFindPay.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblFindPay.setBounds(10, 233, 124, 14); frmTheBosssSecretary.getContentPane().add(lblFindPay); txtFolder = new JTextField(); txtFolder.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtFolder.setBounds(105, 7, 314, 20); frmTheBosssSecretary.getContentPane().add(txtFolder); txtFolder.setColumns(10); txtName = new JTextField(); txtName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtName.setBounds(99, 32, 247, 20); frmTheBosssSecretary.getContentPane().add(txtName); txtName.setColumns(10); txtAddress = new JTextField(); txtAddress.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtAddress.setBounds(109, 57, 237, 20); frmTheBosssSecretary.getContentPane().add(txtAddress); txtAddress.setColumns(10); txtNumber = new JTextField(); txtNumber.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtNumber.setBounds(141, 82, 160, 20); frmTheBosssSecretary.getContentPane().add(txtNumber); txtNumber.setColumns(10); txtPay = new JTextField(); txtPay.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtPay.setBounds(116, 107, 105, 20); frmTheBosssSecretary.getContentPane().add(txtPay); txtPay.setColumns(10); txtSSID = new JTextField(); txtSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtSSID.setBounds(97, 132, 124, 20); frmTheBosssSecretary.getContentPane().add(txtSSID); txtSSID.setColumns(10); txtFindName = new JTextField(); txtFindName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtFindName.setBounds(122, 180, 314, 20); frmTheBosssSecretary.getContentPane().add(txtFindName); txtFindName.setColumns(10); txtFindSSID = new JTextField(); txtFindSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtFindSSID.setBounds(122, 205, 122, 20); frmTheBosssSecretary.getContentPane().add(txtFindSSID); txtFindSSID.setColumns(10); txtFindPay = new JTextField(); txtFindPay.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtFindPay.setBounds(141, 230, 237, 20); frmTheBosssSecretary.getContentPane().add(txtFindPay); txtFindPay.setColumns(10); JButton btnAddEmployee = new JButton("Add Employee"); btnAddEmployee.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { String name = txtName.getText(); String address = txtAddress.getText(); double pay = Double.parseDouble(txtPay.getText()); long ssid = Long.parseLong(txtSSID.getText()); long number = Long.parseLong(txtNumber.getText()); FinalProjectGroup1 ee = new FinalProjectGroup1(name, address, pay, ssid, number); FileWriter writer = new FileWriter(txtFolder.getText(), true); PrintWriter pw = new PrintWriter(writer); pw.println(ee.getName() + ", " + ee.getAddress() + ", " + ee.getNumber() + ", " + ee.getPay() + ", " + ee.getSSID()); pw.close(); } catch (Exception e) { return; } } }); JButton btnFolder = new JButton("Folder"); btnFolder.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser bsearch = new JFileChooser(); int result = bsearch.showOpenDialog(null); if (result != JFileChooser.APPROVE_OPTION) return; txtFolder.setText(bsearch.getSelectedFile().getAbsolutePath()); } }); btnFolder.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnFolder.setBounds(429, 6, 75, 23); frmTheBosssSecretary.getContentPane().add(btnFolder); btnAddEmployee.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnAddEmployee.setBounds(356, 42, 159, 107); frmTheBosssSecretary.getContentPane().add(btnAddEmployee); JButton btnFindName = new JButton("Find"); btnFindName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnFindName.setBounds(446, 179, 69, 23); frmTheBosssSecretary.getContentPane().add(btnFindName); JButton btnFindSSID = new JButton("Find"); btnFindSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnFindSSID.setBounds(250, 204, 85, 23); frmTheBosssSecretary.getContentPane().add(btnFindSSID); JButton btnFindAddress = new JButton("Find"); btnFindAddress.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnFindAddress.setBounds(389, 229, 85, 23); frmTheBosssSecretary.getContentPane().add(btnFindAddress); } } The problem here lies in the JButton Add Employee. Where, as previously mentioned, the long's phone number and social security I.D. don't show the spaces in the text file.

    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 to fix Java Image Fetcher error ?

    - by Frank
    My code looks like this : private static JFileChooser fc; if (fc==null) { fc=new JFileChooser(Image_Dir); fc.addChoosableFileFilter(new Image_Filter()); // Add a custom file filter and disable the default (Accept All) file filter. fc.setAcceptAllFileFilterUsed(false); fc.setAccessory(new Image_Preview(fc)); // Add the preview pane. } int returnVal=fc.showDialog(JFileChooser_For_Image.this,"Get Image"); // Show it. After I select an image from the panel, I got the following error message : Exception in thread "Image Fetcher 0" java.lang.UnsatisfiedLinkError: Native Library C:\Program Files (x86)\Java\jre6\bin\jpeg.dll already loaded in another classloader at java.lang.ClassLoader.loadLibrary0(Unknown Source) at java.lang.ClassLoader.loadLibrary(Unknown Source) at java.lang.Runtime.loadLibrary0(Unknown Source) at java.lang.System.loadLibrary(Unknown Source) at sun.security.action.LoadLibraryAction.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.awt.image.JPEGImageDecoder.<clinit>(Unknown Source) at sun.awt.image.InputStreamImageSource.getDecoder(Unknown Source) at sun.awt.image.FileImageSource.getDecoder(Unknown Source) at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source) at sun.awt.image.ImageFetcher.fetchloop(Unknown Source) at sun.awt.image.ImageFetcher.run(Unknown Source) When I run it from an executable Jar file, it works fine, but after I wrapped it into an exe file, I got the above error, why ? How to fix it ?

    Read the article

  • Java JCheckBox ArrayList help needed

    - by user2929626
    I'm new to Java and struggling with something which I'm sure must have a simple answer but I can't seem to find it. I have an array of checkbox objects defined as: ArrayList<JCheckBox> checkBoxList A JPanel is created with a grid layout and the checkboxes are added to the JPanel and the ArrayList: for (int i = 0; i < 256; i++) { JCheckBox c = new JCheckBox(); c.setSelected(false); checkBoxList.add(c); mainPanel.add(c); } Yes, there are 256 checkboxes! The panel is added to a JFrame and eventually the GUI is displayed. The user can select any combination of the 256 checkboxes. My class implements Serializable and this ArrayList of checkboxes can be saved and restored using 'Save' and 'Load' GUI buttons. My code to load the saved object is as below: public class LoadListener implements ActionListener { public void actionPerformed(ActionEvent a) { try { // Prompt the user for a load file JFileChooser fileLoad = new JFileChooser(); fileLoad.showOpenDialog(mainFrame); // Create a object/file input stream linking to the selected file ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileLoad.getSelectedFile())); // Read the checkBox array list checkBoxList = (ArrayList<JCheckBox>) is.readObject(); is.close(); } catch (Exception ex) { ex.printStackTrace(); } } On loading the ArrayList object, the values of the checkboxes are correctly populated, however I want to update the checkboxes on the GUI to reflect this. Is there an easy way to do this? I assumed as the array of checkboxes had the correct values that I could just repaint the panel / frame but this doesn't work. I'd like to understand why - does my loaded array of checkbox objects no longer reflect the checkbox objects on the GUI? Any help would be much appreciated. Thanks!

    Read the article

  • Java variables across methods

    - by NardCake
    I'm making a basic text editor, and I have 2 methods the first one is triggered when a user click 'Open' and it prompts the user to pick a file and it opens the file fine. I just want to access the same file path which is in a variable in the method that is triggered when the user clicks save. My methods are public, Iv'e tried accessing it through a class, still no. Please help! Code: public void open(){ try{ //Open file JFileChooser fc = new JFileChooser(); fc.showOpenDialog(null); File file = fc.getSelectedFile(); String haha = file.getPath(); BufferedReader br = new BufferedReader(new FileReader(file.getPath())); String line; while((line = br.readLine()) != null){ text.append(line + "\n"); } } catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ } } public void save(){ try { BufferedWriter bw = new BufferedWriter(new FileWriter(file.filePath)); bw.write(text.getText()); bw.close(); } catch (IOException e) { e.printStackTrace(); } }

    Read the article

  • Java Box Class: Unsolvable: aligning components to the left or right

    - by user323186
    I have been trying to left align buttons contained in a Box to the left, with no success. They align left alright, but for some reason dont shift all the way left as one would imagine. I attach the code below. Please try compiling it and see for yourself. Seems bizarre to me. Thanks, Eric import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class MainGUI extends Box implements ActionListener{ //Create GUI Components Box centerGUI=new Box(BoxLayout.X_AXIS); Box bottomGUI=new Box(BoxLayout.X_AXIS); //centerGUI subcomponents JTextArea left=new JTextArea(), right=new JTextArea(); JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right); //bottomGUI subcomponents JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info"); //Create Menubar components JMenuBar menubar=new JMenuBar(); JMenu fileMenu=new JMenu("File"); JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit"); int returnVal =0; public MainGUI(){ super(BoxLayout.Y_AXIS); initCenterGUI(); initBottomGUI(); initFileMenu(); add(centerGUI); add(bottomGUI); addActionListeners(); } private void addActionListeners() { open.addActionListener(this); save.addActionListener(this); exit.addActionListener(this); encrypt.addActionListener(this); decrypt.addActionListener(this); close.addActionListener(this); info.addActionListener(this); } private void initFileMenu() { fileMenu.add(open); fileMenu.add(save); fileMenu.add(exit); menubar.add(fileMenu); } public void initCenterGUI(){ centerGUI.add(leftScrollPane); centerGUI.add(rightScrollPane); } public void initBottomGUI(){ bottomGUI.setAlignmentX(LEFT_ALIGNMENT); //setBorder(BorderFactory.createLineBorder(Color.BLACK)); bottomGUI.add(encrypt); bottomGUI.add(decrypt); bottomGUI.add(close); bottomGUI.add(info); } @Override public void actionPerformed(ActionEvent arg0) { // find source of the action Object source=arg0.getSource(); //if action is of such a type do the corresponding action if(source==close){ kill(); } else if(source==open){ //CHOOSE FILE File file1 =chooseFile(); String input1=readToString(file1); System.out.println(input1); left.setText(input1); } else if(source==decrypt){ //decrypt everything in Right Panel and output in left panel decrypt(); } else if(source==encrypt){ //encrypt everything in left panel and output in right panel encrypt(); } else if(source==info){ //show contents of info file in right panel doInfo(); } else { System.out.println("Error"); //throw new UnimplementedActionException(); } } private void doInfo() { // TODO Auto-generated method stub } private void encrypt() { // TODO Auto-generated method stub } private void decrypt() { // TODO Auto-generated method stub } private String readToString(File file) { FileReader fr = null; try { fr = new FileReader(file); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader br=new BufferedReader(fr); String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } String input=""; while(line!=null){ input=input+"\n"+line; try { line=br.readLine(); } catch (IOException e) { e.printStackTrace(); } } return input; } private File chooseFile() { //Create a file chooser final JFileChooser fc = new JFileChooser(); returnVal = fc.showOpenDialog(fc); return fc.getSelectedFile(); } private void kill() { System.exit(0); } public static void main(String[] args) { // TODO Auto-generated method stub MainGUI test=new MainGUI(); JFrame f=new JFrame("Tester"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setJMenuBar(test.menubar); f.setPreferredSize(new Dimension(600,400)); //f.setUndecorated(true); f.add(test); f.pack(); f.setVisible(true); } }

    Read the article

  • 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

  • Nimbus Tweaking Help Needed

    - by Geertjan
    I was reading this new article on Synthetica and NetBeans RCP this morning, when I remembered this screenshot from Henry Arousell from Sweden: Here, Nimbus is heavily being used, highlighting 6 areas where Henry would really benefit from any help regarding how the foreground properties should be set: The color of the main menu (and its subsequent unfolded menu options) The TopComponent tab colors (as you can see from the screenshot, they've managed to change the foreground colors of the ones in the editor mode by setting the Nimbus property "TextText"). They cannot manipulate TopComponents in other modes, though. Table header foreground colors The foreground color of any provided composite component, like a JFileChooser or the ICEPdf viewer or any other panel with label components. The progress bar message color. The status bar message color, A Nimbus expert is needed to help here, though it seems to me that some of the solutions have already been identified, or are similar, in the article pointed out above.

    Read the article

  • How can Swing dialogs even work?

    - by Bart van Heukelom
    If you open a dialog in Swing, for example a JFileChooser, it goes somewhat like this pseudocode: swing event thread { create dialog add listener to dialog close event { returnValue = somethingFromDialog } show dialog (wait until it is closed) return returnValue } My question is: how can this possibly work? As you can see the thread waits to return until the dialog is closed. This means the Swing event thread is blocked. Yet, one can interact with the dialog, which AFAIK requires this thread to run. So how does that work?

    Read the article

  • File explorer java

    - by Studer
    I'd like to have some kind of file browser like Windows Explorer inside a Java Application. I just want something that's able to list file inside a folder recursively. Is there a simple way to do this ? I already tried to use JFileChooser but it's not what I want.

    Read the article

  • Naming methods that do the same thing but return different types

    - by Konstantin Ð.
    Let's assume that I'm extending a graphical file chooser class (JFileChooser). This class has methods which display the file chooser dialog and return a status signature in the form of an int: APPROVE_OPTION if the user selects a file and hits Open /Save, CANCEL_OPTION if the user hits Cancel, and ERROR_OPTION if something goes wrong. These methods are called showDialog(). I find this cumbersome, so I decide to make another method that returns a File object: in the case of APPROVE_OPTION, it returns the file selected by the user; otherwise, it returns null. This is where I run into a problem: would it be okay for me to keep the showDialog() name, even though methods with that name — and a different return type — already exist? To top it off, my method takes an additional parameter: a File which denotes in which directory the file chooser should start. My question to you: Is it okay to call a method the same name as a superclass method if they return different types? Or would that be confusing to API users? (If so, what other name could I use?) Alternatively, should I keep the name and change the return type so it matches that of the other methods? public int showDialog(Component parent, String approveButtonText) // Superclass method public File showDialog(Component parent, File location) // My method

    Read the article

  • How do you force a Linux process (Java webstart App) to stop locking a Filesystem (CD-ROM) WITHOUT k

    - by Blake
    In Linux (CentOS 5.4), how do you force a process to stop locking a file system without killing the process? I am trying to get my Java Webstart Application, running locally, to eject a CD. I do not have this problem if I am just browsing through the files using a JFileChooser, but once I read the contents of a file, I can no longer eject the CD...even after removing ALL references to any files. Hitting the eject button will give the error (Title - "Cannot Eject Volume"): "An application is preventing the volume 'volume name' from being ejected" Thus, my goal is to tell the process to stop targeting the CD-ROM in order to free it up. Thank you for any help or direction!! Attempted Fix: -running the commands: sudo umount -l /media/Volume_Name //-l Lazy Unmount forces the unmount sudo eject Problem: When a new CD is inserted, it is no longer mounted automatically probably because the process is still "targeting" it.

    Read the article

  • Reading files with Java

    - by sikas
    I would like to know how can I read a file byte by byte then perform some operation every n bytes. for example: Say I have a file of size = 50 bytes, I want to divide it into blocks each of n bytes. Then each block is sent to a function for some operations to be done on those bytes. The blocks are to be created during the read process and sent to the function when the block reaches n bytes so that I don`t use much memory for storing all blocks. I want the output of the function to be written/appended on a new file. This is what I've reached to read, yet I don't know it it is right: fc = new JFileChooser(); File f = fc.getSelectedFile(); FileInputStream in = new FileInputStream(f); byte[] b = new byte[16]; in.read(b); I haven't done anything yet for the write process.

    Read the article

  • Problem with my whiteboard application

    - by swift
    I have to develop a whiteboard application in which both the local user and the remote user should be able to draw simultaneously, is this possible? If possible then any logic? I have already developed a code but in which i am not able to do this, when the remote user starts drawing the shape which i am drawing is being replaced by his shape and co-ordinates. This problem is only when both draw simultaneously. any idea guys? Here is my code class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; int bpressed; Color color; Point start; Point end; Point mp; Button elipse=new Button("elipse"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button empty=new Button(""); JButton save=new JButton("Save"); JButton erase=new JButton("Erase"); String selected; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Point p=new Point(); int w,h; public Paper(DatagramSocket dataSocket) { this.dataSocket=dataSocket; client=new Client(dataSocket); System.out.println("paper"); setBackground(Color.white); addMouseListener(this); addMouseMotionListener(this); color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); //save.setPreferredSize(new Dimension(100,20)); save.setMaximumSize(new Dimension(75,27)); erase.setMaximumSize(new Dimension(75,27)); } public void paintComponent(Graphics g) { try { g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); repaint(); g2.dispose(); start=null; } //To add the point to the board which is broadcasted by the server public synchronized void addPoint(Point ps,String varname,String shape,String event) { try { if(end==null) end = new Point(); if(start==null) start = new Point(); if(shape.equals("elipse")) selected="elipse"; else if(shape.equals("line")) selected="line"; else if(shape.equals("rect")) selected="rect"; else if(shape.equals("erase")) { selected="erase"; erase(); } if(end!=null && start!=null) { if(varname.equals("end")) end=ps; if(varname.equals("mp")) mp=ps; if(varname.equals("start")) start=ps; if(event.equals("drag")) repaint(); else if(event.equals("release")) draw(); } } catch(Exception e) { e.printStackTrace(); } } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); pic.setPaint(Color.white); pic.fillRect(start.x, start.y, 10, 10); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); JPanel row1=new JPanel(); JPanel row2=new JPanel(); JPanel row3=new JPanel(); JPanel row4=new JPanel(); buttonpanel.setPreferredSize(new Dimension(80,80)); //buttonpanel.setMinimumSize(new Dimension(150,150)); row1.setLayout(new BoxLayout(row1,BoxLayout.X_AXIS)); row1.setPreferredSize(new Dimension(150,150)); row2.setLayout(new BoxLayout(row2,BoxLayout.X_AXIS)); row3.setLayout(new BoxLayout(row3,BoxLayout.X_AXIS)); row4.setLayout(new BoxLayout(row4,BoxLayout.X_AXIS)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener( this); save.addActionListener( this); erase.addActionListener( this); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row1.add(elipse); row1.add(Box.createRigidArea(new Dimension(5,0))); row1.add(rectangle); buttonpanel.add(row1); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row2.add(line); row2.add(Box.createRigidArea(new Dimension(5,0))); row2.add(empty); buttonpanel.add(row2); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row3.add(save); buttonpanel.add(row3); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row4.add(erase); buttonpanel.add(row4); return buttonpanel; } //To save the image drawn public void save() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); JFileChooser fc = new JFileChooser(); fc.showSaveDialog(this); encoder.encode(image); byte[] jpgData = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg"); fos.write(jpgData); fos.close(); //add replce confirmation here } catch (IOException e) { System.out.println(e); } } public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase") { start=e.getPoint(); client.broadcast(start,"start", selected,"press"); } else if(selected=="elipse"||selected=="rect") { mp = e.getPoint(); client.broadcast(mp,"mp", selected,"press"); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release"); } else if(selected=="elipse"||selected=="rect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release"); } draw(); } //start=null; } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"drag"); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag"); } else if(selected=="elipse"||selected=="rect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(start,"start", selected,"drag"); client.broadcast(end,"end", selected,"drag"); } repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; if(e.getSource()==rectangle) selected="rect"; if(e.getSource()==save) save(); if(e.getSource()==erase) { selected="erase"; erase(); } } } class Button extends JButton { String name; public Button(String name) { this.name=name; Dimension buttonSize = new Dimension(35,35); setMaximumSize(buttonSize); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); } }

    Read the article

  • How to save image drawn on a JPanel?

    - by swift
    I have a panel with transparent background which i use to draw an image. now problem here is when i draw anything on panel and save the image as a JPEG file its saving the image with black background but i want it to be saved as same, as i draw on the panel. what should be done for this? plz guide me j Client.java public class Client extends Thread { static DatagramSocket datasocket; static DatagramSocket socket; Point point; Whiteboard board; Virtualboard virtualboard; JLayeredPane layerpane; BufferedImage image; public Client(DatagramSocket datasocket) { Client.datasocket=datasocket; } //This function is responsible to connect to the server public static void connect() { try { socket=new DatagramSocket (9000); //client connection socket port= 9000 datasocket=new DatagramSocket (9005); //client data socket port= 9002 ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); //this is to tell server that this is a connection request dos.writeChar('c'); dos.close(); byte[]data=baos.toByteArray(); //Server IP address InetAddress ip=InetAddress.getByName("10.123.97.154"); //create the UDP packet DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000); socket.send(packet); Client client=new Client(datasocket); client.createFrame(); client.run(); } catch(Exception e) { e.printStackTrace(); } } //This function is to create the JFrame public void createFrame() { JFrame frame=new JFrame("Whiteboard"); frame.setVisible(true); frame.setBackground(Color.black); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(680,501); frame.addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { close(); } }); layerpane=frame.getLayeredPane(); board= new Whiteboard(datasocket); image = new BufferedImage(590,463, BufferedImage.TYPE_INT_ARGB); board.setBounds(74,2,590,463); board.setImage(image); virtualboard=new Virtualboard(); virtualboard.setImage(image); virtualboard.setBounds(74,2,590,463); layerpane.add(virtualboard,new Integer(2));//Panel where remote user draws layerpane.add(board,new Integer(3)); layerpane.add(board.colourButtons(),new Integer(1)); layerpane.add(board.shapeButtons(),new Integer(0)); //frame.add(paper.addButtons(),BorderLayout.WEST); } /* * This function is overridden from the thread class * This function listens for incoming packets from the server * which contains the points drawn by the other client */ public void run () { while (true) { try { byte[] buffer = new byte[512]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datasocket.receive(packet); InputStream in=new ByteArrayInputStream(packet.getData(), packet.getOffset(),packet.getLength()); DataInputStream din=new DataInputStream(in); int x=din.readInt(); int y=din.readInt(); String varname=din.readLine(); String var[]=varname.split("-",4); point=new Point(x,y); virtualboard.addPoint(point, var[0], var[1],var[2],var[3]); } catch (IOException ex) { ex.printStackTrace(); } } } //This function is to broadcast the newly drawn point to the server public void broadcast (Point p,String varname,String shape,String event, String color) { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); dos.writeInt(p.x); dos.writeInt(p.y); dos.writeBytes(varname); dos.writeBytes("-"); dos.writeBytes(shape); dos.writeBytes("-"); dos.writeBytes(event); dos.writeBytes("-"); dos.writeBytes(color); dos.close(); byte[]data=baos.toByteArray(); InetAddress ip=InetAddress.getByName("10.123.97.154"); DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8002); datasocket.send(packet); } catch (Exception e) { e.printStackTrace(); } } //This function is to close the client's connection with the server public void close() { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); //This is to tell server that this is request to remove the client dos.writeChar('r'); dos.close(); byte[]data=baos.toByteArray(); //Server IP address InetAddress ip=InetAddress.getByName("10.123.97.154"); DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000); socket.send(packet); System.out.println("closed"); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { connect(); } } Whiteboard.java class Whiteboard extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener { BufferedImage image; Boolean tooltip=false; int post; String shape; String selectedcolor="black"; Color color=Color.black; //Color color=Color.white; Point start; Point end; Point mp; Point tip; int keycode; String fillshape; Point fillstart=new Point(); Point fillend=new Point(); int noofside; Button r=new Button("rect"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button roundrect=new Button("roundrect"); Button polygon=new Button("poly"); Button text=new Button("text"); JButton save=new JButton("Save"); Button elipse=new Button("elipse"); ImageIcon fillicon=new ImageIcon("images/fill.jpg"); JButton fill=new JButton(fillicon); ImageIcon erasericon=new ImageIcon("images/eraser.gif"); JButton erase=new JButton(erasericon); JButton[] colourbutton=new JButton[28]; String selected; Point label; String key=""; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Boolean first; int w,h; public Whiteboard(DatagramSocket dataSocket) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } setLayout(null); setOpaque(false); setBackground(new Color(237,237,237)); this.dataSocket=dataSocket; client=new Client(dataSocket); addKeyListener(this); addMouseListener(this); addMouseMotionListener(this); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { try { super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; if(color!=null) g2.setPaint(color); if(start!=null && end!=null) { if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); else if(selected==("poly")) { g2.drawLine(start.x,start.y,end.x,end.y); client.broadcast(start, "start", "poly", "drag", selectedcolor); client.broadcast(end, "end", "poly", "drag", selectedcolor); } } if(tooltip==true) { System.out.println(selected); if(selected=="text") { g2.drawString("|", tip.x, tip.y-5); g2.drawString("Click to add text", tip.x+10, tip.y+23); g2.drawString("__", label.x+post, label.y); } if(selected=="erase") { g2.setPaint(new Color(237,237,237)); g2.fillRect(tip.x-10,tip.y-10,10,10); g2.setPaint(color); g2.drawRect(tip.x-10,tip.y-10,10,10); } } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = (Graphics2D) image.createGraphics(); Font font=new Font("Times New Roman",Font.PLAIN,14); g2.setFont(font); g2.setPaint(color); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("poly")) { g2.drawLine(start.x,start.y,end.x,end.y); client.broadcast(start, "start", "poly", "release", selectedcolor); client.broadcast(end, "end", "poly", "release", selectedcolor); } fillstart=start; fillend=end; fillshape=selected; } if(selected!="poly") { start=null; end=null; } if(label!=null) { if(selected==("text")) { g2.drawString(key,label.x,label.y); client.broadcast(label, key, "text", "release", selectedcolor); } } repaint(); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.createGraphics(); Color erasecolor=new Color(237,237,237); pic.setPaint(erasecolor); if(start!=null) pic.fillRect(start.x-10, start.y-10, 10, 10); } //To set the size of the image public void setImage(BufferedImage image) { this.image = image; } //Function to add buttons into the panel, calling this function returns a panel public JPanel shapeButtons() { JPanel shape=new JPanel(); shape.setBackground(new Color(181, 197, 210)); shape.setLayout(new GridLayout(5,2,2,4)); shape.setBounds(0, 2, 74, 166); rectangle.addActionListener(this); rectangle.setToolTipText("Rectangle"); line.addActionListener( this); line.setToolTipText("Line"); erase.addActionListener(this); erase.setToolTipText("Eraser"); roundrect.addActionListener(this); roundrect.setToolTipText("Round edge Rectangle"); polygon.addActionListener(this); polygon.setToolTipText("Polygon"); text.addActionListener(this); text.setToolTipText("Text"); fill.addActionListener(this); fill.setToolTipText("Fill with colour"); elipse.addActionListener(this); elipse.setToolTipText("Elipse"); save.addActionListener(this); shape.add(elipse); shape.add(rectangle); shape.add(roundrect); shape.add(polygon); shape.add(line); shape.add(text); shape.add(fill); shape.add(erase); shape.add(save); return shape; } public JPanel colourButtons() { JPanel colourbox=new JPanel(); colourbox.setBackground(new Color(181, 197, 210)); colourbox.setLayout(new GridLayout(8,2,8,8)); colourbox.setBounds(0,323,70,140); //colourbox.add(empty); for(int i=0;i<16;i++) { colourbutton[i]=new JButton(); colourbox.add(colourbutton[i]); if(i==0) colourbutton[0].setBackground(Color.black); else if(i==1) colourbutton[1].setBackground(Color.white); else if(i==2) colourbutton[2].setBackground(Color.red); else if(i==3) colourbutton[3].setBackground(Color.orange); else if(i==4) colourbutton[4].setBackground(Color.blue); else if(i==5) colourbutton[5].setBackground(Color.green); else if(i==6) colourbutton[6].setBackground(Color.pink); else if(i==7) colourbutton[7].setBackground(Color.magenta); else if(i==8) colourbutton[8].setBackground(Color.cyan); else if(i==9) colourbutton[9].setBackground(Color.black); else if(i==10) colourbutton[10].setBackground(Color.yellow); else if(i==11) colourbutton[11].setBackground(new Color(131,168,43)); else if(i==12) colourbutton[12].setBackground(new Color(132,0,210)); else if(i==13) colourbutton[13].setBackground(new Color(193,17,92)); else if(i==14) colourbutton[14].setBackground(new Color(129,82,50)); else if(i==15) colourbutton[15].setBackground(new Color(64,128,128)); colourbutton[i].addActionListener(this); } return colourbox; } public void fill() { if(selected=="fill") { Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setPaint(color); System.out.println("Fill"); if(fillshape=="elipse") g2.fillOval(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y)); else if(fillshape=="rect") g2.fillRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y)); else if(fillshape==("rrect")) g2.fillRoundRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y),11,11); // else if(fillshape==("poly")) // g2.drawPolygon(x,y,2); } repaint(); } //To save the image drawn public void save() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); JFileChooser fc = new JFileChooser(); fc.showSaveDialog(this); encoder.encode(image); byte[] jpgData = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg"); fos.write(jpgData); fos.close(); //add replce confirmation here } catch (IOException e) { System.out.println(e); } } public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="text") { start=e.getPoint(); client.broadcast(start,"start", selected,"press", selectedcolor); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") mp = e.getPoint(); else if(selected=="poly") { if(first==true) { start=e.getPoint(); //client.broadcast(start,"start", selected,"press", selectedcolor); } else if(first==false) { end=e.getPoint(); repaint(); //client.broadcast(end,"end", selected,"press", selectedcolor); } } else if(selected=="erase") { start=e.getPoint(); erase(); } } public void mouseReleased(MouseEvent e) { if(selected=="text") { System.out.println("Reset"); key=""; post=0; label=new Point(); label=e.getPoint(); grabFocus(); } if(start!=null && end!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release", selectedcolor); draw(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release", selectedcolor); draw(); } else if(selected=="poly") { draw(); first=false; start=end; end=null; } } } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"drag", selectedcolor); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag", selectedcolor); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(start,"start", selected,"drag", selectedcolor); client.broadcast(end,"end", selected,"drag", selectedcolor); } else if(selected=="poly") end=e.getPoint(); System.out.println(tooltip); if(tooltip==true) { if(selected=="erase") { Graphics2D g2=(Graphics2D) getGraphics(); tip=e.getPoint(); g2.drawRect(tip.x-10,tip.y-10,10,10); } } repaint(); } public void mouseMoved(MouseEvent e) { if(selected=="text" ||selected=="erase") { tip=new Point(); tip=e.getPoint(); tooltip=true; repaint(); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; else if(e.getSource()==line) selected="line"; else if(e.getSource()==rectangle) selected="rect"; else if(e.getSource()==erase) { selected="erase"; tooltip=true; System.out.println(selected); erase(); } else if(e.getSource()==roundrect) selected="rrect"; else if(e.getSource()==polygon) { selected="poly"; first=true; start=null; } else if(e.getSource()==text) { selected="text"; tooltip=true; } else if(e.getSource()==fill) { selected="fill"; fill(); } else if(e.getSource()==save) save(); if(e.getSource()==colourbutton[0]) { color=Color.black; selectedcolor="black"; } else if(e.getSource()==colourbutton[1]) { color=Color.white; selectedcolor="white"; } else if(e.getSource()==colourbutton[2]) { color=Color.red; selectedcolor="red"; } else if(e.getSource()==colourbutton[3]) { color=Color.orange; selectedcolor="orange"; } else if(e.getSource()==colourbutton[4]) { selectedcolor="blue"; color=Color.blue; } else if(e.getSource()==colourbutton[5]) { selectedcolor="green"; color=Color.green; } else if(e.getSource()==colourbutton[6]) { selectedcolor="pink"; color=Color.pink; } else if(e.getSource()==colourbutton[7]) { selectedcolor="magenta"; color=Color.magenta; } else if(e.getSource()==colourbutton[8]) { selectedcolor="cyan"; color=Color.cyan; } } @Override public void keyPressed(KeyEvent e) { //System.out.println(e.getKeyChar()+" : "+e.getKeyCode()); if(label!=null) { if(e.getKeyCode()==10) //Check for Enter key { label.y=label.y+14; key=""; post=0; repaint(); } else if(e.getKeyCode()==8) //Backspace { try{ Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setPaint(new Color(237,237,237)); g2.fillRect(label.x+post-7, label.y-13, 14, 17); if(post>0) post=post-6; keycode=0; key=key.substring(0, key.length()-1); System.out.println(key.substring(0, key.length())); repaint(); Point broadcastlabel=new Point(); broadcastlabel.x=label.x+post-7; broadcastlabel.y=label.y-13; client.broadcast(broadcastlabel, key, "text", "backspace", selectedcolor); } catch(Exception ex) {} } //Block invalid keys else if(!(e.getKeyCode()>=16 && e.getKeyCode()<=20 || e.getKeyCode()>=112 && e.getKeyCode()<=123 || e.getKeyCode()>=33 && e.getKeyCode()<=40 || e.getKeyCode()>=144 && e.getKeyCode()<=145 || e.getKeyCode()>=524 && e.getKeyCode()<=525 ||e.getKeyCode()==27||e.getKeyCode()==155 ||e.getKeyCode()==127)) { key=key+e.getKeyChar(); post=post+6; draw(); } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } class Button extends JButton { String name; int i; public Button(String name) { this.name=name; try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } } public Button(int i) { this.i=i; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); if (name== "roundrect") g.drawRoundRect(5,5,25,23,10,10); int a[]=new int[]{20,9,20,23,20}; int b[]=new int[]{9,23,25,20,9}; if (name== "poly") g.drawPolyline(a, b, 5); if (name== "text") g.drawString("Text",8, 24); } }

    Read the article

< Previous Page | 1 2