Another JTable Printing Problem!


I finally was able to print my table on different pages without the awkward clipping. Now, new problem occurs:

1. The printed result(font size and row height) are different with maximize window and not. I think the result varies on how the application window was viewed. So how can i fix the size of print result with any window size

2. How can i reduce the font size and row height of the table on print The default size in the application display fits well, but when it was printed, the size is too big and looks un-professional.

Ive been working on this for a week now, any help will be appreciated greatly.
Posted On: Tuesday 23rd of October 2012 11:32:45 PM Total Views:  213
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




Setting JTable model after fetching data on another thread

Hi , I am new to Swing and I have a question. I need to show data on a JFrame. Here are the steps i need to do: 1. creating a JFrame 2. Setting the frame visible 2. fetching data on a seperate thread 3. setting the data in a Table Model 4. creating the table using this table model 5. firing model event But the table is not getting refreshed with the newly fetched data. Any suggestions on how I can get this working will be greatly appreciated.
VIEWS ON THIS POST

83

Posted on:

Thursday 18th October 2012
View Replies!

JComboBox event triggers another JComboBox

I have two JComboBox say 'A' and 'B'. I want event change(item selection) on 'A' to trigger automatic change on another JComboBox 'B'. Items(contents) in 'B' are dynamically read from somewhere. I looked API but didn't find suitable methods. I am sure there must be a way to do the job, but couldn't figure it out. Can anyone please give me suggestion or any code snippets would be appreciated.
VIEWS ON THIS POST

76

Posted on:

Thursday 18th October 2012
View Replies!

Jtable data passing one frame to another frame

