SetSize problem!
hi all
Is there any reason for setSize doesn�t work?
i dont why, its not working for me! :-(
i have a class which extends JFrame and ihv added setSize(600,500) in constructor, juzt after super(title) !
someone please help me!
thanks and regards
sarathy
hi im so sorry to post this lengthy code.
in the constructor part, im reading a text file to load the list box.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import org.jfree.ui.RefineryUtilities;
public class ChartMaster extends JFrame implements ActionListener, ListSelectionListener {
JList pfoList;
String[] selectedPFO;
* Create the GUI and show it. For thread safety, this method should be invoked
* from the event-dispatching thread (main in my case)
public ChartMaster(String title) {
super(title);
setSize(800,600);
//Create GUI look and feel as that of OS look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {e.printStackTrace(); }
//Make sure we have nice window decorations.
setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new BorderLayout());
//List box
DefaultListModel listModel = loadDefaultListModel("PFOList.txt");
pfoList = new JList(listModel);
pfoList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
pfoList.setSelectedIndex(0);
pfoList.addListSelectionListener(this);
pfoList.setVisibleRowCount(5);
JScrollPane listScroller = new JScrollPane(pfoList);
listScroller.setPreferredSize(new Dimension(150, 400));
listScroller.setAlignmentX(LEFT_ALIGNMENT);
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
JLabel label = new JLabel("Select the PFO(s):");
label.setLabelFor(pfoList);
listPane.add(label);
listPane.add(Box.createRigidArea(new Dimension(0,5)));
listPane.add(listScroller);
listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//Date selection
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
JLabel jl = new JLabel("Date selection");
rightPanel.add(Box.createRigidArea(new Dimension(0,5)));
JRadioButton forMonthYear = new JRadioButton("For the Month and Year");
JRadioButton duringMonthYear = new JRadioButton("During the Month and Year");
ButtonGroup bg = new ButtonGroup();
bg.add(forMonthYear);
bg.add(duringMonthYear);
rightPanel.add(jl);
rightPanel.add(forMonthYear);
rightPanel.add(duringMonthYear);
//rightPanel.add(
//Bottom buttons
JButton button = new JButton("Show me Chart");
button.addActionListener(this);
c.add(listPane, BorderLayout.WEST);
c.add(rightPanel,BorderLayout.CENTER);
c.add(button,BorderLayout.SOUTH);
//Display the window.
pack();
//RefineryUtilities.centerFrameOnScreen(this);
setVisible(true);
public void valueChanged(ListSelectionEvent lse){
//System.out.println("List event: " + lse);
Object[] selectedObj = pfoList.getSelectedValues();
selectedPFO = new String[selectedObj.length];
for( int i=0; i < selectedObj.length; i++){
selectedPFO[i] = (String)selectedObj;
public void actionPerformed(ActionEvent e) {
Code to determine what are all the excel sheets to be read goes here
it depends on choices made in the User Interface and File organization!
ADD SOME MORE COMMENTS LATER
PFOBeta.main(new String[]{"Nothing"});
/*for( int i=0; i < selectedPFO.length; i++){
System.out.println(selectedPFO[i]);
public static DefaultListModel loadDefaultListModel(String cfgFileName){
DefaultListModel listModel = new DefaultListModel();
try{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(cfgFileName)));
String pfo = br.readLine();
while(pfo != null){
listModel.addElement(pfo);
pfo = br.readLine();
br.close();
}catch(Exception e){ System.out.println(e);}
return listModel;
public static void main(String[] args) {
ChartMaster cm = new ChartMaster("Process Group Tool");
Similar Messages
-
JFrame.setSize() problem
I'm facing a strange problem. I have a class derived from JFrame which is the main application frame window. Problem is I'm not able to set its size arbitrarily e.g. in following call to setSize(...) even if I replace 700 with 100 OR 1000 or whatever, the frame is always displayed of some fixed size . I can't find out why .. any clues ?
JGuessFrame() {
this.setSize(700, 700);
// Center the window on the screen
setLocationRelativeTo(null);
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}try this:
JGuessFrame() {
this.setSize(700, 700);
// Center the window on the screen
setLocationRelativeTo(null);
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack(); // maybe this will help
// if not then try this
this.repaint(); -
Let me start out by saying that in several decades of programming with literally dozens of different languages I have never encountered a language so difficult to understand as Java.
Having thus ranted,
parentFrame = new JFrame("Alert!");
parentFrame.setSize(600,600);
statusBar = new JLabel(" ");
msgPane = new JEditorPane();
parentFrame.getContentPane().add(msgPane, BorderLayout.CENTER);
parentFrame.getContentPane().add(statusBar, BorderLayout.SOUTH);
parentFrame.pack();
parentFrame.setVisible(true);This code creates a window which is 124 pixels wide by 73 pixels high, including the window borders, not the 600 by 600 specified.
What does it take to actually convince Java to make a window the size you specify.
Also, why, after I exit my ap, do I have to hit CTL-ALT-DEL and shut down "java.exe" from the task manager before I can launch the ap again? Why doesn't "java.exe" go away when I close my ap?
--garyfiziwig wrote:
Let me start out by saying that in several decades of programming with literally dozens of different languages I have never encountered a language so difficult to understand as Java.
Having thus ranted,\\
This code creates a window which is 124 pixels wide by 73 pixels high, including the window borders, not the 600 by 600 specified.
What does it take to actually convince Java to make a window the size you specify.\\
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Window.html#pack()
Also, why, after I exit my ap, do I have to hit CTL-ALT-DEL and shut down "java.exe" from the task manager before I can launch the ap again? Why doesn't "java.exe" go away when I close my ap?
--gary\\
Because you didn't tell Java to do so. Have a look at JFrame's setDefaultCloseOperation(...) method.
Perhaps you should do some serious reading before ranting? -
SetSize / scaling image problems
Hi there.
I'm having trouble resizing the main JFrame of my application, and getting the Container displayed inside it to resize appropriately.
The Container contains a call to:
g2.drawImage(screen, 0, 0, horizontal_length_scaled, verical_length_scaled, this);
When I call setSize on the main frame, it resizes the window correctly. However, the container simply clips the image at the size the old frame was set to. Note the image is actually scaled, but just clipped.
If I set the main frame to the larger size on start up, the image displays fine and I can then call setSize to set the frame to be smaller, and restore it to its original size without the clipping problem.
Any help would be appreciated. I can provide more info if necessary.
Thanks,
ChrisRight I've fixed the problem.
I called resize on the actual Component rather than the JFrame, and wrote code to override the getMinimumSize() etc. methods in the class. I then setClip(null); (although I had not specified a clip in the first place). I then called pack() to the main JFrame.
Thanks for your help with this - it gave me some ideas in any case.
C :) -
Problems setSize ListCellRenderer items
I hope to create a jlist with not fixed Height size,
first i creat MyJLabel class extended from jlabel and i create CustomedCellRenderer extended from this MyJLabel and i try to set Size of the MyJLabel on the end of the paint methode but it not work and it's also the same thing on the methode getPreferredSize() where de setSize methode not work
not :
i would nt to work width the setPreferredSize() and getPreferredSize() because it call sizeCalculator(WidthContener) methode to calculate the string width, height off the label text and it take lot of time to be executed
Help me to make the setSize on this location (1) and (2) to work fine
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
//import lib.HTMLEntities;
public class CustomedCellRenderer extends MyJLabel implements ListCellRenderer {
private static final long serialVersionUID = 1L;
int WidthContener=0;
public Component getListCellRendererComponent(
JList list,
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // the list and the cell have the focus
setLayout(null);
String Value =(String)value;
setText(Value);
setEnabled(list.isEnabled());
setOpaque(true);
/* it the execution of the JList so slow */
//Dimension Size = sizeCalculator(WidthContener);
//setPreferredSize(Size); // NOT Work (1)
//setSize(Size); // NOT Work
WidthContener= ((JList)list).getWidth();
return this;
public Dimension getPreferredSize()
setLayout(null);
Dimension Size = sizeCalculator(WidthContener);
setPreferredSize(Size); // NOT Work
setSize(Size); // NOT Work
validate();
return Size;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JLabel;
public class MyJlabel extends JLabel{
private String Text;
public MyJlabel()
super();
public MyJlabel(String text)
super(text);
this.Text=text;
public void setText(String text)
if ((Text==null)||!(Text.equals(text)))
this.Text= text;
public Dimension sizeCalculator(int WidthList)
// Calculate the Size of the HTML Text (parsing the HTML text)
// It make long time to calculate the dimension
return new Dimension(x,y) ;
public void paint(Graphics g) {
super.paint(g);
setLayout(null);
Dimension Size = sizeCalculator();
setPreferredSize(Size);// NOT WWWWWOOOORKKKK (2)
setSize(Size));// NOT WWWWWOOOORKKKK
this.validate();
}Thkx
Christineit seem work but all the cellrendere items returns the same heightmost times when dealing with renderers you need to specify an if/else, not just an if
run this example, and you''ll notice all items after "Rome" are also 100 high.
uncomment the 'else' line, recompile/rerun and it should then have Rome as the only 100 high item
import javax.swing.*;
import java.awt.*;
class Testing
public void buildGUI()
String[] cities = {"London","Madrid","New York","Rome","Sydney","Toronto","Washington"};
DefaultListModel listModel = new DefaultListModel();
for(int x = 0; x < cities.length; x++) listModel.addElement(cities[x]);
JList list = new JList(listModel);
list.setCellRenderer(new DefaultListCellRenderer(){
public Component getListCellRendererComponent(JList list,Object value,
int index,boolean isSelected,boolean cellHasFocus){
JLabel label = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
if(label.getText().equals("Rome")) label.setPreferredSize(new Dimension(100,100));
//else label.setPreferredSize(new Dimension(100,20));
return label;
JFrame f = new JFrame();
f.getContentPane().add(new JScrollPane(list));
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
} -
Problem with setContentPane() in JFrame class
I recently discovered a problem with the setContentPane method in the JFrame class. When I use setContentPane(Container ..), the previously existing contentPane remains in the stack. I have tried nullifying getContentPane(), and all manner of things, but, each time I use setContentPane, I have another instance of a JPanel in the stack.
I'm using code similar to setContentPane(new CustomJPanel()); and each time the user changes screens, and a similar call to that is made, the old CustomJPanel instance remains in the stack. Can anyone suggest a way around this? On their own the panels do not take up very much memory, but after several hours of usage, they will build up.I tried what you suggested; it only resulted in a huge performance decrease. The problem with memory allocation is still there.
Here is the method I use to switch screens in my app:
public static void changeScreen (JPanel panel){
try{
appFrame.setTitle("Wordinary : \""+getTitle()+"\"");
appFrame.setContentPane(panel);
appFrame.setSize(appFrame.getContentPane().getPreferredSize());
appFrame.getContentPane().setBackground(backColour);
for (int i = 0; i < appFrame.getContentPane().getComponents().length; i++)
appFrame.getContentPane().getComponents().setForeground(textColour);
//System.out.println("Background colour set to "+backColour+" text colour set to "+textColour);
appFrame.validate();
catch (Exception e){
//System.out.println("change");
e.printStackTrace();
And it is called like this:
changeScreen(new AddWordPanel());The instantiation of the new instance is what is causing the memory problems, but I can't think of a way around it. -
File and FileInputStream problem
Hi all
I have downloaded from developpez.com a sample code to zip files. I modified it a bit to suit with my needs, and when I launched it, there was an exception. So I commented all the lines except for the first executable one; and when it succeeds then I uncomment the next executable line; and so on. When I arrived at the FileInputStream line , the exception raised. When I looked at the code, it seemed normal. So I want help how to solve it. Here is the code with the last executable line uncommented, and the exception stack :
// Copyright (c) 2001
package pack_zip;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import oracle.jdeveloper.layout.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.text.*;
* A Swing-based top level window class.
* <P>
* @author a
public class fzip extends JFrame implements ActionListener{
JPanel jPanel1 = new JPanel();
XYLayout xYLayout1 = new XYLayout();
JTextField szdir = new JTextField();
JButton btn = new JButton();
JButton bzip = new JButton();
* Taille générique du tampon en lecture et écriture
static final int BUFFER = 2048;
* Constructs a new instance.
public fzip() {
super("Test zip");
try {
jbInit();
catch (Exception e) {
e.printStackTrace();
* Initializes the state of this instance.
private void jbInit() throws Exception {
this.getContentPane().setLayout(xYLayout1);
this.setSize(new Dimension(400, 300));
btn.setText("btn");
btn.setActionCommand("browse");
btn.setLabel("Browse ...");
btn.setFont(new Font("Dialog", 0, 14));
bzip.setText("bzip");
bzip.setActionCommand("zipper");
bzip.setLabel("Zipper");
bzip.setFont(new Font("Dialog", 0, 14));
btn.addActionListener(this);
bzip.addActionListener(this);
bzip.setEnabled(false);
this.getContentPane().add(jPanel1, new XYConstraints(0, 0, -1, -1));
this.getContentPane().add(szdir, new XYConstraints(23, 28, 252, 35));
this.getContentPane().add(btn, new XYConstraints(279, 28, 103, 38));
this.getContentPane().add(bzip, new XYConstraints(128, 71, 103, 38));
public void actionPerformed(ActionEvent e)
if(e.getActionCommand() == "browse")
FileDialog fd = new FileDialog(this);
fd.setVisible(true);
szdir.setText(fd.getDirectory());
bzip.setEnabled(true);
else
* Compression
try {
// création d'un flux d'écriture sur fichier
FileOutputStream dest = new FileOutputStream("Test_archive.zip");
// calcul du checksum : Adler32 (plus rapide) ou CRC32
CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
// création d'un buffer d'écriture
BufferedOutputStream buff = new BufferedOutputStream(checksum);
// création d'un flux d'écriture Zip
ZipOutputStream out = new ZipOutputStream(buff);
// spécification de la méthode de compression
out.setMethod(ZipOutputStream.DEFLATED);
// spécifier la qualité de la compression 0..9
out.setLevel(Deflater.BEST_COMPRESSION);
// buffer temporaire des données à écriture dans le flux de sortie
byte data[] = new byte[BUFFER];
// extraction de la liste des fichiers du répertoire courant
File f = new File(szdir.getText());
String files[] = f.list();
// pour chacun des fichiers de la liste
for (int i=0; i<files.length; i++) {
// en afficher le nom
System.out.println("Adding: "+files);
// création d'un flux de lecture
FileInputStream fi = new FileInputStream(files[i]);
/* // création d'un tampon de lecture sur ce flux
BufferedInputStream buffi = new BufferedInputStream(fi, BUFFER);
// création d'en entrée Zip pour ce fichier
ZipEntry entry = new ZipEntry(files[i]);
// ajout de cette entrée dans le flux d'écriture de l'archive Zip
out.putNextEntry(entry);
// écriture du fichier par paquet de BUFFER octets
// dans le flux d'écriture
int count;
while((count = buffi.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
// Close the current entry
out.closeEntry();
// fermeture du flux de lecture
buffi.close();*/
/* // fermeture du flux d'écriture
out.close();
buff.close();
checksum.close();
dest.close();
System.out.println("checksum: " + checksum.getChecksum().getValue());*/
// traitement de toute exception
catch(Exception ex) {
ex.printStackTrace();
And here is the error stack :
"D:\jdev32\java1.2\jre\bin\javaw.exe" -mx50m -classpath "D:\jdev32\myclasses;D:\jdev32\lib\jdev-rt.zip;D:\jdev32\jdbc\lib\oracle8.1.7\classes12.zip;D:\jdev32\lib\connectionmanager.zip;D:\jdev32\lib\jbcl2.0.zip;D:\jdev32\lib\jgl3.1.0.jar;D:\jdev32\java1.2\jre\lib\rt.jar" pack_zip.czip
Adding: accueil188.cfm
java.io.FileNotFoundException: accueil188.cfm (Le fichier spécifié est introuvable.
void java.io.FileInputStream.open(java.lang.String)
void java.io.FileInputStream.<init>(java.lang.String)
void pack_zip.fzip.actionPerformed(java.awt.event.ActionEvent)
void javax.swing.AbstractButton.fireActionPerformed(java.awt.event.ActionEvent)
void javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(java.awt.event.ActionEvent)
void javax.swing.DefaultButtonModel.fireActionPerformed(java.awt.event.ActionEvent)
void javax.swing.DefaultButtonModel.setPressed(boolean)
void javax.swing.plaf.basic.BasicButtonListener.mouseReleased(java.awt.event.MouseEvent)
void java.awt.Component.processMouseEvent(java.awt.event.MouseEvent)
void java.awt.Component.processEvent(java.awt.AWTEvent)
void java.awt.Container.processEvent(java.awt.AWTEvent)
void java.awt.Component.dispatchEventImpl(java.awt.AWTEvent)
void java.awt.Container.dispatchEventImpl(java.awt.AWTEvent)
void java.awt.Component.dispatchEvent(java.awt.AWTEvent)
void java.awt.LightweightDispatcher.retargetMouseEvent(java.awt.Component, int, java.awt.event.MouseEvent)
boolean java.awt.LightweightDispatcher.processMouseEvent(java.awt.event.MouseEvent)
boolean java.awt.LightweightDispatcher.dispatchEvent(java.awt.AWTEvent)
void java.awt.Container.dispatchEventImpl(java.awt.AWTEvent)
void java.awt.Window.dispatchEventImpl(java.awt.AWTEvent)
void java.awt.Component.dispatchEvent(java.awt.AWTEvent)
void java.awt.EventQueue.dispatchEvent(java.awt.AWTEvent)
boolean java.awt.EventDispatchThread.pumpOneEvent()
void java.awt.EventDispatchThread.pumpEvents(java.awt.Conditional)
void java.awt.EventDispatchThread.run()
Thank you very muchOne easy way to send a file through RMI is to read all bytes of a file to a byte array and send this array as a parameter of a remote method. But of course you may have problems with memory when you send large files. The receive is simillary.
Other way is to split the file and getting slices of the file, sending slices and re-assemble at destination. This assume that the file isn't changed through the full transfering is concluded.
I hope these could help you. -
firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
* Created on 03-Aug-2005
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* @author Administrator
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import java.io.*;
public class NodesTable extends JFrame implements TableModelListener, ActionListener {
JTable jt;
DefaultTableColumnModel dtcm;
TableColumn column[] = new TableColumn[100];
DefaultTableModel dtm;
JLabel Name,m1,w1,m2,w2;
JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
float x=0,y=0,tMark=0,z = 0;
float j=0;
int i;
JButton DelButton;
JButton AddButton;
JScrollPane scrollPane;
JPanel mainPanel,buttonPanel;
JFrame frame;
Object[][] data =
{"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
{"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
{"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
{"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
public NodesTable() {
super("Student Marking Spreadsheet");
this.AddNodesintoTable();
setSize(400,250);
setVisible(true);
public void AddNodesintoTable(){
// Create a vector object and load them with the data
// to be placed on each row of the table
dtm = new DefaultTableModel(data,c);
dtm.addTableModelListener( this );
jt = new JTable(dtm){
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
// The Cost is not editable
public boolean isCellEditable(int row, int column)
int modelColumn = convertColumnIndexToModel( column );
return (modelColumn == 5) ? false : true;
//****************************User Input**************************
//Add another node
//Creating and setting the properties
//of the panel's component (panels and textfields)
Name = new JLabel("Name");
Name.setForeground(Color.black);
m1 = new JLabel("Mark1");
m1.setForeground(Color.black);
w1 = new JLabel("Weigth1");
w1.setForeground(Color.black);
m2= new JLabel("Mark2");
m2.setForeground(Color.black);
w2 = new JLabel("Weight2");
w2.setForeground(Color.black);
NameTF = new JTextField(5);
NameTF.setText("Node");
m1TF = new JTextField(5);
w1TF = new JTextField(5);
m2TF=new JTextField(5);
w2TF=new JTextField(5);
//creating the buttons
JPanel buttonPanel = new JPanel();
AddButton=new JButton("Add Row");
DelButton=new JButton("Delete") ;
buttonPanel.add(AddButton);
buttonPanel.add(DelButton);
//adding the components to the panel
JPanel inputpanel = new JPanel();
inputpanel.add(Name);
inputpanel.add(NameTF);
inputpanel.add(m1);
inputpanel.add(m1TF);
inputpanel.add(w1);
inputpanel.add(w1TF);
inputpanel.add(m2);
inputpanel.add(m2TF);
inputpanel.add(w2TF);
inputpanel.add(w2);
inputpanel.add(AddButton);
inputpanel.add(DelButton);
//creating the panel and setting its properties
JPanel tablepanel = new JPanel();
tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
getContentPane().add(tablepanel, BorderLayout.CENTER);
getContentPane().add(inputpanel, BorderLayout.SOUTH);
//Method to add row for each new entry
public void addRow()
Vector r=new Vector();
r=createBlankElement();
dtm.addRow(r);
jt.addNotify();
public Vector createBlankElement()
Vector t = new Vector();
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
return t;
// Method to delete a row from the spreadsheet
void deleteRow(int index)
if(index!=-1) //At least one Row in Table
dtm.removeRow(index);
jt.addNotify();
// Method that adds and deletes rows
// from the table by pressing the
//corresponding buttons
public void actionPerformed(ActionEvent ae){
Float z=new Float (m2TF.getText());
String Name= NameTF.getText();
Float x= new Float(m1TF.getText());
Float y= new Float(w1TF.getText());
Float j=new Float (w2TF.getText());
JFileChooser jfc2 = new JFileChooser();
String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
String.valueOf(z),String.valueOf(j)};
Object source = ae.getSource();
if(ae.getSource() == (JButton)AddButton)
addRow();
if (ae.getSource() ==(JButton) DelButton)
deleteRow(jt.getSelectedRow());
//method to calculate the total mark in the TotalMark column
//that updates the values in every other column
//It takes the values from the column 1,2,3,4
//and changes the value in the column 5
public void tableChanged(TableModelEvent e) {
System.out.println(e.getSource());
if (e.getType() == TableModelEvent.UPDATE)
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 1 || column == 2 ||column == 3 ||column == 4)
TableModel model = jt.getModel();
float q= ((Float)model.getValueAt(row,1)).floatValue();
float w= ((Float)model.getValueAt(row,2)).floatValue();
float t= ((Float)model.getValueAt(row,3)).floatValue();
float r= ((Float)model.getValueAt(row,4)).floatValue();
Float tMark = new Float((q*w+t*r)/(w+r) );
model.setValueAt(tMark, row, 5);
// Which cells are editable.
// It is only necessary to implement this method
// if the table is editable
public boolean isCellEditable(int row, int col)
{ return true; //All cells are editable
public static void main(String[] args) {
NodesTable t=new NodesTable();
}There are too many mistakes in your program. It looks like you are new to java.
Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
Here is the updated code: Do the diff and u will know my changes
* Created on 03-Aug-2005
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* @author Administrator
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
public class NodesTable extends JFrame implements TableModelListener,
ActionListener {
JTable jt;
DefaultTableColumnModel dtcm;
TableColumn column[] = new TableColumn[100];
DefaultTableModel dtm;
JLabel Name, m1, w1, m2, w2;
JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
"TotalMark" };
float x = 0, y = 0, tMark = 0, z = 0;
float j = 0;
int i;
JButton DelButton;
JButton AddButton;
JScrollPane scrollPane;
JPanel mainPanel, buttonPanel;
JFrame frame;
public NodesTable() {
super("Student Marking Spreadsheet");
this.AddNodesintoTable();
setSize(400, 250);
setVisible(true);
public void AddNodesintoTable() {
// Create a vector object and load them with the data
// to be placed on each row of the table
dtm = new DefaultTableModel(c,0);
dtm.addTableModelListener(this);
jt = new JTable(dtm) {
// The Cost is not editable
public boolean isCellEditable(int row, int column) {
int modelColumn = convertColumnIndexToModel(column);
return (modelColumn == 5) ? false : true;
//****************************User Input**************************
//Add another node
//Creating and setting the properties
//of the panel's component (panels and textfields)
Name = new JLabel("Name");
Name.setForeground(Color.black);
m1 = new JLabel("Mark1");
m1.setForeground(Color.black);
w1 = new JLabel("Weigth1");
w1.setForeground(Color.black);
m2 = new JLabel("Mark2");
m2.setForeground(Color.black);
w2 = new JLabel("Weight2");
w2.setForeground(Color.black);
NameTF = new JTextField(5);
NameTF.setText("Node");
m1TF = new JTextField(5);
w1TF = new JTextField(5);
m2TF = new JTextField(5);
w2TF = new JTextField(5);
//creating the buttons
JPanel buttonPanel = new JPanel();
AddButton = new JButton("Add Row");
AddButton.addActionListener(this);
DelButton = new JButton("Delete");
DelButton.addActionListener(this);
buttonPanel.add(AddButton);
buttonPanel.add(DelButton);
//adding the components to the panel
JPanel inputpanel = new JPanel();
inputpanel.add(Name);
inputpanel.add(NameTF);
inputpanel.add(m1);
inputpanel.add(m1TF);
inputpanel.add(w1);
inputpanel.add(w1TF);
inputpanel.add(m2);
inputpanel.add(m2TF);
inputpanel.add(w2TF);
inputpanel.add(w2);
inputpanel.add(AddButton);
inputpanel.add(DelButton);
//creating the panel and setting its properties
JPanel tablepanel = new JPanel();
tablepanel.add(new JScrollPane(jt,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
getContentPane().add(tablepanel, BorderLayout.CENTER);
getContentPane().add(inputpanel, BorderLayout.SOUTH);
//Method to add row for each new entry
public void addRow() {
Float z = new Float(m2TF.getText());
String Name = NameTF.getText();
Float x = new Float(m1TF.getText());
Float y = new Float(w1TF.getText());
Float j = new Float(w2TF.getText());
String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
String.valueOf(z), String.valueOf(j) };
dtm.addRow(newdata);
// Method to delete a row from the spreadsheet
void deleteRow(int index) {
if (index != -1) //At least one Row in Table
dtm.removeRow(index);
jt.addNotify();
// Method that adds and deletes rows
// from the table by pressing the
//corresponding buttons
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (ae.getSource() == (JButton) AddButton) {
addRow();
if (ae.getSource() == (JButton) DelButton) {
deleteRow(jt.getSelectedRow());
//method to calculate the total mark in the TotalMark column
//that updates the values in every other column
//It takes the values from the column 1,2,3,4
//and changes the value in the column 5
public void tableChanged(TableModelEvent e) {
System.out.println(e.getSource());
//if (e.getType() == TableModelEvent.UPDATE) {
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 1 || column == 2 || column == 3 || column == 4) {
TableModel model = jt.getModel();
float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
Float tMark = new Float((q * w + t * r) / (w + r));
model.setValueAt(tMark, row, 5);
// Which cells are editable.
// It is only necessary to implement this method
// if the table is editable
public boolean isCellEditable(int row, int col) {
return true; //All cells are editable
public static void main(String[] args) {
NodesTable t = new NodesTable();
} -
Problem with PDFBox-0.7.3 library - Runtime Error
Hello,
The problem is inside the method "chamaConversor".
" conversor.pdfToText(arquivoPdf,arquivoTxt);" make a file.txt from one file.pdf. After that it don?t return the control to "ConstrutorDeTemplate2.java", and show the following error message:
Exception in thread "AWT-EventQueue-O" java.lang.NoClassDefFoundError : org/fontbox/afm/FontMetric
at org.pdfbox.pdmodel.font.PDFont.getAFM (PDFont.java:334)
I am using the NetBeans IDE 5.5.
I have added all of these libraries below to my project from c:\Program Files\netbeans-5.5\PDFBox-0.7.3\external:
* FontBox-0.1.0-dev.jar
* ant.jar
* bcmail-jdk14-132.jar
* junit.jar
* bcprov-jdk14-132.jar
* lucene-core-2.0.0.jar
* checkstyle-all-4.2.jar
* lucene-demos-2.0.0.jar
and PDFBox-0.7.3.jar from c:\Program Files\netbeans-5.5\PDFBox-0.7.3\lib.
There are no more jar from PDFBox-0.7.3 directory.
All of these libraries are in "Compile-time Libraries" option in Project Properties. Should I add they to "Run-time Libraries" option?
What is going on?
Thank you!
* ConstrutorDeTemplate2.java
* Created on 11 de Agosto de 2007, 14:54
* @author
package br.unifacs.dis2007.template2;
// Java core packages
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
// Java extension packages
import javax.swing.*;
import org.pdfbox.*;
public class ConstrutorDeTemplate2 extends JFrame
implements ActionListener {
private JTextField enterField;
private JTextArea outputArea;
private BufferedWriter out;
private String word;
private PdfToText conversor = new PdfToText();
// ajusta a interface do usu?rio
public ConstrutorDeTemplate2()
super( "Testing class File" );
enterField = new JTextField("Digite aqui o nome do arquivo :" );
enterField.addActionListener( this );
outputArea = new JTextArea();
ScrollPane scrollPane = new ScrollPane();
scrollPane.add( outputArea );
Container container = getContentPane();
container.add( enterField, BorderLayout.NORTH );
container.add( scrollPane, BorderLayout.CENTER );
setSize( 400, 400 );
show();
// Exibe as informa??es sobre o arquivo especificado pelo usu?rio
public void actionPerformed( ActionEvent actionEvent )
File name = new File( actionEvent.getActionCommand() );
// Se o arquivo existe, envia para a sa?da as informa??es sobre ele
if ( name.exists() ) {
outputArea.setText(
name.getName() + " exists\n" +
( name.isFile () ?
"is a file\n" : "is not a file\n" ) +
( name.isDirectory() ?
"is a directory\n" : "is not a directory\n" ) +
( name.isAbsolute() ? "is absolute path\n" :
"is not absolute path\n" ) +
"Last modified: " + name.lastModified() +
"\nLength: " + name.length () +
"\nPath: " + name.getPath() +
"\nAbsolute path: " + name.getAbsolutePath() +
"\nParent: " + name.getParent() );
// informa??o de sa?da se "name" ? um arquivo
if ( name.isFile() ) {
String nameString = String.valueOf(name.getPath());
String nameTeste = new String(nameString);
if (nameString.endsWith(".pdf"))
nameTeste = chamaConversor(nameString);
else
if (nameString.endsWith(".doc"))
nameTeste = chamaConversorDoc(nameString); // chama conversor de arquivos DOC
else
if (nameString.endsWith(".txt"))
nameTeste = nameString;
// se o arquivo termina com ".txt"
if (nameTeste.endsWith(".txt"))
// acrescenta conte?do do arquivo ? ?rea de sa?da
try {
// Create the tokenizer to read from a file
FileReader rd = new FileReader(nameTeste);
StreamTokenizer st = new StreamTokenizer(rd);
// Prepare the tokenizer for Java-style tokenizing rules
st.parseNumbers();
st.wordChars('_', '_');
st.eolIsSignificant (true);
// If whitespace is not to be discarded, make this call
st.ordinaryChars(0, ' ');
// These calls caused comments to be discarded
st.slashSlashComments(true);
st.slashStarComments(true);
// Parse the file
int token = st.nextToken();
String word_ant = "";
outputArea.append( " \n" );
out = new BufferedWriter(new FileWriter(nameTeste, true));
while (token != StreamTokenizer.TT_EOF) {
token = st.nextToken();
if (token == StreamTokenizer.TT_EOL){
//out.write(word);
out.flush();
out = new BufferedWriter(new FileWriter(nameTeste, true));
//outputArea.append( word + "\n" );
// out.append ( "\n" );
switch (token) {
case StreamTokenizer.TT_NUMBER:
// A number was found; the value is in nval
double num = st.nval;
break;
case StreamTokenizer.TT_WORD:
// A word was found; the value is in sval
word = st.sval;
// if (word_ant.equals("a") || word_ant.equals("an") || word_ant.equals("the") || word_ant.equals("The") || word_ant.equals("An"))
outputArea.append( word.toString() + " \n " );
// out.append( word + " " );
// word_ant = word;
break;
case '"':
// A double-quoted string was found; sval contains the contents
String dquoteVal = st.sval;
break;
case '\'':
// A single-quoted string was found; sval contains the contents
String squoteVal = st.sval;
break;
case StreamTokenizer.TT_EOL:
// End of line character found
break;
case StreamTokenizer.TT_EOF:
// End of file has been reached
break;
default:
// A regular character was found; the value is the token itself
char ch = (char)st.ttype;
break;
} // fim do switch
} // fim do while
rd.close();
out.close();
} // fim do try
// process file processing problems
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"FILE ERROR",
"FILE ERROR", JOptionPane.ERROR_MESSAGE );
} // fim do if da linha 92 - testa se o arquivo ? do tipo texto
} // fim do if da linha 78 - testa se ? um arquivo
// output directory listing
else if ( name.isDirectory() ) {
String directory[] = name.list();
outputArea.append( "\n\nDirectory contents:\n");
for ( int i = 0; i < directory.length; i++ )
outputArea.append( directory[ i ] + "\n" );
} // fim do else if da linha 184 - testa se ? um diret?rio
} // fim do if da linha 62 - testa se o arquivo existe
// not file or directory, output error message
else {
JOptionPane.showMessageDialog( this,
actionEvent.getActionCommand() + " Does Not Exist",
"ERROR", JOptionPane.ERROR_MESSAGE );
} // fim do m?todo actionPerformed
// m?todo que chama o conversor
public String chamaConversor(String arquivoPdf){
String arquivoTxt = new String(arquivoPdf);
arquivoTxt = arquivoPdf.replace(".pdf", ".txt");
try {
conversor.pdfToText(arquivoPdf,arquivoTxt);
catch (Exception ex) {
ex.printStackTrace();
return (arquivoTxt);
// executa a aplica??o
public static void main( String args[] )
ConstrutorDeTemplate2 application = new ConstrutorDeTemplate2();
application.setDefaultCloseOperation (
JFrame.EXIT_ON_CLOSE );
} // fim do m?todo main
} // fim da classe ExtratorDeSubstantivos2
* PdfToText.java
* Created on 11 de Agosto de 2007, 10:57
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
//package br.unifacs.dis2007.template2;
* @author www
package br.unifacs.dis2007.template2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL ;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.pdmodel.encryption.AccessPermission;
import org.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
import org.pdfbox.util.PDFText2HTML;
import org.pdfbox.pdmodel.font.PDFont.* ;
import org.pdfbox.util.PDFTextStripper;
import org.pdfbox.util.*;
import org.pdfbox.pdmodel.*;
public class PdfToText
public void pdfToText( String pdfFile, String textFile) throws Exception
Writer output = null;
PDDocument document = null;
try
try
//basically try to load it from a url first and if the URL
//is not recognized then try to load it from the file system.
URL url = new URL( pdfFile );
document = PDDocument.load( url );
String fileName = url.getFile();
if( textFile == null && fileName.length () >4 )
File outputFile =
new File( fileName.substring( 0,fileName.length() -4 ) + ".txt" );
textFile = outputFile.getName();
catch( MalformedURLException e )
document = PDDocument.load( pdfFile );
if( textFile == null && pdfFile.length() >4 )
textFile = pdfFile.substring( 0,pdfFile.length() -4 ) + ".txt";
//use default encoding
output = new OutputStreamWriter( new FileOutputStream( textFile ) );
PDFTextStripper stripper = null;
stripper = new PDFTextStripper();
stripper.writeText( document, output );
finally
if( output != null )
output.close();
if( document != null )
document.close();
}//finally
}//end funcao
All of these libraries are in "Compile-time
Libraries" option in Project Properties. Should I add
they to "Run-time Libraries" option?Yes -
I am using JDK1.4 and working on Windows Xp.
I have written a code for application in java as follows:
import javax.swing.*;
public class sample
JPanel panel;
static JFrame frame;
JButton but;
public sample()
frame=new JFrame("frame");
panel=new JPanel();
frame.getContentPane().add(panel);
but=new JButton("click");
panel.add(but);
public static void main(String args[])
sample s=new sample();
frame.setSize(300,300);
frame.setVisible(true);
on executing program application window has appeared and it ran properly.
Then I closed that application window.But after that in command prompt window curser was just blinking and it was not allow to enter also.
I have tried pressing CTRL+C also.But situation in command prompt was same i.e curser in command prompt was just blinking.
Then I closed cmd window ;but one error has occured saying that cmd window can not close .
My friend has told me that she is also having windows xp and JDK1.4 ; ctrl+c is working properly in her command prompt.She has written the above same code in her computer and it executes properly.
Even though she has not written following statement:
"frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);"
when she exits from application window ,her cmd window gave same problem of only blinking curser.But when she press CTRL+C ; her command prompt starts responding by giving root.But my command prompt is not giving
positive responce to "ctrl+c" when I am exiting java application.
Is it possible to solve this problem without giving statement
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ?
Why my command prompt is not responding to CTRL+c?
How can I tackle this problem ?
Is there any other key which can be used in command prompt of Windows Xp?Is it possible to solve this problem without giving
statement
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
?this is because Swing have started some non-daemon helper threads for its internal purposes and the default close operation for frame is just HIDE_ON_CLOSE. So, the system will not exit because those non-daemon thread still not terminated.
What is the problems setting the default close operation to JFrame.EXIT_ON_CLOSE ? -
Can some one help me with this problem with my frame???
i have gt a veri strange problem with my program,that is teh graphic changes only when i resize the the frame,if i dun resize,it will remain the same.However what i intended is that when i click on the radio button,it will change immediately to the respective pages.A simple version of my code is below,can someone helpl me solve it??(there is 3 different class)
import java.awt.event.*;
import javax.swing.*;
public class MainPg extends JFrame implements ActionListener{
private javax.swing.JPanel jContentPane = null;
private javax.swing.JPanel buttons = null;
private javax.swing.JRadioButton one = null;
private javax.swing.JRadioButton two = null;
private javax.swing.JPanel change = null;
public MainPg() {
super();
initialize();
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setName("mainClass");
this.setVisible(true);
private javax.swing.JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new javax.swing.JPanel();
jContentPane.setLayout(new java.awt.BorderLayout());
jContentPane.add(getButtons(), java.awt.BorderLayout.WEST);
jContentPane.add(getChange(), java.awt.BorderLayout.CENTER);
return jContentPane;
private javax.swing.JPanel getButtons() {
if(buttons == null) {
buttons = new javax.swing.JPanel();
java.awt.GridLayout layGridLayout1 = new java.awt.GridLayout();
layGridLayout1.setRows(2);
layGridLayout1.setColumns(1);
ButtonGroup group=new ButtonGroup();
group.add(getOne());
group.add(getTwo());
buttons.setLayout(layGridLayout1);
buttons.add(getOne(), null);
buttons.add(getTwo(), null);
return buttons;
private javax.swing.JRadioButton getOne() {
if(one == null) {
one = new javax.swing.JRadioButton();
one.setText("One");
one.setSelected(true);
one.addActionListener(this);
one.setActionCommand("one");
return one;
private javax.swing.JRadioButton getTwo() {
if(two == null) {
two = new javax.swing.JRadioButton();
two.setText("Two");
two.addActionListener(this);
two.setActionCommand("two");
return two;
private javax.swing.JPanel getChange() {
if(change == null) {
change = new javax.swing.JPanel();
change.add(new One());
return change;
public static void main(String[] args){
new MainPg();
public void actionPerformed(ActionEvent e) {
change.removeAll();
if("one".equals(e.getActionCommand())){
change.add(new One());
else{
change.add(new Two());
change.repaint();
import javax.swing.*;
public class One extends JPanel {
private javax.swing.JPanel jPanel = null;
private javax.swing.JLabel jLabel = null;
private javax.swing.JPanel jPanel1 = null;
private javax.swing.JLabel jLabel1 = null;
private javax.swing.JLabel jLabel2 = null;
public One() {
super();
initialize();
* This method initializes this
* @return void
private void initialize() {
this.setLayout(new java.awt.BorderLayout());
this.add(getJPanel(), java.awt.BorderLayout.NORTH);
this.add(getJPanel1(), java.awt.BorderLayout.WEST);
this.setSize(300, 200);
* This method initializes jPanel
* @return javax.swing.JPanel
private javax.swing.JPanel getJPanel() {
if(jPanel == null) {
jPanel = new javax.swing.JPanel();
jPanel.add(getJLabel(), null);
return jPanel;
* This method initializes jLabel
* @return javax.swing.JLabel
private javax.swing.JLabel getJLabel() {
if(jLabel == null) {
jLabel = new javax.swing.JLabel();
jLabel.setText("one");
return jLabel;
* This method initializes jPanel1
* @return javax.swing.JPanel
private javax.swing.JPanel getJPanel1() {
if(jPanel1 == null) {
jPanel1 = new javax.swing.JPanel();
java.awt.GridLayout layGridLayout2 = new java.awt.GridLayout();
layGridLayout2.setRows(2);
layGridLayout2.setColumns(1);
jPanel1.setLayout(layGridLayout2);
jPanel1.add(getJLabel2(), null);
jPanel1.add(getJLabel1(), null);
return jPanel1;
* This method initializes jLabel1
* @return javax.swing.JLabel
private javax.swing.JLabel getJLabel1() {
if(jLabel1 == null) {
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("one");
return jLabel1;
* This method initializes jLabel2
* @return javax.swing.JLabel
private javax.swing.JLabel getJLabel2() {
if(jLabel2 == null) {
jLabel2 = new javax.swing.JLabel();
jLabel2.setText("one");
return jLabel2;
import javax.swing.*;
public class Two extends JPanel {
private javax.swing.JLabel jLabel = null;
public Two() {
super();
initialize();
* This method initializes this
* @return void
private void initialize() {
this.setLayout(new java.awt.FlowLayout());
this.add(getJLabel(), null);
this.setSize(300, 200);
* This method initializes jLabel
* @return javax.swing.JLabel
private javax.swing.JLabel getJLabel() {
if(jLabel == null) {
jLabel = new javax.swing.JLabel();
jLabel.setText("two");
return jLabel;
}//change.repaint();
change.revalidate(); -
JFrames and Java3D simple problem
Hi ive created a program using jframes in Java and im wanting to move it over to java 3d but im having problems. Ive litterally just looked at java 3d so my knowledge is limited. All i want is to set up my canvas so that i have a Jframe panel on the right and a 3d ball on the left. Here's my failed attempt......
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.image.*;//imports image functions
import javax.media.j3d.*;
import javax.vecmath.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.*;
public class Prog extends JFrame
private Canvas3D canvas;
private SimpleUniverse universe = new SimpleUniverse(); // Create the universe
private BranchGroup group = new BranchGroup(); // Create a structure to contain objects
private Bounds bounds;
public Prog()
super("Program");
GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
canvas = new Canvas3D(config);
//getContentPane().setLayout( new BorderLayout( ) );
//getContentPane().add(canvas, "Center");
Container c = getContentPane();
setSize(600,400);
c.setLayout(new BorderLayout( ));
JPanel leftPanel = new JPanel( );
leftPanel.setBackground(Color.BLACK);
c.add(leftPanel, BorderLayout.CENTER);
c.setLayout(new BorderLayout( ));
JPanel rightPanel = new JPanel( );
rightPanel.setBackground(Color.GRAY);
c.add(rightPanel, BorderLayout.EAST);
JButton goButton = new JButton(" Go ");
goButton.setBackground(Color.RED);
rightPanel.add(goButton);
Light();//Creates A Light Source
// Create a ball and add it to the group of objects
Sphere sphere = new Sphere(0.5f);
group.addChild(sphere);
// look towards the ball
universe.getViewingPlatform().setNominalViewingTransform();
// add the group of objects to the Universe
universe.addBranchGraph(group);
public void Light()
// Create a white light that shines for 100m from the origin
Color3f light1Color = new Color3f(1.8f, 1.8f, 1.8f);
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);
Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
DirectionalLight light1 = new DirectionalLight(light1Color, light1Direction);
light1.setInfluencingBounds(bounds);
group.addChild(light1);
public static void main(String[] args)
Prog frame = new Prog();
frame.setVisible(true);
}It Compiles but the 3d ball and the Jframe gui are in different windows but i want them in the same window but i duno how ?Hi tesla66 I'm sorry if I didn't correct your code, but drop some new code trying to solve the problem. I've used the cube instead the sphere because it's easier to see is rotating but just change "new ColorCube(0.4f)" with " new Sphere( 0.4f )". I wrote even some coments tought they're helpful. Tell me if I solved the problem
import java.awt.*;
import javax.swing.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.universe.SimpleUniverse;
import com.sun.j3d.utils.geometry.*;
public class JFrameAndCanvas3D extends JFrame
private Canvas3D canvas3D;
public static void main(String[] args)
new JFrameAndCanvas3D();
public JFrameAndCanvas3D()
initialize();
public BranchGroup createSceneGraph()
BranchGroup objRoot = new BranchGroup(); //root
// Creates a bounds for lights and interpolator
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
//Ambient light
Color3f ambientColour = new Color3f(0.2f, 0.2f, 0.2f);
AmbientLight ambientLight = new AmbientLight(ambientColour);
ambientLight.setInfluencingBounds(bounds);
objRoot.addChild(ambientLight);
///Creates a group for transforms
TransformGroup objMove = new TransformGroup();
//You must set the capability bit to allow to write transform on the object
objMove.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
//Adds a color cube
objMove.addChild(new ColorCube(0.4));
//Creates a timer
Alpha rotationAlpha = new Alpha(-1, //-1 = infinite loop
4000 // rotation time in ms
//creates a transform 3D based on Y axis roation
Transform3D t3d = new Transform3D();
t3d.rotY(Math.PI/2);
//Creates an rotation interpolator with an alpha and a TransformGroup
RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, objMove);
rotator.setTransformAxis(t3d);//setta l'asse di rotazione
//sets a bounding region. withouth this scheduling bounds the interpolator won't work
rotator.setSchedulingBounds(bounds);
//add the interpolator to the group
objMove.addChild(rotator);
//Adding the group to the root
objRoot.addChild(objMove);
objRoot.compile();//improve the performance
return objRoot;
public void initialize()
setSize(800, 600);
setLayout(new BorderLayout());
GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();//default config
canvas3D = new Canvas3D(config);
canvas3D.setSize(400, 600);
add(canvas3D, BorderLayout.WEST); //adding the canvas to the west side of the JFrame
SimpleUniverse simpleU = new SimpleUniverse( canvas3D );
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BorderLayout());
controlPanel.setSize(400, 600);
JLabel label = new JLabel();
label.setText("I'm the control Panel");
controlPanel.add(label, BorderLayout.CENTER);
add(controlPanel, BorderLayout.EAST);
//Positioning the view
TransformGroup viewingPlatformGroup = simpleU.getViewingPlatform().getViewPlatformTransform();
Transform3D t3d = new Transform3D();
t3d.setTranslation(new Vector3f(0, 0, 3)); //moving back from the cube--> +z
viewingPlatformGroup.setTransform(t3d);
canvas3D.getView().setBackClipDistance(300.0d); //sets the visible distance
canvas3D.getView().setFrontClipDistance(0.1d);
canvas3D.getView().setMinimumFrameCycleTime(20); //minimum time refresh
canvas3D.getView().setTransparencySortingPolicy(View.TRANSPARENCY_SORT_GEOMETRY); //rendering order
BranchGroup scene = createSceneGraph();
simpleU.addBranchGraph(scene);
setVisible(true);
}-->Davil -
GridBagLayout and Panel Border problem
I have 3 panels like
A
B
C
and the C panel has a Mouse Listener that on a mouseEntered creates a border around the same panel and on a mouseExited clears that border.
When this border is created the A and B panels go up a little bit .. they move alone when the border is created.
Is there any way to fix this problem? Is there any way to get the panels static?
the code is close to the following:
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import java.text.NumberFormat;
public class Game extends JFrame implements MouseListener
JPanel game, options, top, down, middle;
NumberFormat nf;
public Game() {
super("Game");
nf = NumberFormat.getPercentInstance();
nf.setMaximumFractionDigits(1);
JPanel center = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = gbc.BOTH;
gbc.weighty = 1.0;
gbc.weightx = 0.8;
center.add(getGamePanel(), gbc);
gbc.weightx = 0.104;
center.add(getOptionsPanel(), gbc);
Container cp = getContentPane();
// use the JFrame default BorderLayout
cp.add(center); // default center section
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(700,600);
// this.setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
addComponentListener(new ComponentAdapter()
public void componentResized(ComponentEvent e)
showSizeInfo();
showSizeInfo();
private void showSizeInfo()
Dimension d = getContentPane().getSize();
double totalWidth = game.getWidth() + options.getWidth();
double gamePercent = game.getWidth() / totalWidth;
double optionsPercent = options.getWidth() / totalWidth;
double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
double topPercent = top.getHeight() / totalHeight;
double middlePercent = middle.getHeight() / totalHeight;
double downPercent = down.getHeight() / totalHeight;
System.out.println("content size = " + d.width + ", " + d.height + "\n" +
"game width = " + nf.format(gamePercent) + "\n" +
"options width = " + nf.format(optionsPercent) + "\n" +
"top height = " + nf.format(topPercent) + "\n" +
"middle height = " + nf.format(middlePercent) + "\n" +
"down height = " + nf.format(downPercent) + "\n");
private JPanel getGamePanel()
// init components
top = new JPanel(new BorderLayout());
top.setBackground(Color.red);
top.add(new JLabel("top panel", JLabel.CENTER));
middle = new JPanel(new BorderLayout());
middle.setBackground(Color.green.darker());
middle.add(new JLabel("middle panel", JLabel.CENTER));
down = new JPanel(new BorderLayout());
down.setBackground(Color.blue);
down.add(new JLabel("down panel", JLabel.CENTER));
// layout game panel
game = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.fill = gbc.BOTH;
gbc.gridwidth = gbc.REMAINDER;
gbc.weighty = 0.2;
game.add(top, gbc);
gbc.weighty = 0.425;
game.add(middle, gbc);
gbc.weighty = 0.2;
game.add(down, gbc);
down.addMouseListener(this);
return game;
private JPanel getOptionsPanel()
options = new JPanel(new BorderLayout());
options.setBackground(Color.pink);
options.add(new JLabel("options panel", JLabel.CENTER));
return options;
// mouse listener events
public void mouseClicked( MouseEvent e ) {
System.out.println("pressed");
public void mousePressed( MouseEvent e ) {
public void mouseReleased( MouseEvent e ) {
public void mouseEntered( MouseEvent e ) {
Border redline = BorderFactory.createLineBorder(Color.red);
JPanel x = (JPanel) e.getSource();
x.setBorder(redline);
public void mouseExited( MouseEvent e ){
JPanel x = (JPanel) e.getSource();
x.setBorder(null);
public static void main(String[] args ) {
Game exe = new Game();
exe.show();
}import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.text.NumberFormat;
public class Game extends JFrame implements MouseListener{
JPanel game, options, top, down, middle;
NumberFormat nf;
public Game() {
super("Game");
nf = NumberFormat.getPercentInstance();
nf.setMaximumFractionDigits(1);
JPanel center = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = gbc.BOTH;
gbc.weighty = 1.0;
gbc.weightx = 0.8;
center.add(getGamePanel(), gbc);
gbc.weightx = 0.104;
center.add(getOptionsPanel(), gbc);
Container cp = getContentPane();
// use the JFrame default BorderLayout
cp.add(center); // default center section
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(700,600);
// this.setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
addComponentListener(new ComponentAdapter(){
public void componentResized(ComponentEvent e){
showSizeInfo();
showSizeInfo();
private void showSizeInfo(){
Dimension d = getContentPane().getSize();
double totalWidth = game.getWidth() + options.getWidth();
double gamePercent = game.getWidth() / totalWidth;
double optionsPercent = options.getWidth() / totalWidth;
double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
double topPercent = top.getHeight() / totalHeight;
double middlePercent = middle.getHeight() / totalHeight;
double downPercent = down.getHeight() / totalHeight;
System.out.println("content size = " + d.width + ", " + d.height + "\n" +
"game width = " + nf.format(gamePercent) + "\n" +
"options width = " + nf.format(optionsPercent) + "\n" +
"top height = " + nf.format(topPercent) + "\n" +
"middle height = " + nf.format(middlePercent) + "\n" +
"down height = " + nf.format(downPercent) + "\n");
private JPanel getGamePanel(){
// init components
top = new JPanel(new BorderLayout());
top.setBackground(Color.red);
top.add(new JLabel("top panel", JLabel.CENTER));
middle = new JPanel(new BorderLayout());
middle.setBackground(Color.green.darker());
middle.add(new JLabel("middle panel", JLabel.CENTER));
down = new JPanel(new BorderLayout());
down.setBackground(Color.blue);
down.add(new JLabel("down panel", JLabel.CENTER));
// layout game panel
game = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.fill = gbc.BOTH;
gbc.gridwidth = gbc.REMAINDER;
gbc.weighty = 0.2;
game.add(top, gbc);
gbc.weighty = 0.425;
game.add(middle, gbc);
gbc.weighty = 0.2;
game.add(down, gbc);
down.addMouseListener(this);
return game;
private JPanel getOptionsPanel(){
options = new JPanel(new BorderLayout());
options.setBackground(Color.pink);
options.add(new JLabel("options panel", JLabel.CENTER));
return options;
public void mouseClicked( MouseEvent e ) {
System.out.println("pressed");
public void mousePressed( MouseEvent e ) {
public void mouseReleased( MouseEvent e ) {
public void mouseEntered( MouseEvent e ) {
Border redline = new CalmLineBorder(Color.red);
JPanel x = (JPanel) e.getSource();
x.setBorder(redline);
public void mouseExited( MouseEvent e ){
JPanel x = (JPanel) e.getSource();
x.setBorder(null);
public static void main(String[] args ) {
Game exe = new Game();
exe.setVisible(true);
class CalmLineBorder extends LineBorder{
public CalmLineBorder(Color c){
super(c);
public CalmLineBorder(Color c, int thick){
super(c, thick);
public CalmLineBorder(Color c, int thick, boolean round){
super(c, thick, round);
public Insets getBorderInsets(Component comp){
return new Insets(0, 0, 0, 0);
} -
Puzzle Game and new Game Problem
Hello Java Programmers,
Once again I have encountered a problem with my ongoing puzzle game. I have completed it all. Now I want my user to be able to start a new game in after they win. I tried repaint and update method with JFrame but it deosn't reshuffle the buttons. How can I do that. The code geos below.
[/b]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JOptionPane;
public class PuzzleGame{
String[] btn_Labels = {"1","2","3","4","5","6","7","8","9",
"10","11","12","13","14","15"," "};
String[] labels = {"1","2","3","4","5","6","7","8","9",
"10","11","12","13","14","15"};
private final int ONE = 1, TWO = 2, THREE = 3, FIVE = 5;
private boolean WIN_STATE = false;
private JButton b[];
public String clicked_btn_label = "";
//Constructor method.
public PuzzleGame(){
showSplashScreen();
initGame();
public static void main(String args[]){
PuzzleGame game = new PuzzleGame();
//When a new Game started labels of buttons are shuffled using this method.
public void shuffleNumbers(){
String temp = null;
for(int j=0; j<16; j++){
int k = (int)(Math.random()*16);
temp = btn_Labels[j];
btn_Labels[j] = btn_Labels[k];
btn_Labels[k] = temp;
//Game initialization method.
public void initGame(){
b = new JButton[16];
JPanel p = new JPanel();
JFrame frame = new JFrame();
shuffleNumbers();
for(int i=0; i<16; i++){
b[i] = new JButton();
b.setText(btn_Labels[i]);
b[i].setActionCommand(""+(i+1));
for(int i=0; i<16; i++){
b[i].addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
clicked_btn_label =(String)e.getActionCommand();
doSwapping();
checkWin();
p.add(b[i]);
p.setLayout(new GridLayout(4,4));
frame.getContentPane().add(p);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
Dimension dm = Toolkit.getDefaultToolkit().getScreenSize();
int x = (dm.width - 230)/2;
int y = (dm.height - 240)/2;
frame.setBounds(x,y,320,240);
frame.setSize(340,240);
frame.setVisible(true);
//This method swaps the clicked button with the empty button if it doesn't violate rule.
public void doSwapping(){
int num = Integer.parseInt(clicked_btn_label);
String temp;
if( (num + ONE <= 16) && b[num].getText() == " " && num % 4 != 0){
temp = b[num].getText();
b[num].setText(b[num-ONE].getText());
b[num-ONE].setText(temp);
else if((num - TWO >= 0) && b[num-TWO].getText() == " " && ((num - ONE) % 4 != 0)){
temp = b[num-ONE].getText();
b[num-ONE].setText(b[num-TWO].getText());
b[num-TWO].setText(temp);
else if( (num + THREE < 16) && b[num+THREE].getText() == " "){
temp = b[num-ONE].getText();
b[num-ONE].setText(b[num+THREE].getText());
b[num+THREE].setText(temp);
else if( (num - FIVE >= 0) && b[num-FIVE].getText() == " "){
temp = b[num-ONE].getText();
b[num-ONE].setText(b[num-FIVE].getText());
b[num-FIVE].setText(temp);
// else{}
public void checkWin(){
WIN_STATE = true;
for(int i=0; i<15; i++){
if( b[i].getText() != labels[i])
WIN_STATE = false;
if(WIN_STATE == true){
JOptionPane.showMessageDialog(null,"Congratulations You Have won the Game!","You Win",JOptionPane.INFORMATION_MESSAGE);
initGame();
public void showSplashScreen(){
JWindow w = new JWindow();
JPanel p = (JPanel)w.getContentPane();
JLabel l = new JLabel(new ImageIcon("splash.jpg"));
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - 230)/2;
int y = (d.height - 240)/2;
p.add(l);
w.setBounds(x,y,320,240);
w.setVisible(true);
try{
Thread.sleep(10000);
catch(Exception e){
w.setVisible(false);
[/b]Sorry for violation. I would like to add a menubar to the application containing a single menu button for new game. adding a menubar is simple but how can i reshuffle the buttons using methods like update etc. or any other way.
-
The Rules of Game of Life
For a space that is 'populated':
Each cell with one or no neighbors dies, as if by loneliness.
Each cell with four or more neighbors dies, as if by overpopulation.
Each cell with two or three neighbors survives.
For a space that is 'empty' or 'unpopulated'
Each cell with three neighbors becomes populated.
I have three classes: Cell, BoardComponent, and GameViewer
I got few problems in my code: 1. the button shows wrongly, 2. without the button, there is always a dot on the upper-left corner, which is not on purpose, 3, after click the mouse to initialize few dots, nothing happened
How could I fix those problems?
My Code:
1. Cell:
import java.awt.Rectangle;
public class Cell extends Rectangle{
public Cell(int x, int y, int side)
super(x, y, side, side);
}2. BoardComponent:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import com.sun.jdi.event.Event;
public class BoardComponent extends JComponent{
public BoardComponent()
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
board[i][j] = new Cell(i*SIDE, j*SIDE, SIDE);
public void paint(Graphics g)
Graphics2D g2 = (Graphics2D)g;
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
g2.draw(board[i][j]);
public void initialize(int x, int y)
Graphics g = getGraphics();
Graphics2D g2 = (Graphics2D) g;
if(g2.getColor().equals(Color.BLUE))
g2.getBackground();
else
g2.setColor(Color.BLUE);
g.fillOval(mouseX, mouseY, 10, 10);
public void generate()
int count = 0;
for(int i = 0; i < ROW-2; i++)
for(int j = 0; j < COL-2; j++)
for(int m = 0; m < 2; m++)
for(int n = 0; n < 2; n++)
if(m!=0 || n !=0)
if(!(board[i+m][j+n].isEmpty()))
count++;
if(count == 3 || count < 2 || count > 4)
initialize(i*SIDE, j*SIDE);
private int mouseX, mouseY;
private boolean mouseclicked = false;
public static final int ROW = 40;
public static final int COL = 40;
private Cell[][] board = new Cell[ROW][COL];
public static final int SIDE = 14;
}3. GameViewer:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GameViewer extends JFrame{
public static void main(String[] args)
final BoardComponent game = new BoardComponent();
class MouseClickListener extends MouseAdapter
public void mouseClicked(MouseEvent event)
int x = event.getX();
int y = event.getY();
game.initialize(x, y);
MouseAdapter listener = new MouseClickListener();
game.addMouseListener(listener);
JButton button = new JButton("Start");
class TimerListener implements ActionListener
public void actionPerformed(ActionEvent event)
game.generate();
ActionListener timer = new TimerListener();
button.setSize(40, 10);
button.setLocation(250, 500);
button.addActionListener(timer);
final int DELAY = 500;
Timer t = new Timer(DELAY, timer);
t.start();
JFrame window = new JFrame();
window.setSize(600, 600);
window.setTitle("Life of Game");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.add(game);
window.add(button);
window.setVisible(true);
}Thanks a million.As already said, you should override paintComponent(), not paint(), and don't forget to call the superclass's paintComponent() method.
public void paintComponent(Graphics g)
super.paintComponent(g);
}As for this method:
public void initialize(int x, int y)
Graphics g = getGraphics();
Graphics2D g2 = (Graphics2D) g;
if(g2.getColor().equals(Color.BLUE))
g2.getBackground();
else
g2.setColor(Color.BLUE);
g.fillOval(mouseX, mouseY, 10, 10);
}You really shouldn't be doing any painting outside the paintComponent() method.
Finally, your GameViewer class extends JFrame, but yet you are creating another JFrame in the main method. This doesn't make sense.
Maybe you are looking for
-
Can't Open Safari anymore - Crashes everytime
Process: Safari [19470] Path: /Applications/Safari.app/Contents/MacOS/Safari Identifier: com.apple.Safari Version: 8.0.2 (10600.2.5) Build Info: WebBrowser-7600002005000000~1 Code Typ
-
How can I make changes to an exixting PDF document
I HAVE TRIED EDITING SOME DOCUMENTS IN PDF TO PREVENT PARICY OF MY COMMUNICATIONS. I'm such a novice. please help!
-
Hi, I'm struggling with getting my program outfitted with a drag and drop function in and between a few JList components. (I'm using NetBeans IDE 6.7) I have four JLists of which only one I want to enabled drag and drop rearrangement of the strings.
-
I am trying to install some xrpm components through jspm but I need to make j2ee start first. Previously I was trying to setup xpd user to CAF roles.... unsuccesfully, changed some UMe properties. already tried to set to default values in the configt
-
Table name for SRM Purchasing Org.
Hi, I have created an org. unit for purchasing org and it is linked to the back-end purchasing org ( Function TAB). Now I want to know where is purchasing org. (Function TAB) is stored in SRM table please help -Pranav