I am very new to this this. But want to resolve this java swing problem asap. I have two jframes in two classes. First one is customer and second frame is Sales form. I want to fill some textfields in the sales class from the customer jtable(that in the customer class). Once the getCustomerDetails jbutton click in sales class, customer class should visible with customer jtable. And selected row data in customer table should come to the sales form and update sales class text fields. Both sales and Customer classes extends jframe. And im using beans binding to get the selected row from the jtable. I know that i have to use mouseListner event to perform this, But do not know to use this for this. Please let me know how can I perform this. Im using netbeans IDE to generate the GUI. In the customerTable is selected index property use to get the correct index of customerList (ArrayList) Hope community feedback soon. Here I have illustrated sales class, Customer class and pojo class sample coding with this. Sales class package TES; /** * * @author Ruchira Kariyawasam */ public class Sales extends javax.swing.JFrame { /** Creates new form Sales */ public Sales() { initComponents(); } @SuppressWarnings("unchecked") // private void initComponents() { jPanel1 = new javax.swing.JPanel(); custIDTextField = new javax.swing.JTextField(); custNameTextField = new javax.swing.JTextField(); custAddressTextField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("SALES"); // NOI18N jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel1.setText("Customer ID "); // NOI18N jLabel2.setText("Customer Name "); // NOI18N jLabel3.setText("Customer Name "); jButton1.setText("Get Customer Details"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel1)) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(custNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE) .addComponent(custIDTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE) .addComponent(custAddressTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(72, 72, 72) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(custIDTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(custNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(custAddressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(45, 45, 45) .addComponent(jButton1) .addContainerGap(86, Short.MAX_VALUE)) ); 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(19, 19, 19) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(30, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(81, Short.MAX_VALUE)) ); pack(); }// public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Sales().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTextField custAddressTextField; private javax.swing.JTextField custIDTextField; private javax.swing.JTextField custNameTextField; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; // End of variables declaration }
VIEWS ON THIS POST

77

Posted on:

Monday 22nd October 2012
View Replies!

calling another swing application to run when a button is click from my swing application

this is my code import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyClass { public static void main(String args[]) { MyFrame mf = new MyFrame(); mf.setVisible(true); mf.setSize(400,400); mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class MyFrame extends JFrame { public MyFrame() { MyFramePanel mfp = new MyFramePanel(); add(mfp); mfp.setSize(100,100); } } class MyFramePanel extends JPanel implements ActionListener { JButton OkBtn,exitBtn; JLabel name,address,phone; JTextField nameField,phoneField; JTextArea addressField; public MyFramePanel() { setLayout(new BorderLayout()); JPanel centerPanel = new JPanel(new GridLayout(3,2)); name = new JLabel("Name :"); nameField = new JTextField(20); address = new JLabel("Address :"); addressField = new JTextArea(5,6); phone = new JLabel("Phone :"); phoneField = new JTextField(20); centerPanel.add(name); centerPanel.add(nameField); centerPanel.add(address); centerPanel.add(addressField); centerPanel.add(phone); centerPanel.add(phoneField); add(centerPanel,BorderLayout.CENTER); JPanel buttonPanel =new JPanel(); OkBtn = new JButton("OK"); OkBtn.addActionListener(this); exitBtn = new JButton("EXIT"); exitBtn.addActionListener(this); buttonPanel.add(OkBtn); buttonPanel.add(exitBtn); add(buttonPanel,BorderLayout.SOUTH); } public void actionPerformed(ActionEvent evt){ //TransferClass tc = new TransferClass(); Object source = evt.getSource(); if(source == OkBtn){ System.out.println("OK button is clicked"); TransferClass tc = new TransferClass(); //tc.setVisible(true); System.exit(0); } else if (source == exitBtn){ System.out.println("EXIT button is clicked"); } } }
VIEWS ON THIS POST

88

Posted on:

Monday 22nd October 2012
View Replies!

How do I pass a frame into another class?

On line #271 I am trying to pass the frame into Title class so that it can open a JDialog, but I am stumped on how to pass the frame into the class. import java.awt.*; import java.awt.event.*; import java.awt.font.*; import java.io.*; import java.lang.Integer; import java.util.*; import javax.swing.*; /** * The main application of an automotive history system * @author Mike Lipay * @version 1.0 */ public class AutoHistory { public static void main (String args[]) { displayMenu(); } /** * Display main window to the user */ public static void displayMenu() { EventQueue.invokeLater (new Runnable() { public void run() { MainFrame frame = new MainFrame(); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setFocus(); } }); } } /** * Create the window frame */ class MainFrame extends JFrame { static int windowWidth = 400; static int windowHeight = 250; // Combo box fields private JPanel comboPanel = new JPanel(); private JComboBox vehicleCombo = new JComboBox(); // Main panel fields private JPanel ahPanel = new JPanel(); private JTextField textFld = new JTextField(); // Text fields JTextField vinTxtFld = new JTextField(); JTextField yearTxtFld = new JTextField(); JTextField makeTxtFld = new JTextField(); JTextField modelTxtFld = new JTextField(); JTextField pkgTxtFld = new JTextField(); // Button fields private JPanel buttonPanel = new JPanel(); private JButton button = new JButton(); JButton titleButton = new JButton("Title"); JButton buySellButton = new JButton("Buy / Sell"); JButton registrationButton = new JButton("Registration"); JButton insuranceButton = new JButton("Insurance"); JButton serviceButton = new JButton("Service"); JButton saveButton = new JButton("Save"); JButton clearButton = new JButton("Clear"); JButton removeButton = new JButton("Remove"); // Fields from the Vehicle Identification File (VIF.obj) VIF VIFarray = new VIF (); VIF VIFentry = new VIF ( "", "", "", "", ""); /** * Sets the focus to the VIN field */ public void setFocus () { vehicleCombo.requestFocusInWindow(); return; } /** * Create the main frame which enables the selection of or addition of * vehicles to the Vehicle Identification File (VIF.obj) */ public MainFrame() { // Main window setup setLocationByPlatform(true); setSize(windowWidth, windowHeight); setTitle("Vehicle History"); // Build Vehicle Combo Box VIFarray.loadVIF(); GridBagLayout layout = new GridBagLayout(); setLayout(layout); vehicleCombo.setEditable(false); vehicleCombo.addItem("Add New Vehicle"); do { VIFentry = VIFarray.readnextVIF(); if (VIFentry != null) { vehicleCombo.addItem ( VIFentry.getVIN() + ", " + VIFentry.getYear() + ", " + VIFentry.getMake() + ", " + VIFentry.getModel() + ", " + VIFentry.getPkg() ); } } while (VIFentry != null); comboPanel.add(vehicleCombo); add (comboPanel, new GBC(0,0,4,1)); // VIN add (new JLabel (" VIN: "), new GBC(0,1).setAnchor(GBC.EAST)); add (vinTxtFld, new GBC (1,1,2,1).setFill(GBC.HORIZONTAL).setWeight(100,0).setInsets(1)); TextAction vinAction = new TextAction(vinTxtFld); vinTxtFld.addFocusListener(vinAction); // Year add (new JLabel (" Year: "), new GBC(0,2).setAnchor(GBC.EAST)); add (yearTxtFld, new GBC (1,2).setFill(GBC.HORIZONTAL).setWeight(100,0).setInsets(1)); // Make add (new JLabel (" Make: "), new GBC(0,3).setAnchor(GBC.EAST)); add (makeTxtFld, new GBC (1,3,2,1).setFill(GBC.HORIZONTAL).setWeight(100,0).setInsets(1)); // Model add (new JLabel (" Model: "), new GBC(0,4).setAnchor(GBC.EAST)); add (modelTxtFld, new GBC (1,4,2,1).setFill(GBC.HORIZONTAL).setWeight(100,0).setInsets(1)); // Package add (new JLabel (" Pkg: "), new GBC(0,5).setAnchor(GBC.EAST)); add (pkgTxtFld, new GBC (1,5,2,1).setFill(GBC.HORIZONTAL).setWeight(100,0).setInsets(1)); // Add the panel to the frame add(ahPanel); // add the Title button to panel add (titleButton, new GBC(3,1).setAnchor(GBC.WEST).setFill(GBC.HORIZONTAL)); ButtonAction titleAction = new ButtonAction(titleButton); titleButton.addActionListener(titleAction); // Add the Buy/Sell button to panel add (buySellButton, new GBC(3,2).setAnchor(GBC.WEST).setFill(GBC.HORIZONTAL)); ButtonAction buySellAction = new ButtonAction(buySellButton); buySellButton.addActionListener(buySellAction); // Add the Registration button to panel add (registrationButton, new GBC(3,3).setAnchor(GBC.WEST).setFill(GBC.HORIZONTAL)); ButtonAction registrationAction = new ButtonAction(registrationButton); registrationButton.addActionListener(registrationAction); // Add the Insurance button to panel add (insuranceButton, new GBC(3,4).setAnchor(GBC.WEST).setFill(GBC.HORIZONTAL)); ButtonAction insuranceAction = new ButtonAction(insuranceButton); insuranceButton.addActionListener(insuranceAction); // Add the Service button to panel add (serviceButton, new GBC(3,5).setAnchor(GBC.WEST).setFill(GBC.HORIZONTAL)); ButtonAction serviceAction = new ButtonAction(serviceButton); serviceButton.addActionListener(serviceAction); // Add the Save button to panel add (saveButton, new GBC(1,6).setAnchor(GBC.EAST).setFill(GBC.HORIZONTAL).setWeight(33,0)); ButtonAction saveAction = new ButtonAction(saveButton); saveButton.addActionListener(saveAction); // Add the Clear button to panel add (clearButton, new GBC(2,6).setAnchor(GBC.EAST).setFill(GBC.HORIZONTAL).setWeight(33,0)); ButtonAction clearAction = new ButtonAction(clearButton); clearButton.addActionListener(clearAction); // Add the Remove button to panel add (removeButton, new GBC(3,6).setAnchor(GBC.WEST).setFill(GBC.HORIZONTAL).setWeight(33,0)); ButtonAction removeAction = new ButtonAction(removeButton); removeButton.addActionListener(removeAction); // Set the visibility for the fields setVisibility("add"); /** * An action listener that handles combo selects */ vehicleCombo.addActionListener (new ActionListener() { public void actionPerformed(ActionEvent event) { String selectedItem = (String) vehicleCombo.getSelectedItem(); if (selectedItem.equals("Add New Vehicle")) { setVisibility("add"); clearFields(); vinTxtFld.requestFocus(); } else { setVisibility("chg"); VIF VIFentry = new VIF( "", "", "", "", ""); String [] temp = selectedItem.split(","); VIFentry = VIFarray.readVIF(temp[0]); vinTxtFld.setText(VIFentry.getVIN()); yearTxtFld.setText(VIFentry.getYear()); makeTxtFld.setText(VIFentry.getMake()); modelTxtFld.setText(VIFentry.getModel()); pkgTxtFld.setText(VIFentry.getPkg()); } } }); } /** * An action listener that handles button clicks */ private class ButtonAction implements ActionListener { public ButtonAction(JButton b) { button = b; } public void actionPerformed(ActionEvent event) { String buttonSelected = event.getActionCommand(); if (buttonSelected.equals("Title")) { String temp = (String) vehicleCombo.getSelectedItem(); Title.Title(this, temp); return; } if (buttonSelected.equals("Buy / Sell")) return; if (buttonSelected.equals("Registration")) return; if (buttonSelected.equals("Insurance")) return; if (buttonSelected.equals("Service")) return; // Save the new / changed record if (buttonSelected.equals("Save")) { // Check if all fields are populated if ((yearTxtFld.getText().length() == 0) || (makeTxtFld.getText().length() == 0) || (modelTxtFld.getText().length() == 0) || (pkgTxtFld.getText().length() == 0)) { sendMessage(" fields must be populated and VIN must be unique."); if (pkgTxtFld.getText().length() == 0) KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(modelTxtFld); if (modelTxtFld.getText().length() == 0) KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(makeTxtFld); if (makeTxtFld.getText().length() == 0) KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(yearTxtFld); if (yearTxtFld.getText().length() == 0) KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(vinTxtFld); return; } // Make sure the year is between 1900 and 2100 if ((Integer.parseInt(yearTxtFld.getText()) < 1900) || (Integer.parseInt(yearTxtFld.getText()) > 2100)) { sendMessage("Year must be between 1900 and 2100"); return; } // If the VIN exists change the record, otherwise add it VIFentry = VIFarray.readVIF(vinTxtFld.getText()); if (VIFentry != null) { VIFarray.changeVIF ( vinTxtFld.getText(), yearTxtFld.getText(), makeTxtFld.getText(), modelTxtFld.getText(), pkgTxtFld.getText() ); VIFarray.saveVIF(); sendMessage("Vehicle changed."); } else { int index = VIFarray.addVIF ( vinTxtFld.getText(), yearTxtFld.getText(), makeTxtFld.getText(), modelTxtFld.getText(), pkgTxtFld.getText() ); VIFarray.saveVIF(); sendMessage("Vehicle added."); String temp = ( vinTxtFld.getText() + ", " + yearTxtFld.getText() + ", " + makeTxtFld.getText() + ", " + modelTxtFld.getText() + ", " + pkgTxtFld.getText()); vehicleCombo.insertItemAt(temp, index); vehicleCombo.setSelectedIndex(index); } // Save the changes setVisibility("chg"); return; } // Clear all of the fields in the window if (buttonSelected.equals("Clear")) { setVisibility("clr"); clearFields(); vehicleCombo.setSelectedItem("Add New Vehicle"); return; } // Remove vehicle from array if (buttonSelected.equals("Remove")) { String selectedItem = (String) vehicleCombo.getSelectedItem(); String [] temp = selectedItem.split(","); VIFarray.deleteVIF(temp[0]); VIFarray.saveVIF(); vehicleCombo.removeItem(selectedItem); sendMessage("Vehicle has been removed."); return; } } } /** * An action listener that handles text actions */ private class TextAction implements FocusListener { public TextAction(JTextField t) { textFld = t; } public void focusLost(FocusEvent event) { String VIN = textFld.getText().toUpperCase(); textFld.setText(VIN); VIF VIFentry = new VIF ( "", "", "", "", ""); VIFentry = VIFarray.readVIF(VIN); if (VIN.length() == 0) return; if ((VIN.length() != 17) || (VIN.contains("I")) || (VIN.contains("O")) || (VIN.contains("Q")) || (VIFentry != null)) { sendMessage("VIN must be unique, 17 characters in length and not contain \"I\", \"O\", or \"Q\"."); KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent(vinTxtFld); return; } // Enable fields & buttons setVisibility("nw2"); KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(vinTxtFld); } public void focusGained(FocusEvent event) {} } // Enable / disable fields and buttons public void setVisibility (String func) { // First disable everything vinTxtFld.setEnabled(false); yearTxtFld.setEnabled(false); makeTxtFld.setEnabled(false); modelTxtFld.setEnabled(false); pkgTxtFld.setEnabled(false); titleButton.setEnabled(false); buySellButton.setEnabled(false); registrationButton.setEnabled(false); insuranceButton.setEnabled(false); serviceButton.setEnabled(false); saveButton.setEnabled(false); clearButton.setEnabled(false); removeButton.setEnabled(false); // Now enable just what is needed based on function if (func.equals("add") || func.equals("clr")) vinTxtFld.setEnabled(true); if (func.equals("chg") || func.equals("nw2")) yearTxtFld.setEnabled(true); if (func.equals("chg") || func.equals("nw2")) makeTxtFld.setEnabled(true); if (func.equals("chg") || func.equals("nw2")) modelTxtFld.setEnabled(true); if (func.equals("chg") || func.equals("nw2")) pkgTxtFld.setEnabled(true); if (func.equals("chg")) titleButton.setEnabled(true); if (func.equals("chg")) buySellButton.setEnabled(true); if (func.equals("chg")) registrationButton.setEnabled(true); if (func.equals("chg")) insuranceButton.setEnabled(true); if (func.equals("chg")) serviceButton.setEnabled(true); if (func.equals("chg") || func.equals("nw2")) saveButton.setEnabled(true); if (func.equals("chg") || func.equals("nw2")) clearButton.setEnabled(true); if (func.equals("chg")) removeButton.setEnabled(true); } // Clear all text fields public void clearFields() { vinTxtFld.setText(""); yearTxtFld.setText(""); makeTxtFld.setText(""); modelTxtFld.setText(""); pkgTxtFld.setText(""); } // Send message dialog public void sendMessage(String msg) { JOptionPane.showMessageDialog( ahPanel, msg, "Message Dialog", JOptionPane.INFORMATION_MESSAGE); } }
VIEWS ON THIS POST

73

Posted on:

Monday 22nd October 2012
View Replies!

Update GUI components from another thread.

It has been a while since I last had the chance to do anything with Swing or AWT, so I am a little bit rusty to say the least, so be kind and bare with me. I have a program that I wrote a while back that I would like to replace the console output with a simple GUI. The original program fills a number of arrays with information from several files, prints an initial state, then starts several threads that as they change the contents of the arrays, they print the changes to the console. I would like to replace the console output with something that tells the GUI to update a specific components or all components. The first couple of things were easy, I have a new program that loads the arrays with the information from the files and a GUI that fills several JLists based on those arrays. Right now I am wondering if there is anything I can do within the original threads that will allow me to update the GUI or if it would be better to start a SwingWorker that monitors the arrays and updates the JLists while the other threads are running.
VIEWS ON THIS POST

77

Posted on:

Monday 22nd October 2012
View Replies!

how will we move from one page to another within the same window in Swing?

I am new to Swing. I am trying to understand it. My problem is, I have created one login form which has username and password fields in it, when ever user clicks submit button, it has to show another page within the same window. But for me whenever he clicks submit button in the login form page , another new window is opening. Please someone help me with this problem.
VIEWS ON THIS POST

78

Posted on:

Monday 22nd October 2012
View Replies!

How do i put a graphic behind another graphic icon?

I have a bigger graphic that i want to put beind the smaller graphic icon as its background. The smaller icon should be centered inside the bigger graphic. How do i do this
VIEWS ON THIS POST

62

Posted on:

Monday 22nd October 2012
View Replies!

Drag and drop a table from 1 frame to another frame

Hi is it possible to drag and drop a table (with rows and columns) to another frame in swings.If anyone have idea pl help me. I am able to drag and drop checkbox from 1 frame to other frame.
VIEWS ON THIS POST

79

Posted on:

Monday 22nd October 2012
View Replies!

Help adding JButton to a JPanel from another method!

Hi all, I have a bit of a problem, I am trying to add some JButtons into a JPanel from a method call that is triggered by a buttons actionlistener, the problem i have got is when it comes to adding the button it does not show on the JPanel but if i get the component count of the JPanel it shows it as being there. I am using Netbeans 6.5 and using a FlowLayout for my JPanel, this is what i have in my first JPanel that i have i add buttons to it when the JPanel is created and this works fine categoryPane = new javax.swing.JPanel(); categoryPane.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); categoryPane.setName("categoryPane"); ProductRepository prodRepo = new ProductRepository(); ArrayList catName = prodRepo.getCategoryName(parentName); int i = 0; Font font = new Font("Button Font", Font.PLAIN, 24); while (i < catName.size()) { JButton button = new JButton(catName.get(i)); button.setFont(font); button.setActionCommand(catName.get(i)); button.addActionListener(new CatListener()); button.setVisible(true); categoryPane.add(button); i++; }
VIEWS ON THIS POST

75

Posted on:

Monday 22nd October 2012
View Replies!

JButton that runs another Java program

all. I am currently working on a Java project that is due to be completed soon (so I may have a few questions at a later date). Admitedly, I'm not very good at programming and much of my code so far is a bit of a mish mash of stuff that I have found by searching the net. I have a program that runs correctly in DOS with a few changes I need to make at a later date. I also currently have a GUI that displays as I would like it to. However, I am at the stage of adding Action Events and cannot find too much help elsewhere. I have my jbuttons and one of these, when clicked on, I want it to run the other program I have created. The output of this program is a text file and I would like it to be possible to open this text file when a 2nd jbutton is clicked on. Is this possible and any pointers
VIEWS ON THIS POST

65

Posted on:

Monday 22nd October 2012
View Replies!

Table sorter going nuts once added another itam

Howdy, I've successfully implemented the table sorter from the sun website. Problem is when I add another item to the table - I get an ArrayIndexOutOfBoundsException.ArrayIndexOutOfBoundsException. specifying the problem at: return getViewToModel()[viewIndex].modelIndex; in public int modelIndex(int viewIndex) { return getViewToModel()[viewIndex].modelIndex; } does anyone know what might be the problem thanks the complete error is below. java.lang.ArrayIndexOutOfBoundsException: 8 at com.jhexagon.incentive.utilities.jtable.Renderer.TableSorter.modelIndex(TableSorter.java:206) at com.jhexagon.incentive.utilities.jtable.Renderer.TableSorter.getValueAt(TableSorter.java:243) at javax.swing.JTable.getValueAt(Unknown Source) at javax.swing.JTable.prepareRenderer(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source) at javax.swing.plaf.ComponentUI.update(Unknown Source) at javax.swing.JComponent.paintComponent(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JViewport.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintWithOffscreenBuffer(Unknown Source) at javax.swing.JComponent.paintDoubleBuffered(Unknown Source) at javax.swing.JComponent._paintImmediately(Unknown Source) at javax.swing.JComponent.paintImmediately(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)
VIEWS ON THIS POST

83

Posted on:

Monday 22nd October 2012
View Replies!

Table sorter going nuts once added another itam

Howdy, I've successfully implemented the table sorter from the sun website. Problem is when I add another item to the table - I get an ArrayIndexOutOfBoundsException.ArrayIndexOutOfBoundsException. specifying the problem at: return getViewToModel()[viewIndex].modelIndex; in public int modelIndex(int viewIndex) { return getViewToModel()[viewIndex].modelIndex; } does anyone know what might be the problem thanks the complete error is below. java.lang.ArrayIndexOutOfBoundsException: 8 at com.jhexagon.incentive.utilities.jtable.Renderer.TableSorter.modelIndex(TableSorter.java:206) at com.jhexagon.incentive.utilities.jtable.Renderer.TableSorter.getValueAt(TableSorter.java:243) at javax.swing.JTable.getValueAt(Unknown Source) at javax.swing.JTable.prepareRenderer(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source) at javax.swing.plaf.ComponentUI.update(Unknown Source) at javax.swing.JComponent.paintComponent(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JViewport.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintWithOffscreenBuffer(Unknown Source) at javax.swing.JComponent.paintDoubleBuffered(Unknown Source) at javax.swing.JComponent._paintImmediately(Unknown Source) at javax.swing.JComponent.paintImmediately(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)
VIEWS ON THIS POST

67

Posted on:

Monday 22nd October 2012
View Replies!

another .ttf question

hey i got another question on using the .ttf files. I want to leave the commented sections out. What i was trying to do was to set the fonts individually on the components but when i tried, it typed in teeny weeny size letters, and wasent even readable. Can anyone help me out. i just want to leave the code the way it is, but just be able to set the deed components to the imported font. public Converter() { try{ InputStream in = Converter.class.getResourceAsStream("Augustin.ttf"); Font font = Font.createFont(Font.TRUETYPE_FONT,in); c = new Conversions(); super.setLayout(new GridLayout(3,1)); label1 = new JLabel("Enter Fahrenheit:"); field1 = new JTextField(5); field1.addActionListener(new FahrenheitListener()); button1 = new JButton("CONVERT"); button1.addActionListener(new FahrenheitListener()); label2 = new JLabel("to Celsius:"); field2 = new JTextField(8); field2.setEditable(false); panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel1.add(label1); panel1.add(field1); panel1.add(button1); panel1.add(label2); panel1.add(field2); add(panel1); label3 = new JLabel("Enter Celsius:"); field3 = new JTextField(5); field3.addActionListener(new CelsiusListener()); button2 = new JButton("CONVERT"); button2.addActionListener(new CelsiusListener()); label4 = new JLabel("to Fahrenheit:"); field4 = new JTextField(8); field4.setEditable(false); panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel2.add(label3); panel2.add(field3); panel2.add(button2); panel2.add(label4); panel2.add(field4); add(panel2); button3 = new JButton("CLEAR"); button3.addActionListener(new button3Listener()); button4 = new JButton("CHANGE BACKGROUND COLOR"); button4.addActionListener(new button4Listener()); button5 = new JButton("EXIT"); button5.addActionListener(new button5Listener()); panel3 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel3.add(button4); panel3.add(button3); panel3.add(button5); add(panel3); }catch(Exception ex){ex.printStackTrace();}
VIEWS ON THIS POST

72

Posted on:

Tuesday 23rd October 2012
View Replies!

Analysing if a Jpeg exists in another Jpeg

I want to write a Jpeg that recognizes if it exists in another jpeg. Example: I got a jpeg, 50*50 pixels, which I have cut out from a bigger jpeg 100*100 How Do I write a function that can tell me if picture 1 exists within picture 2 Code example please! /BondePer
VIEWS ON THIS POST

73

Posted on:

Tuesday 23rd October 2012
View Replies!

DND from one table cell to another in the same table

I've implemented dnd from a jlist to a jtable. Now I'd like to be able to drag from one cell in the table and drop into another cell in the same table. My issue is that all of the events (export and import) seem to be triggered as soon as the mouse button is pressed on a table cell, and then nothing happens when the mouse button is released over the new cell. Does anyone have experience in DND within the same JTable ms
VIEWS ON THIS POST

58

Posted on:

Tuesday 23rd October 2012
View Replies!

controlling size of part of split pane and another error

I am new to Swing. I've got two problems in the code below javascript: x() banghead 1)for some reason, the whiteboard is showing up as just a tiny sliver on the left hand side. 2)when I expand the whiteboard panel and start drawing on it, the label and the border for that component get duplicated. This code should be ready to run (MainPanel is the executable). The only prerequisite is to have some hello.gif in the same folder. import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeSelectionModel; public class MainPanel extends JPanel implements ActionListener { static JFrame frame; JTextArea textArea; JTextField textField; JList list; JTable table; JTree tree; JColorChooser colorChooser; JCheckBox toggleDnD; WebToolBar webToolBar; private WebBrowserPane browserPane; private SimpleWhiteboard whiteBoard; public MainPanel() { super(new BorderLayout()); JPanel rightPanel = createVerticalBoxPanel(); JPanel leftPanel = createVerticalBoxPanel(); JPanel topPanel = createTopPanel(); // top browserPane = new WebBrowserPane(); webToolBar = new WebToolBar(browserPane); topPanel.add(createPanelForComponent(webToolBar, "WebToolBar")); // RIGHT COLUMN // Create a color chooser. colorChooser = new JColorChooser(); rightPanel.add(createPanelForComponent(colorChooser, "JColorChooser")); // LEFT COLUMN // Create a textfield. whiteBoard = new SimpleWhiteboard(); leftPanel.add(createPanelForComponent(whiteBoard, "SimpleWhiteboard")); // Create the toggle button. toggleDnD = new JCheckBox("Turn on Drag and Drop"); toggleDnD.setActionCommand("toggleDnD"); toggleDnD.addActionListener(this); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel); splitPane.setOneTouchExpandable(true); add(topPanel, BorderLayout.NORTH); add(splitPane, BorderLayout.CENTER); add(toggleDnD, BorderLayout.PAGE_END); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); } protected JPanel createVerticalBoxPanel() { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS)); p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); return p; } protected JPanel createTopPanel() { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS)); p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); return p; } public JPanel createPanelForComponent(JComponent comp, String title) { JPanel panel = new JPanel(new BorderLayout()); panel.add(comp, BorderLayout.CENTER); if (title != null) { panel.setBorder(BorderFactory.createTitledBorder(title)); } return panel; } public void actionPerformed(ActionEvent e) { if ("toggleDnD".equals(e.getActionCommand())) { boolean toggle = toggleDnD.isSelected(); textArea.setDragEnabled(toggle); textField.setDragEnabled(toggle); list.setDragEnabled(toggle); table.setDragEnabled(toggle); tree.setDragEnabled(toggle); colorChooser.setDragEnabled(toggle); } } /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event-dispatching thread. */ private static void createAndShowGUI() { // Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); // Create and set up the window. frame = new JFrame("BasicDnD"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create and set up the content pane. JComponent newContentPane = new MainPanel(); newContentPane.setOpaque(true); // content panes must be opaque frame.setContentPane(newContentPane); // Display the window. frame.pack(); frame.setVisible(true); } 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() { createAndShowGUI(); } }); } } ------------------------------------- import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SimpleWhiteboard extends JPanel { private Point oldPoint, newPoint; protected ImageIcon image; private boolean start = true; // set up GUI and register mouse event handler public SimpleWhiteboard() { // super( "A simple whiteboard program" ); setBackground( Color.WHITE ); image = new ImageIcon( getClass().getResource( "hello.gif" ) ); addMouseMotionListener( new MouseMotionAdapter() { // anonymous inner class // store drag coordinates and repaint public void mouseDragged( MouseEvent event ) { if ( start ) { newPoint = event.getPoint(); start = false; } else { oldPoint = newPoint; newPoint = event.getPoint(); repaint(); } } public void mouseMoved( MouseEvent event ) { start = true; } } // end anonymous inner class ); // end call to addMouseMotionListener setSize( 1200, 700 ); setVisible( true ); } // end Painter constructor // draw oval in a 4-by-4 bounding box at specified location on window public void paint( Graphics g ) { if ( start ) { image.paintIcon( this, g, 0, 0 ); } else g.drawLine( oldPoint.x, oldPoint.y, newPoint.x, newPoint.y ); } public static void main( String args[] ) { SimpleWhiteboard application = new SimpleWhiteboard(); // application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class Painter ------------------------------------ // WebBrowserPane.java // WebBrowserPane is a simple Web-browsing component that // extends JEditorPane and maintains a history of visited URLs. // Java core packages import java.util.*; import java.net.*; import java.io.*; // Java extension packages import javax.swing.*; import javax.swing.event.*; public class WebBrowserPane extends JEditorPane { private List history = new ArrayList(); private int historyIndex; // WebBrowserPane constructor public WebBrowserPane() { // disable editing to enable hyperlinks setEditable( false ); } // display given URL and add it to history public void goToURL( URL url ) { displayPage( url ); history.add( url ); historyIndex = history.size() - 1; } // display next history URL in editorPane public URL forward() { historyIndex++; // do not go past end of history if ( historyIndex >= history.size() ) historyIndex = history.size() - 1; URL url = ( URL ) history.get( historyIndex ); displayPage( url ); return url; } // display previous history URL in editorPane public URL back() { historyIndex--; // do not go past beginning of history if ( historyIndex < 0 ) historyIndex = 0; // display previous URL URL url = ( URL ) history.get( historyIndex ); displayPage( url ); return url; } // display given URL in JEditorPane private void displayPage( URL pageURL ) { // display URL try { setPage( pageURL ); } // handle exception reading from URL catch ( IOException ioException ) { ioException.printStackTrace(); } } } ----------------------------- // WebToolBar.java // WebToolBar is a JToolBar subclass that contains components // for navigating a WebBrowserPane. WebToolBar includes back // and forward buttons and a text field for entering URLs. // Java core packages import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.MalformedURLException; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; public class WebToolBar extends JToolBar implements HyperlinkListener { private WebBrowserPane webBrowserPane; private JButton backButton; private JButton forwardButton; private JTextField urlTextField; // WebToolBar constructor public WebToolBar( WebBrowserPane browser ) { super( "Web Navigation" ); // register for HyperlinkEvents webBrowserPane = browser; webBrowserPane.addHyperlinkListener( this ); // create JTextField for entering URLs urlTextField = new JTextField( 25 ); urlTextField.addActionListener( new ActionListener() { // navigate webBrowser to user-entered URL public void actionPerformed( ActionEvent event ) { // attempt to load URL in webBrowserPane try { URL url = new URL( urlTextField.getText() ); webBrowserPane.goToURL( url ); } // handle invalid URL catch ( MalformedURLException urlException ) { urlException.printStackTrace(); } } } ); // create JButton for navigating to previous history URL backButton = new JButton( new ImageIcon( getClass().getResource( "images/back.gif" ) ) ); backButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { // navigate to previous URL URL url = webBrowserPane.back(); // display URL in urlTextField urlTextField.setText( url.toString() ); } } ); // create JButton for navigating to next history URL forwardButton = new JButton( new ImageIcon( getClass().getResource( "images/forward.gif" ) ) ); forwardButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { // navigate to next URL URL url = webBrowserPane.forward(); // display new URL in urlTextField urlTextField.setText( url.toString() ); } } ); // add JButtons and JTextField to WebToolBar add( backButton ); add( forwardButton ); add( urlTextField ); } // end WebToolBar constructor // listen for HyperlinkEvents in WebBrowserPane public void hyperlinkUpdate( HyperlinkEvent event ) { // if hyperlink was activated, go to hyperlink's URL if ( event.getEventType() == HyperlinkEvent.EventType.ACTIVATED ) { // get URL from HyperlinkEvent URL url = event.getURL(); // navigate to URL and display URL in urlTextField webBrowserPane.goToURL( url ); urlTextField.setText( url.toString() ); } } }
VIEWS ON THIS POST

53

Posted on:

Tuesday 23rd October 2012
View Replies!

Copying a value from 1 JPanel to another

Hi - I am having a heck of a time with what I am sure is a simple issue. I have a frame with a tabbed pane. In this pane I have placed two JPanels that are separate classes. I am trying to copy the value of a text field from one panel to the other based on the button press action on the second. I seem to have missed the concept of visibility here. What I am trying to do is pretty simple in VB etc but for the life of me I can't seem to get it here. I need this so that I can do updates on records in a database and promulgate the record id's. Any help woudl be greatly appreciated.
VIEWS ON THIS POST

65

Posted on:

Tuesday 23rd October 2012
View Replies!

frame calling another frame

Background: : I have two frame/classes. A login screen and a "display results" screen. A login screen has a login button which takes you to display results screen. Display eesults screen as a logout button however... Problem: when you click on the logout button, it generates two instances of the login screen. In other words, two login screens appear one on top of the other on the left hand corner NOT in the center like the first time the program launches. Behavior I want: once I click logout on "display results" screen, I go right away to the login screen. Exactly the way it previously was: centered and with only one instance running not two as it is right now. This is on the login screen. void loginbtn_actionPerformed(ActionEvent e) { //if login successful, you will get the results screen Display results = new Display(); results.setVisible(true); results.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(false); }
VIEWS ON THIS POST

70

Posted on:

Tuesday 23rd October 2012
View Replies!

Does Swing need another Layer?

A lot of people out there in the community keep addressing the fact that they think Swing needs a higher level that developers use. Similar I supose to how SWT has JFace. Personally, I think this might be a good idea. So I started playing around with some ideas. Don't slam me on this simple primative example, but see if this is something you think is a good idea to build off of. When I use a JTextArea there is a lot of initial constructing that needs to be done. For example, I always word and line wrap and I always have a JScrollPane. Here is a typical initialization of a JTextArea: JTextArea text = new JTextArea(10, 10); text.setWrapStyleWord(true); //false by default. Don't know why text.setLineWrap(true); //False by default. Don't know why JScrollPane textScroll = new JScrollPane(text); container.add(textScroll);
VIEWS ON THIS POST

204

Posted on:

Tuesday 23rd October 2012
View Replies!