Search Results

Search found 269 results on 11 pages for 'actionlistener'.

Page 2/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • JFrame not working correctly

    - by Nick Gibson
    This is making me very angry, I have worked on this for 2 days, have 2 books open and have looked through them, and STILL can't get this program to run the way I want it run. I'm getting to the point where if this doesn't help, I quit. I want a SIMPLE Frame application. It has a JComboBox centered at the top. Next to it is a text field big enough to show numeric digits such as "$49.99" Below it is a spot for a Text area showing terms of service Below that is the checkbox agreeing to the terms of service Below that is 2 buttons "Accept" and "Decline" I Have worked on this for 2 days, here is the coding: public class Bar extends JFrame implements ActionListener { public Bar(final JFrame frame) { String[] tests = { "A+ Certification", "Network+ Certification", "Security+ Certification", "CIT Full Test Package" }; JButton button = new JButton("Click Meh"); add(new JLabel("Welcome to the CIT Test Program ")); add(new JLabel("Please select which Test Package from the list below.")); frame.setVisible(true); frame.setSize(250,250); JPanel pane1 = new JPanel(new FlowLayout()); JPanel pane2 = new JPanel(new FlowLayout()); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu editMenu = new JMenu("Edit"); JMenu helpMenu = new JMenu("Help"); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(helpMenu); JMenuItem newMenu = new JMenuItem("New (Ctrl+N)"); JMenuItem openMenu = new JMenuItem("Open (Ctrl+O)"); JMenuItem saveMenu = new JMenuItem("Save (Ctrl+S)"); saveMenu.addActionListener(this); JMenuItem exitMenu = new JMenuItem("Exit (Ctrl+W)"); JMenuItem cutMenu = new JMenuItem("Cut (Ctrl+X)"); JMenuItem copyMenu = new JMenuItem("Copy (Ctrl+C)"); JMenuItem pasteMenu = new JMenuItem("Paste (Ctrl+V)"); JMenuItem infoMenu = new JMenuItem("Help (Ctrl+H)"); fileMenu.add(newMenu); fileMenu.add(openMenu); fileMenu.add(saveMenu); fileMenu.add(exitMenu); editMenu.add(cutMenu); editMenu.add(copyMenu); editMenu.add(pasteMenu); helpMenu.add(infoMenu); frame.setJMenuBar(menuBar); JComboBox packageChoice = new JComboBox(tests); frame.add(packageChoice); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); { } } EDIT: Forgot to add the second program public class JFrameWithPanel { public static void main(String[] args) { JPanel panel = new Bar(new JFrame("CIT Test Program")); } } How do I get this to have everything where I want it and show up? I'm very confused because of this and now barely even get how Frames work.

    Read the article

  • Superclass Sensitive Actions

    - by Geertjan
    I've created a small piece of functionality that enables you to create actions for Java classes in the IDE. When the user right-clicks on a Java class, they will see one or more actions depending on the superclass of the selected class. To explain this visually, here I have "BlaTopComponent.java". I right-click on its node in the Projects window and I see "This is a TopComponent": Indeed, when you look at the source code of "BlaTopComponent.java", you'll see that it implements the TopComponent class. Next, in the screenshot below, you see that I have right-click a different class. In this case, there's an action available because the selected class implements the ActionListener class. Then, take a look at this one. Here both TopComponent and ActionListener are superclasses of the current class, hence both the actions are available to be invoked: Finally, here's a class that subclasses neither TopComponent nor ActionListener, hence neither of the actions that I created for doing something that relates to TopComponents or ActionListeners is available, since those actions are irrelevant in this context: How does this work? Well, it's a combination of my blog entries "Generic Node Popup Registration Solution" and "Showing an Action on a TopComponent Node". The cool part is that the definition of the two actions that you see above is remarkably trivial: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import org.openide.loaders.DataObject; import org.openide.util.Utilities; public class TopComponentSensitiveAction implements ActionListener { private final DataObject context; public TopComponentSensitiveAction() { context = Utilities.actionsGlobalContext().lookup(DataObject.class); } @Override public void actionPerformed(ActionEvent ev) { //Do something with the context: JOptionPane.showMessageDialog(null, "TopComponent: " + context.getNodeDelegate().getDisplayName()); } } The above is the action that will be available if you right-click a Java class that extends TopComponent. This, in turn, is the action that will be available if you right-click a Java class that implements ActionListener: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import org.openide.loaders.DataObject; import org.openide.util.Utilities; public class ActionListenerSensitiveAction implements ActionListener { private final DataObject context; public ActionListenerSensitiveAction() { context = Utilities.actionsGlobalContext().lookup(DataObject.class); } @Override public void actionPerformed(ActionEvent ev) { //Do something with the context: JOptionPane.showMessageDialog(null, "ActionListener: " + context.getNodeDelegate().getDisplayName()); } } Indeed, the classes, at this stage are the same. But, depending on what I want to do with TopComponents or ActionListeners, I now have a starting point, which includes access to the DataObject, from where I can get down into the source code, as shown here. This is how the two ActionListeners that you see defined above are registered in the layer, which could ultimately be done via annotations on the ActionListeners, of course: <folder name="Actions"> <folder name="Tools"> <file name="org-netbeans-sbas-impl-TopComponentSensitiveAction.instance"> <attr stringvalue="This is a TopComponent" name="displayName"/> <attr name="instanceCreate" methodvalue="org.netbeans.sbas.SuperclassSensitiveAction.create"/> <attr name="type" stringvalue="org.openide.windows.TopComponent"/> <attr name="delegate" newvalue="org.netbeans.sbas.impl.TopComponentSensitiveAction"/> </file> <file name="org-netbeans-sbas-impl-ActionListenerSensitiveAction.instance"> <attr stringvalue="This is an ActionListener" name="displayName"/> <attr name="instanceCreate" methodvalue="org.netbeans.sbas.SuperclassSensitiveAction.create"/> <attr name="type" stringvalue="java.awt.event.ActionListener"/> <attr name="delegate" newvalue="org.netbeans.sbas.impl.ActionListenerSensitiveAction"/> </file> </folder> </folder> <folder name="Loaders"> <folder name="text"> <folder name="x-java"> <folder name="Actions"> <file name="org-netbeans-sbas-impl-TopComponentSensitiveAction.shadow"> <attr name="originalFile" stringvalue="Actions/Tools/org-netbeans-sbas-impl-TopComponentSensitiveAction.instance"/> <attr intvalue="150" name="position"/> </file> <file name="org-netbeans-sbas-impl-ActionListenerSensitiveAction.shadow"> <attr name="originalFile" stringvalue="Actions/Tools/org-netbeans-sbas-impl-ActionListenerSensitiveAction.instance"/> <attr intvalue="160" name="position"/> </file> </folder> </folder> </folder> </folder> The most important parts of the layer registration are the lines that are highlighted above. Those lines connect the layer to the generic action that delegates back to the action listeners defined above, as follows: public final class SuperclassSensitiveAction extends AbstractAction implements ContextAwareAction { private final Map map; //This method is called from the layer, via "instanceCreate", //magically receiving a map, which contains all the attributes //that are defined in the layer for the file: static SuperclassSensitiveAction create(Map map) { return new SuperclassSensitiveAction(Utilities.actionsGlobalContext(), map); } public SuperclassSensitiveAction(Lookup context, Map m) { super(m.get("displayName").toString()); this.map = m; String superclass = m.get("type").toString(); //Enable the menu item only if //we're dealing with a class of type superclass: JavaSource javaSource = JavaSource.forFileObject( context.lookup(DataObject.class).getPrimaryFile()); try { javaSource.runUserActionTask(new ScanTask(this, superclass), true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } //Hide the menu item if it isn't enabled: putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true); } @Override public void actionPerformed(ActionEvent ev) { ActionListener delegatedAction = (ActionListener)map.get("delegate"); delegatedAction.actionPerformed(ev); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new SuperclassSensitiveAction(actionContext, map); } private class ScanTask implements Task<CompilationController> { private SuperclassSensitiveAction action = null; private String superclass; private ScanTask(SuperclassSensitiveAction action, String superclass) { this.action = action; this.superclass = superclass; } @Override public void run(final CompilationController info) throws Exception { info.toPhase(Phase.ELEMENTS_RESOLVED); new EnableIfGivenSuperclassMatches(info, action, superclass).scan( info.getCompilationUnit(), null); } } private static class EnableIfGivenSuperclassMatches extends TreePathScanner<Void, Void> { private CompilationInfo info; private final AbstractAction action; private final String superclassName; public EnableIfGivenSuperclassMatches(CompilationInfo info, AbstractAction action, String superclassName) { this.info = info; this.action = action; this.superclassName = superclassName; } @Override public Void visitClass(ClassTree t, Void v) { Element el = info.getTrees().getElement(getCurrentPath()); if (el != null) { TypeElement te = (TypeElement) el; List<? extends TypeMirror> interfaces = te.getInterfaces(); if (te.getSuperclass().toString().equals(superclassName)) { action.setEnabled(true); } else { action.setEnabled(false); } for (TypeMirror typeMirror : interfaces) { if (typeMirror.toString().equals(superclassName)){ action.setEnabled(true); } } } return null; } } } This is a pretty cool solution and, as you can see, very generic. Create a new ActionListener, register it in the layer so that it maps to the generic class above, and make sure to set the type attribute, which defines the superclass to which the action should be sensitive.

    Read the article

  • Manage multiple Jlabel's events

    - by IMAnis_tn
    I have a left Panel with multiples Jlabels which i use them as buttons to change a Main Panel's content which is layouted with a CardLayout. I cant work perfectly with these events: mouseEntered : to make highlight effect to the jlabel mouseExited : to take off the highlight effect. mouseClicked : to change the content of the main Panel and start some threads The problem here that can't found an event or a method tell me that another Jlabel has been clicked so i can stop my threads started in the mouseClicked event, OR an event or method tell me that a JPanel in the CardLayout has been displayed or hidden.

    Read the article

  • Sleep a thread until an event is attended in another thread from a different class

    - by Afro Genius
    I have an application that fires 2 threads, the 1st launches another class to do some processing which in turn launches a 3rd class to do yet more processing. The 2nd thread in the main class should wait until some event in the 3rd class completes before it performs its job. How can this be achieved? I had tried implementing a wait/notify to share a lock object between the two threads but technically this will not work as I found the hard way. Can I share a lock between classes? Note, an instance of the 3rd class is declared in the 1st class and passed as parameter to the 2nd class. Also I tried creating boolean value in 3rd class that tells when event is complete then poll 2nd thread till this value is true. This worked but is not very desirable. Also is actionListner a better approach to this problem?

    Read the article

  • What is the common way to program action listeners?

    - by Roman
    I just started to learn how to use action listeners. To my understanding it works in the following way: There are some classes which contains "addActionListener" method by default (for example classes for buttons). Using this method we add an action listener to an object. For example: listenedObject.addActionListener(listeningObject). When an action with the "listenedObject" is performed, the "actionPerformed" method of the "listeningObject" will be called. So, it means that when we program a class for the listeningObject, we need to put there "actionPerformed" method. What is not clear to me, should we create a new class for every object that we want to listen. It does not seem to me as an elegant solution. On the other hand, if we have one action listener class for all (or at least many) object, than we have a problem since a instance of this class will not know which object is calling the "actionPerformed" method (and we need to know that since actions performed by the actionPerformed differs depending on who is called for this method). In my opinion, for every listened object we need to create are "personal" action listener and we can do it by setting a specific value to the corresponding field of the action listener. But I am not sure that it is a standard way to go? How do usually people do it?

    Read the article

  • Using addMouseListener() and paintComponent() for JPanel

    - by Alex
    This is a follow-up to my previous question. I've simplified things as much as I could, and it still doesn't work! Although the good thing I got around using getGraphics(). A detailed explanation on what goes wrong here is massively appreciated. My suspicion is that something's wrong with the the way I used addMouseListener() method here. import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JPanel; public class MainClass1{ private static PaintClass22 inst2 = new PaintClass22(); public static void main(String args[]){ JFrame frame1 = new JFrame(); frame1.add(inst2); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.setTitle("NewPaintToolbox"); frame1.setSize(200, 200); frame1.setLocationRelativeTo(null); frame1.setVisible(true); } } class PaintClass11 extends MouseAdapter{ int xvar; int yvar; static PaintClass22 inst1 = new PaintClass22(); public PaintClass11(){ inst1.addMouseListener(this); inst1.addMouseMotionListener(this); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub xvar = arg0.getX(); yvar = arg0.getY(); inst1.return_paint(xvar, yvar); } } class PaintClass22 extends JPanel{ private static int varx; private static int vary; public void return_paint(int input1, int input2){ varx = input1; vary = input2; repaint(varx,vary,10,10); } public void paintComponent(Graphics g){ super.paintComponents(g); g.setColor(Color.RED); g.fillRect(varx, vary, 10, 10); } }

    Read the article

  • Java Simple Calculator

    - by Lahiru Kavinda
    I have made this calculator program in Java. This works well only when two numbers are calculated at one time. That means to get the sum of 1+2+3 you have to go this way : press 1 press + press 2 press = press + press 3 press = and it calculates it as 6. But I want to program this so that I can get the answer by: press 1 press + press 2 press + press 3 press = but this gives the answer 5!!! How to code this so that it works like an ordinary calculator? Here is my code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class cal1 extends JFrame { double op1 = 0d, op2 = 0d; double result = 0d; char action; boolean b = false; boolean pressequal = false; public cal1() { makeUI(); } private void makeUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); b0 = new JButton("0"); b1 = new JButton("1"); b2 = new JButton("2"); b3 = new JButton("3"); b4 = new JButton("4"); b5 = new JButton("5"); b6 = new JButton("6"); b7 = new JButton("7"); b8 = new JButton("8"); b9 = new JButton("9"); bDot = new JButton("."); bMul = new JButton("*"); bDiv = new JButton("/"); bPlus = new JButton("+"); bMinus = new JButton("-"); bEq = new JButton("="); t = new JTextField(12); t.setFont(new Font("Tahoma", Font.PLAIN, 24)); t.setHorizontalAlignment(JTextField.RIGHT); numpad = new JPanel(); display = new JPanel(); numpad.add(b7); numpad.add(b8); numpad.add(b9); numpad.add(bMul); numpad.add(b4); numpad.add(b5); numpad.add(b6); numpad.add(bDiv); numpad.add(b1); numpad.add(b2); numpad.add(b3); numpad.add(bMinus); numpad.add(bDot); numpad.add(b0); numpad.add(bEq); numpad.add(bPlus); numpad.setLayout(new GridLayout(4, 5, 5, 4)); display.add(t); add(display, BorderLayout.NORTH); add(numpad, BorderLayout.CENTER); t.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { typeOnt(e); } }); b0.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b0pressed(e); } }); b1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b1pressed(e); } }); b2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b2pressed(e); } }); b3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b3pressed(e); } }); b4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b4pressed(e); } }); b5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b5pressed(e); } }); b6.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b6pressed(e); } }); b7.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b7pressed(e); } }); b8.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b8pressed(e); } }); b9.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b9pressed(e); } }); bDot.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bDotpressed(e); } }); bPlus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bPlusPressed(e); } }); bMinus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bMinusPressed(e); } }); bMul.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bMulPressed(e); } }); bDiv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bDivPressed(e); } }); bEq.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bEqpressed(e); } }); } void typeOnt(KeyEvent e) { e.consume(); } void b0pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "0"); } else { t.setText(t.getText() + "0"); } } void b1pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "1"); } else { t.setText(t.getText() + "1"); } } void b2pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "2"); } else { t.setText(t.getText() + "2"); } } void b3pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "3"); } else { t.setText(t.getText() + "3"); } } void b4pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "4"); } else { t.setText(t.getText() + "4"); } } void b5pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "5"); } else { t.setText(t.getText() + "5"); } } void b6pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "6"); } else { t.setText(t.getText() + "6"); } } void b7pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "7"); } else { t.setText(t.getText() + "7"); } } void b8pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "8"); } else { t.setText(t.getText() + "8"); } } void b9pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "9"); } else { t.setText(t.getText() + "9"); } } void bDotpressed(ActionEvent e) { if (!t.getText().contains(".")) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "0."); } else if (t.getText().isEmpty()) { t.setText("0."); } else { t.setText(t.getText() + "."); } } } void bPlusPressed(ActionEvent e) { b = true; action = '+'; op1 = Double.parseDouble(t.getText()); } void bMinusPressed(ActionEvent e) { b = true; action = '-'; op1 = Double.parseDouble(t.getText()); } void bMulPressed(ActionEvent e) { b = true; action = '*'; op1 = Double.parseDouble(t.getText()); } void bDivPressed(ActionEvent e) { b = true; action = '/'; op1 = Double.parseDouble(t.getText()); } void bEqpressed(ActionEvent e) { op2 = Double.parseDouble(t.getText()); doCal(); } void doCal() { switch (action) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case '*': result = op1 * op2; break; case '/': result = op1 / op2; break; } t.setText(String.valueOf(result)); } public static void main(String[] args) { new cal1().setVisible(true); } JButton b0; JButton b1; JButton b2; JButton b3; JButton b4; JButton b5; JButton b6; JButton b7; JButton b8; JButton b9; JButton bDot; JButton bPlus; JButton bMinus; JButton bMul; JButton bDiv; JButton bEq; JPanel display; JPanel numpad; JTextField t; }

    Read the article

  • Why Timer does not work if we do not generate a window?

    - by Roman
    Here is the code: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.Timer; public class TimerSample { public static void main(String args[]) { new JFrame().setVisible(true); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println("Hello World Timer"); } }; Timer timer = new Timer(500, actionListener); timer.start(); } } It generates a window and then periodically prints "Hello World Timer" in the terminal (Command Prompt). If I comment this line new JFrame().setVisible(true); the application do not print anything to the command line. Why?

    Read the article

  • JPedal Action for Converting PDF to JavaFX

    - by Geertjan
    The question of the day comes from Mark Stephens, from JPedal (JPedal is the leading 100% Java PDF library, providing a Java PDF viewer, PDF to image conversion, PDF printing or adding PDF search and PDF extraction features), in the form of a screenshot: The question is clear. By looking at the annotations above, you can see that Mark has an ActionListener that has been bound to the right-click popup menu on PDF files. Now he needs to get hold of the file to which the Action has been bound. How, oh  how, can one get hold of that file? Well, it's simple. Leave everything you see above exactly as it is but change the Java code section to this: public final class PDF2JavaFXContext implements ActionListener {     private final DataObject context;     public PDF2JavaFXContext(DataObject context) {         this.context = context;     }     public void actionPerformed(ActionEvent ev) {         FileObject fo = context.getPrimaryFile();         File theFile = FileUtil.toFile(fo);         //do something with your file...     } } The point is that the annotations at the top of the class bind the Action to either Actions.alwaysEnabled, which is a factory method for creating always-enabled Actions, or Actions.context, which is a factory method for creating context-sensitive Actions. How does the Action get bound to the factory method? The annotations are converted, when the module is compiled, into XML registration entries in the "generated-layer.xml", which you can find in your "build" folder, in the Files window, after building the module. In Mark's case, since the Action should be context-sensitive to PDF files, he needs to bind his PDF2JavaFXContext ActionListener (which should probably be named "PDF2JavaFXActionListener", since the class is an ActionListener) to Actions.context. All he needs to do that is pass in the object he wants to work with into the constructor of the ActionListener. Now, when the module is built, the annotation processor is going to take the annotations and convert them to XML registration entries, but the constructor will also be checked to see whether it is empty or not. In this case, the constructor isn't empty, hence the Action should be context-sensitive and so the ActionListener is bound to Actions.context. The Actions.context will do all the enablement work for Mark, so that he will not need to provide any code for enabling/disabling the Action. The Action will be enabled whenever a DataObject is selected. Since his Action is bound to Nodes in the Projects window that represent PDF files, the Action will always be enabled whenever Mark right-clicks on a PDF Node, since the Node exposes its own DataObject. Once Mark has access to the DataObject, he can get the underlying FileObject via getPrimaryFile and he can then convert the FileObject to a java.io.File via FileUtil.getConfigFile. Once he's got the java.io.File, he can do with it whatever he needs. Further reading: http://bits.netbeans.org/dev/javadoc/

    Read the article

  • C++Template in Java?

    - by RnMss
    I want something like this: public abstract class ListenerEx<LISTENER, PARENT> implements LISTENER { PARENT parent; public ListenerEx(PARENT p) { parent = p; } } But it doesn't compile. Is there a better solution? Is there something in Java like C++ template that would do check syntax after template deduction? The following explains why I need such a ListenerEX class, if you already know what it is, you don't need to read the following. I have a main window, and a button on it, and I want to get access to some method of the main window's within the listener: public class MainWindow extends JFrame { public void doSomething() { /* ... */ } public void doSomethingElse() { /* ... */ } private JButton button; public MainWindow() { button = new JButton(...); add(button); button.setActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSomething(); doSomethingElse(); } }); } } This would compile but does not work properly all the time. (Why would it compile when the ActionListener does not have doSomething() method?) Of course we can do it like this: public class MainWindow extends JFrame { public void doSomething() { } public void doSomethingElse() { } private JButton button; public MainWindow() { button = new JButton(...); add(button); class ActionListener1 implements ActionListener { MainWindow parent; public ActionListener(MainWindow p) { parent = p; } public void actionPerformed(ActionEvent e) { parent.doSomething(); parent.doSomethingElse(); } } button.setActionListener(new ActionListener1(this)); } } However I hate this style ... So I tried: public abstract class ActionListenerEx<P> implements ActionListener { P parent; public ActionListenerEx(P p) { parent = p; } } public class MainWindow extends JFrame { public void doSomething() { } public void doSomethingElse() { } private JButton button; public MainWindow() { button = new JButton(...); add(button); button.setActionListener(new ActionListenerEx<MainWindow>(this) { public void actionPerformed(ActionEvent e) { parent.doSomething(); parent.doSomethingElse(); } }); } } But there's lots of Listeners beside the ActionListener ... public abstract class ActionListenerEx<LISTENER, PARENT> implements LISTENER { PARENT parent; public ActionListenerEx(PARENT p) { parent = p; } } However, it won't compile ... I am fresh at Java, and I wonder if there's already better solution.

    Read the article

  • View Clipboard & Copy To Clipboard from NetBeans IDE

    - by Geertjan
    Thanks to this code, I can press Ctrl-Alt-V in NetBeans IDE and then view whatever is in the clipboard: import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.JOptionPane; import org.openide.awt.ActionRegistration; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionID; import org.openide.util.NbBundle.Messages; @ActionID( category = "Tools", id = "org.demo.ShowClipboardAction") @ActionRegistration( displayName = "#CTL_ShowClipboardAction") @ActionReferences({ @ActionReference(path = "Menu/Tools", position = 5), @ActionReference(path = "Shortcuts", name = "DA-V") }) @Messages("CTL_ShowClipboardAction=Show Clipboard") public final class ShowClipboardAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, getClipboard(), "Clipboard Content", 1); } public String getClipboard() { String text = null; Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); try { if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { text = (String) t.getTransferData(DataFlavor.stringFlavor); } } catch (UnsupportedFlavorException e) { } catch (IOException e) { } return text; } } And now I can also press Ctrl-Alt-C, which copies the path to the current file to the clipboard: import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.awt.StatusDisplayer; import org.openide.loaders.DataObject; import org.openide.util.NbBundle.Messages; @ActionID( category = "Tools", id = "org.demo.CopyPathToClipboard") @ActionRegistration( displayName = "#CTL_CopyPathToClipboard") @ActionReferences({ @ActionReference(path = "Menu/Tools", position = 0), @ActionReference(path = "Editors/Popup", position = 10), @ActionReference(path = "Shortcuts", name = "DA-C") }) @Messages("CTL_CopyPathToClipboard=Copy Path to Clipboard") public final class CopyPathToClipboardAction implements ActionListener { private final DataObject context; public CopyPathToClipboardAction(DataObject context) { this.context = context; } @Override public void actionPerformed(ActionEvent e) { String path = context.getPrimaryFile().getPath(); StatusDisplayer.getDefault().setStatusText(path); StringSelection ss = new StringSelection(path); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(ss, null); } }

    Read the article

  • Question: Richfaces tabPanel - using the same page for the different tabs changing the content dinam

    - by user280320
    I am using Seam 2.1.2 and RichFaces 3.3.2.SR1. <a4j:form> <rich:tabPanel switchType="ajax"> <rich:tab label="TAB 1" actionListener="#{outControl.tab1}" immediate="true"> <ui:include src="/pages/agenda/TabContain.xhtml" /> </rich:tab> <rich:tab label="TAB 2" actionListener="#{outControl.tab2}"> <ui:include src="/pages/agenda/TabContain.xhtml" /> </rich:tab> ... TabContain.xhtml: <rich:extendedDataTable value="#{manBean.seDataModel}" var="out" id="bc_table" sortMode="#{manBean.sortMode}" selectionMode="#{manBean.selectionMode}" tableState="#{manBean.tableState}" selection="#{manBean.selection}" rowKeyVar="rkvar"> <rich:column sortable="false" id="bc_col_0"> ... The content of extendedDataTable should be dependent of the tab selected. My first approach was to set an actionListener in the tabs and change the manBean within that action. After that actionListener even if I can see in the logs that the manBean has changed, this is not reflected in the page in the browser. It's like not refreshing. I tried setting a rerender in the rich:tab but that's also not doing it. Any idea? Also happy about other approaches, this might be not the best one.

    Read the article

  • h:commandButton action not working inside a h:datatable.

    - by Chris
    I'm stuck with this piece of jsf code that I don't understand why it's working when used outside a datatable and doesn't inside a datatable... <h:dataTable id="myTable" rendered="true" value="#{bean.selectedItemsList}" var="items"> <h:column> <h:commandButton action="#{bean.removeItemFromList}" image="/resources/images/deleterow.gif"> <f:actionListener binding="#{bean.actionListenerImpl}" type="com.mycorp.ActionListenerImpl"/> </h:commandButton> </h:column> <h:column> <h:outputText value="#{items}" /> </h:column> </h:dataTable> I read around the net to put value="#{items}" inside the action listener so the action can get the items in the row like this: <f:actionListener value="#{items}" binding="#{bean.actionListenerImpl}" type="com.mycorp.ActionListenerImpl"/> But it's doesn't work either. Bu if I do the action outside the data table everything work fine. <h:commandButton action="#{bean.removeItemFromList}" image="/resources/images/deleterow.gif"> <f:actionListener binding="#{bean.actionListenerImpl}" type="com.mycorp.ActionListenerImpl"/> </h:commandButton> Side note I also tried a4j:commandButton and didn't so I guess my problem is probably the actionlistener or how the bean handling it.

    Read the article

  • Collision Detection within Player/Enemy Class

    - by user1264811
    I'm making a 2D platform game. Right now I'm just working on making a very generic Player class. I'm wondering if it would be more efficient/better practice to have an ActionListener within the Player class to detect collisions with Enemy objects (also have an ActionListener) or to handle all the collisions in the main world. Furthermore, I'm thinking ahead about how I will handle collisions with the platforms themselves. I've looked into the double boolean arrays to see which tiles players can go to and which they can't. I don't understand how to use this class and the player class at the same time. Thank you.

    Read the article

  • Should my game handle collisions in the Player object?

    - by user1264811
    I'm making a 2D platform game. Right now I'm just working on making a very generic Player class. I'm wondering if it would be more efficient/better practice to have an ActionListener within the Player class to detect collisions with Enemy objects (also have an ActionListener) or to handle all the collisions in the main world. Furthermore, I'm thinking ahead about how I will handle collisions with the platforms themselves. I've looked into the double boolean arrays to see which tiles players can go to and which they can't. I don't understand how to use this class and the player class at the same time.

    Read the article

  • Keeping socket open to send files on timer calls?

    - by user3704768
    I'm writing a program that requires an image to be fetched from a remote server every 10 milliseconds or so, as that's how often the image is updated. My current method calls a timer to grab the image, but it encounters Socket Closed errors all the time, and sometimes does not work at all. How can I fix my methods to keep the socket open the whole time, so no reconnecting is needed? Here is the full class: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.Timer; public class Connection { public static void createServer() throws IOException { Capture.getScreen(); ServerSocket socket = null; try { socket = new ServerSocket(12345, 0, InetAddress.getByName("127.0.0.1")); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Server started on " + socket.getInetAddress().getHostAddress() + ":" + socket.getLocalPort() + ",\nWaiting for client to connect."); final Socket clientConnection = socket.accept(); System.out.println("Client accepted from " + clientConnection.getInetAddress().getHostAddress() + ", sending file"); ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("Sending File"); try { pipeStreams(new FileInputStream(new File( "captures/sCap.png")), clientConnection.getOutputStream(), 1024); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }; System.out.println("closing out connection"); try { clientConnection.close(); } catch (IOException e) { e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } Timer timer = new Timer(10, taskPerformer); timer.setRepeats(true); timer.start(); } public static void createClient() throws IOException { System.out.println("Connecting to server."); final Socket socket = new Socket(); try { socket.connect(new InetSocketAddress(InetAddress .getByName("127.0.0.1"), 12345)); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { } ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("Success, retreiving file."); try { pipeStreams(socket.getInputStream(), new FileOutputStream( new File("captures/rCap.png")), 1024); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { } } }; System.out.println("Closing connection"); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } Timer timer = new Timer(10, taskPerformer); timer.setRepeats(true); timer.start(); } public static void pipeStreams(java.io.InputStream source, java.io.OutputStream destination, int bufferSize) throws IOException { byte[] buffer = new byte[bufferSize]; int read = 0; while ((read = source.read(buffer)) != -1) { destination.write(buffer, 0, read); } destination.flush(); destination.close(); source.close(); } }

    Read the article

  • Stop method not working

    - by avoq
    Hi everyone , can anybody tell me why the following code doesn't work properly? I want to play and stop an audio file. I can do the playback but whenever I click the stop button nothing happens. Here's the code : Thank you. .................. import java.io.*; import javax.sound.sampled.*; import javax.swing.*; import java.awt.event.*; public class SoundClipTest extends JFrame { final JButton button1 = new JButton("Play"); final JButton button2 = new JButton("Stop"); int stopPlayback = 0; // Constructor public SoundClipTest() { button1.setEnabled(true); button2.setEnabled(false); // button play button1.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ button1.setEnabled(false); button2.setEnabled(true); play(); }// end actionPerformed }// end ActionListener );// end addActionListener() // button stop button2.addActionListener( new ActionListener(){ public void actionPerformed( ActionEvent e){ //Terminate playback before EOF stopPlayback = 1; }//end actionPerformed }//end ActionListener );//end addActionListener() this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("Test Sound Clip"); this.setSize(300, 200); JToolBar bar = new JToolBar(); bar.add(button1); bar.add(button2); bar.setOrientation(JToolBar.VERTICAL); add("North", bar); add("West", bar); setVisible(true); } void play() { try { final File inputAudio = new File("first.wav"); // First, we get the format of the input file final AudioFileFormat.Type fileType = AudioSystem.getAudioFileFormat(inputAudio).getType(); // Then, we get a clip for playing the audio. final Clip c = AudioSystem.getClip(); // We get a stream for playing the input file. AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio); // We use the clip to open (but not start) the input stream c.open(ais); // We get the format of the audio codec (not the file format we got above) final AudioFormat audioFormat = ais.getFormat(); c.start(); if (stopPlayback == 1 ) {c.stop();} } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } }// end play public static void main(String[] args) { //new SoundClipTest().play(); new SoundClipTest(); } }

    Read the article

  • Beginner Scoring program button development in Java [migrated]

    - by A.G.
    I'm trying to add a "green team" to an example scoring GUI I found online. For some reason, the code compiles, but it runs with only the original two teams. I've tried playing around with the sizes/locations somewhat clumsily, and since no change was observed with these modications (NO change at ALL), I admit that I must be missing some necessary property or something. Any help? Here's the code: import javax.swing.*; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class ButtonDemo_Extended3 implements ActionListener{ // Definition of global values and items that are part of the GUI. int redScoreAmount = 0; int blueScoreAmount = 0; int greenScoreAmount = 0; JPanel titlePanel, scorePanel, buttonPanel; JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore; JButton redButton, blueButton, greenButton,resetButton; public JPanel createContentPane (){ // We create a bottom JPanel to place everything on. JPanel totalGUI = new JPanel(); totalGUI.setLayout(null); // Creation of a Panel to contain the title labels titlePanel = new JPanel(); titlePanel.setLayout(null); titlePanel.setLocation(0, 0); titlePanel.setSize(500, 500); totalGUI.add(titlePanel); redLabel = new JLabel("Red Team"); redLabel.setLocation(300, 0); redLabel.setSize(100, 30); redLabel.setHorizontalAlignment(0); redLabel.setForeground(Color.red); titlePanel.add(redLabel); blueLabel = new JLabel("Blue Team"); blueLabel.setLocation(900, 0); blueLabel.setSize(100, 30); blueLabel.setHorizontalAlignment(0); blueLabel.setForeground(Color.blue); titlePanel.add(blueLabel); greenLabel = new JLabel("Green Team"); greenLabel.setLocation(600, 0); greenLabel.setSize(100, 30); greenLabel.setHorizontalAlignment(0); greenLabel.setForeground(Color.green); titlePanel.add(greenLabel); // Creation of a Panel to contain the score labels. scorePanel = new JPanel(); scorePanel.setLayout(null); scorePanel.setLocation(10, 40); scorePanel.setSize(500, 30); totalGUI.add(scorePanel); redScore = new JLabel(""+redScoreAmount); redScore.setLocation(0, 0); redScore.setSize(40, 30); redScore.setHorizontalAlignment(0); scorePanel.add(redScore); greenScore = new JLabel(""+greenScoreAmount); greenScore.setLocation(60, 0); greenScore.setSize(40, 30); greenScore.setHorizontalAlignment(0); scorePanel.add(greenScore); blueScore = new JLabel(""+blueScoreAmount); blueScore.setLocation(130, 0); blueScore.setSize(40, 30); blueScore.setHorizontalAlignment(0); scorePanel.add(blueScore); // Creation of a Panel to contain all the JButtons. buttonPanel = new JPanel(); buttonPanel.setLayout(null); buttonPanel.setLocation(10, 80); buttonPanel.setSize(2600, 70); totalGUI.add(buttonPanel); // We create a button and manipulate it using the syntax we have // used before. Now each button has an ActionListener which posts // its action out when the button is pressed. redButton = new JButton("Red Score!"); redButton.setLocation(0, 0); redButton.setSize(30, 30); redButton.addActionListener(this); buttonPanel.add(redButton); blueButton = new JButton("Blue Score!"); blueButton.setLocation(150, 0); blueButton.setSize(30, 30); blueButton.addActionListener(this); buttonPanel.add(blueButton); greenButton = new JButton("Green Score!"); greenButton.setLocation(250, 0); greenButton.setSize(30, 30); greenButton.addActionListener(this); buttonPanel.add(greenButton); resetButton = new JButton("Reset Score"); resetButton.setLocation(0, 100); resetButton.setSize(50, 30); resetButton.addActionListener(this); buttonPanel.add(resetButton); totalGUI.setOpaque(true); return totalGUI; } // This is the new ActionPerformed Method. // It catches any events with an ActionListener attached. // Using an if statement, we can determine which button was pressed // and change the appropriate values in our GUI. public void actionPerformed(ActionEvent e) { if(e.getSource() == redButton) { redScoreAmount = redScoreAmount + 1; redScore.setText(""+redScoreAmount); } else if(e.getSource() == blueButton) { blueScoreAmount = blueScoreAmount + 1; blueScore.setText(""+blueScoreAmount); } else if(e.getSource() == greenButton) { greenScoreAmount = greenScoreAmount + 1; greenScore.setText(""+greenScoreAmount); } else if(e.getSource() == resetButton) { redScoreAmount = 0; blueScoreAmount = 0; greenScoreAmount = 0; redScore.setText(""+redScoreAmount); blueScore.setText(""+blueScoreAmount); greenScore.setText(""+greenScoreAmount); } } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("[=] JButton Scores! [=]"); //Create and set up the content pane. ButtonDemo_Extended demo = new ButtonDemo_Extended(); frame.setContentPane(demo.createContentPane()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1024, 768); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }

    Read the article

  • Creating ActionEvent object for CustomButton in Java

    - by Crystal
    For a hw assignment, we were supposed to create a custom button to get familiar with swing and responding to events. We were also to make this button an event source which confuses me. I have an ArrayList to keep track of listeners that would register to listen to my CustomButton. What I am getting confused on is how to notify the listeners. My teacher hinted at having a notify and overriding actionPerformed which I tried doing, but then I wasn't sure how to create an ActionEvent object looking at the constructor documentation. The source, id, string all confuses me. Any help would be appreciated. Thanks! code: import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class CustomButton { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CustomButtonFrame frame = new CustomButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } public void addActionListener(ActionListener al) { listenerList.add(al); } public void removeActionListener(ActionListener al) { listenerList.remove(al); } public void actionPerformed(ActionEvent e) { System.out.println("Button Clicked!"); } private void notifyListeners() { ActionEvent event = new ActionEvent(CONFUSED HERE!!!!; for (ActionListener action : listenerList) { action.actionPerfomed(event); } } List<ActionListener> listenerList = new ArrayList<ActionListener>(); } class CustomButtonFrame extends JFrame { // constructor for CustomButtonFrame public CustomButtonFrame() { setTitle("Custom Button"); CustomButtonSetup buttonSetup = new CustomButtonSetup(); this.add(buttonSetup); this.pack(); } } class CustomButtonSetup extends JComponent { public CustomButtonSetup() { ButtonAction buttonClicked = new ButtonAction(); this.addMouseListener(buttonClicked); } // because frame includes borders and insets, use this method public Dimension getPreferredSize() { return new Dimension(200, 200); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // first triangle coords int x[] = new int[TRIANGLE_SIDES]; int y[] = new int[TRIANGLE_SIDES]; x[0] = 0; y[0] = 0; x[1] = 200; y[1] = 0; x[2] = 0; y[2] = 200; Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES); // second triangle coords x[0] = 0; y[0] = 200; x[1] = 200; y[1] = 200; x[2] = 200; y[2] = 0; Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES); g2.drawPolygon(firstTriangle); g2.setColor(firstColor); g2.fillPolygon(firstTriangle); g2.drawPolygon(secondTriangle); g2.setColor(secondColor); g2.fillPolygon(secondTriangle); // draw rectangle 10 pixels off border int s1[] = new int[RECT_SIDES]; int s2[] = new int[RECT_SIDES]; s1[0] = 5; s2[0] = 5; s1[1] = 195; s2[1] = 5; s1[2] = 195; s2[2] = 195; s1[3] = 5; s2[3] = 195; Polygon rectangle = new Polygon(s1, s2, RECT_SIDES); g2.drawPolygon(rectangle); g2.setColor(thirdColor); g2.fillPolygon(rectangle); } private class ButtonAction implements MouseListener { public void mousePressed(MouseEvent e) { System.out.println("Click!"); firstColor = Color.GRAY; secondColor = Color.WHITE; repaint(); } public void mouseReleased(MouseEvent e) { System.out.println("Released!"); firstColor = Color.WHITE; secondColor = Color.GRAY; repaint(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} } public static final int TRIANGLE_SIDES = 3; public static final int RECT_SIDES = 4; private Color firstColor = Color.WHITE; private Color secondColor = Color.DARK_GRAY; private Color thirdColor = Color.LIGHT_GRAY; }

    Read the article

  • Java, two JPanel on JFrame - Settings JPanel, StartMenu JPanel [on hold]

    - by Andy Tyurin
    There is my first question and I welcome community! I'm making a simple game and have some problems with Start menu. I have three buttons on my JPanel StartMenu and when I click "Settings" button, new JPanel will be open, but I don't know why buttons from StartMenu JPanel appeared in my Settings JPanel. My "Settings" JPanel has one ugly button "Back" in center and ugly grey background. I made some screens to see a problem. Start Menu JPanel when game launched Settings JPanel when button clicked Settings JPanel when mouse was over settings window There is code of StartMenu class: public class StartMenu extends JPanel { private GameButton startGameButton = new GameButton("Start game"); private GameButton settingsGameButton = new GameButton("Settings"); private GameButton exitGameButton = new GameButton("Exit game"); private Image bgImage = new ImageIcon(getClass().getClassLoader().getResource("ru/andydevs/astraLaserForce/bg.png")).getImage(); private int posX; private int posY; final private int WIDTH=(int)Game.SCREEN_DIMENSION.getWidth()/3; final private int HEIGHT=(int)Game.SCREEN_DIMENSION.getHeight()/2; public StartMenu() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); setSize(new Dimension(WIDTH, HEIGHT)); posX=(int)Game.SCREEN_DIMENSION.getWidth()/2-WIDTH/2; posY=(int)Game.SCREEN_DIMENSION.getHeight()/2-HEIGHT/2; setBounds(posX, posY,WIDTH,HEIGHT); c.ipadx=95; c.ipady=15; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(20,0,0,0); c.gridy=0; add(startGameButton, c); c.gridy=1; c.insets = new Insets(20,0,0,0); System.out.println(settingsGameButton.getWidth()); add(settingsGameButton, c); c.gridy=2; c.insets = new Insets(20,0,0,0); add(exitGameButton, c); settingsGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameOptionsPanel gop = new GameOptionsPanel(); Game.container.add(gop); Game.container.setComponentZOrder(gop, 0); Game.container.revalidate(); Game.container.repaint(); } }); exitGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Main.currentGame.stop(); } }); } public void paintComponent(Graphics g) { g.drawImage(bgImage,0,0,WIDTH,HEIGHT,null); } } There is code of Settings JPanel public class GameOptionsPanel extends GamePanel { private GameButton backButton = new GameButton("Back"); private GameOptionsPanel that; public GameOptionsPanel() { super((int) (Game.SCREEN_DIMENSION.getWidth()/3), (int) (Game.SCREEN_DIMENSION.getHeight()/2), new Color(50,50,50)); that=this; setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill=gbc.HORIZONTAL; add(backButton); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Game.container.remove(that); Game.container.revalidate(); Game.container.repaint(); } }); } } I glad to see some suggestions. Thanks.

    Read the article

  • How to manage a lot of Action Listeners for multiple buttons

    - by Wumbo4Dayz
    I have this Tic Tac Toe game and I thought of this really cool way to draw out the grid of 9 little boxes. I was thinking of putting buttons in each of those boxes. How should I give each button (9 buttons in total) an ActionListener that draws either an X or O? Should they each have their own, or should I do some sort of code that detects turns in this? Could I even do a JButton Array and do some for loops to put 9 buttons. So many possibilities, but which one is the most proper? Code so far: import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Board extends JPanel implements ActionListener{ public Board(){ Timer timer = new Timer(25,this); timer.start(); } @Override protected void paintComponent(Graphics g){ for(int y = 0; y < 3; y++){ for(int x = 0; x < 3; x++){ g.drawRect(x*64, y*64, 64, 64); } } } public void actionPerformed(ActionEvent e){ repaint(); } }

    Read the article

  • JSF index out of bounds exception when submiting a form

    - by selvin
    When I click submit button in a JSF form the following exception occurs. It says an Indexout of bounds exception, but I did not use any ArrayList associated with the code. Is this a bug? what should i do to get rid of this error.. Mojarra: 2.0.2 FCS with primefaces 2.2 JSF: 2.0 NetBeans IDE 6.8 Glassfish Domain V3 Form Code: <p:panel id="jobres" style="min-width: 200px" header="Reservation" widgetVar="jres" closable="true" toggleable="true" > <h:form id="arj" prependId="false" style="width:550px;max-height:400px;overflow:auto;"> <p:tooltip global="true"/> <h:panelGrid columns="2" > <p:panel style="min-width: 220px"> <h:outputLabel value="1.Job type:"/> </p:panel> <h:panelGroup> <h:messages id="aerr"/> <h:selectOneMenu title="Choose a Jobtype" value="#{arjob.jobtype}"> <f:selectItem itemLabel="Sequential" itemValue="sequential"/> <f:selectItem itemLabel="Parallel" itemValue="parallel"/> </h:selectOneMenu> </h:panelGroup> <p:panel> <h:outputLabel value="2.Executable: *"/> </p:panel> <h:panelGroup> <p:fileUpload id="aexeupload" fileUploadListener="#{arjob.chooseListener}" auto="true" update="adlist :erdialog" description="Resource Files"> </p:fileUpload> <br/> <h:panelGroup id="aexelistwrapper"> <p:dataList var="fileList" type="ordered" id="adlist" value="#{arjob.fexelist}"> <p:column> #{fileList}&nbsp; <p:commandLink ajax="true" update="aexelistwrapper" actionListener="#{arjob.removeExe(fileList)}"> <p:graphicImage value="images/closebar.png"/> </p:commandLink> </p:column> </p:dataList> </h:panelGroup> </h:panelGroup> <p:panel> <h:outputLabel value="3.Argument(s):"/> </p:panel> <h:panelGroup> <u style="color:orange"> <i> <p:inplace emptyLabel="Add Arguments" onEditUpdate="aarglist"> <h:inputText title="Enter the arguments" id="aiparg" value="#{arjob.args}"> <f:ajax event="valueChange"/> </h:inputText> <p:commandButton update="aarglistwrapper erdialog" value="add" actionListener="#{arjob.addArg}"/> </p:inplace> </i> </u> </h:panelGroup> <h:panelGroup> </h:panelGroup> <h:panelGroup> <h:panelGrid id="aarglistwrapper"> <p:dataList id="aarglist" type="ordered" var="args" value="#{arjob.arglist}"> <p:column id="col2"> #{args}&nbsp; <p:commandLink ajax="true" update="arj:arglistwrapper" actionListener="#{arjob.removeArgs(args)}"> <p:graphicImage title="remove" value="images/closebar.png"/> </p:commandLink> </p:column> </p:dataList> </h:panelGrid> </h:panelGroup> <p:panel> <h:outputLabel value="4.InputFile(s): *"/> </p:panel> <h:panelGroup> <p:fileUpload id="ainpupload" fileUploadListener="#{arjob.inputChooseListener}" auto="true" update="aipfilelistwrapper :erdialog" description="Resource Files"> </p:fileUpload> <br/> <h:panelGroup id="aipfilelistwrapper"> <p:dataList var="ipfile" type="ordered" id="aipflist" value="#{arjob.finlist}"> <p:column> #{ipfile}&nbsp; <p:commandLink ajax="true" update="aipfilelistwrapper" actionListener="#{arjob.removeInfile(ipfile)}"> <p:graphicImage value="images/closebar.png"/> </p:commandLink> </p:column> </p:dataList> </h:panelGroup> </h:panelGroup> <h:panelGroup> <p:panel > 5)Output File(s): </p:panel> </h:panelGroup> <h:panelGroup> <u style="color:orange"> <i> <p:inplace emptyLabel="Add file name" id="aipexe"> <h:inputText title="Enter the output filenames" id="aexe" value="#{arjob.ofilename}"> <f:ajax event="valueChange"/> </h:inputText> <p:commandButton update="adoutlist :erdialog" value="add" actionListener="#{arjob.addOutfile}"/> </p:inplace> </i> </u> </h:panelGroup> <h:panelGroup> </h:panelGroup> <h:panelGroup> <h:panelGrid id="afilelistwrapper"> <p:dataList id="adoutlist" type="ordered" var="ofile" value="#{arjob.foutlist}"> <p:column id="acol"> #{ofile}&nbsp; <p:commandLink ajax="true" update="afilelistwrapper" actionListener="#{arjob.removeOutfile(ofile)}"> <p:graphicImage value="images/closebar.png"/> </p:commandLink> </p:column> </p:dataList> </h:panelGrid> </h:panelGroup> <p:panel> <h:outputLabel value="6) Operating System"/> </p:panel> <h:panelGroup> <h:selectOneMenu title="Select an OperatingSystem" value="#{arjob.os}"> <f:selectItem itemLabel="CentOS Release 5.2" itemValue="Cent OS 5.2"/> <f:selectItem itemLabel="RHEL Server Release 5" itemValue="RHEL server 5"/> <f:selectItem itemLabel="RHEL Server Release 5.2" itemValue="RHEL server 5.2"/> </h:selectOneMenu> </h:panelGroup> <h:panelGroup> <p:panel> <h:outputLabel value="7) Physical Memory:"/> </p:panel> </h:panelGroup> <h:panelGroup> <p:spinner min="0" style="width: 100px" stepFactor="10" value="#{arjob.mem}"> </p:spinner>(MB) </h:panelGroup> <h:panelGroup> <p:panel> <h:outputLabel value="8) Disk Space:"/> </p:panel> </h:panelGroup> <h:panelGroup> <p:spinner min="0" style="width: 100px" stepFactor="10" value="#{arjob.diskspace}"> </p:spinner>(MB) </h:panelGroup> <h:panelGroup> <p:panel> <h:outputLabel value="9) CPU Mhz:"/> </p:panel> </h:panelGroup> <h:panelGroup> <p:spinner min="0" style="width: 100px" stepFactor="10" value="#{arjob.cpumhz}"> </p:spinner>(Mhz) </h:panelGroup> <p:panel> <h:outputLabel value="10) Start Time:"/> </p:panel> <h:panelGroup> <p:inputMask title="(YYYY-MM-DD HH:MM:SS)" mask="9999-99-99 99:99:99" value="#{arjob.startt}"> </p:inputMask> </h:panelGroup> <p:panel> <h:outputLabel value="11) End Time:"/> </p:panel> <h:panelGroup> <p:inputMask title="(YYYY-MM-DD HH:MM:SS)" mask="9999-99-99 99:99:99" value="#{arjob.endt}"> <p:ajax event="valueChange"/> </p:inputMask> </h:panelGroup> <p:panel> <h:outputLabel value="12) LRMS type"/> </p:panel> <h:panelGroup> <h:selectOneMenu value="#{arjob.lrms}"> <f:selectItem itemLabel="PBS" itemValue="PBS"/> <f:selectItem itemLabel="SGE" itemValue="SGE"/> </h:selectOneMenu> </h:panelGroup> <h:panelGroup> <p:panel> <h:outputLabel value="13)Number of Nodes: *"/> </p:panel> </h:panelGroup> <h:panelGroup> <h:panelGroup> <p:spinner style="width: 100px" min="1" max="100" value="#{arjob.numnodes}"> </p:spinner> </h:panelGroup> </h:panelGroup> <h:panelGroup> </h:panelGroup> <h:panelGroup> <p:commandButton ajax="false" value="Submit" action="#{arjob.jobSubmitAction}"/> </h:panelGroup> </h:panelGrid> </h:form> <p:draggable for="jobres" handle=".ui-panel-titlebar"/> </p:panel> Exception: SEVERE: javax.faces.FacesException: Unexpected error restoring state for component with id j_idt7. Cause: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0. at com.sun.faces.application.view.StateManagementStrategyImpl$2.visit(StateManagementStrategyImpl.java:239) at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:147) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1446) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1457) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1457) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1457) at com.sun.faces.application.view.StateManagementStrategyImpl.restoreView(StateManagementStrategyImpl.java:223) at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:177) at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:131) at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:430) at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:143) at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:288) at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:199) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:110) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.RangeCheck(ArrayList.java:547) at java.util.ArrayList.get(ArrayList.java:322) at javax.faces.component.AttachedObjectListHolder.restoreState(AttachedObjectListHolder.java:161) at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1427) at com.sun.faces.application.view.StateManagementStrategyImpl$2.visit(StateManagementStrategyImpl.java:231) ... 45 more

    Read the article

  • Error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException [migrated]

    - by user134212
    I'm new here. I'm learning how to program on java and I have a problem with my code. I really have no clue why my code is not working. I think my mistake may be here, but I'm not quite sure. m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); My Complete code import java.awt.*; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.Border; import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*; public class Practica2 { private int opcion,ren2,col2; private JFrame ventana,ventanaPrintMatriz; private JPanel panel,panel2; private Border borderRed2,borderBlue2,borderGreen2,borderGreen4; private Color red,green,blue,white,black; private Font Verdana14,ArialBlack18; private JLabel labelTitulo; public JButton btSalir,btSumar,btRestar,btMultiplica,btTranspuesta,btCrear; private ImageIcon suma,resta,multi,crear,salir,trans; private boolean ventanaAbierta = false; private static ValidacionesMatrices valida; private static Operaciones operacion; private static Matriz m1,m2,m3; private static ImprimirMatriz printMat; public Practica2() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Operaciones con Matrices"); ventana.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Sale del programa System.exit(0); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(150,150,300,380); //ventana.setBounds(0,0,650,650); } public void inicializarComponentes() { panel2 = new JPanel(); panel2.setLayout(null); labelTitulo = new JLabel("Practica #2"); suma = new ImageIcon("suma1.png"); resta = new ImageIcon("resta1.png"); multi = new ImageIcon("multi1.png"); trans = new ImageIcon("trans2.png"); crear = new ImageIcon("crear1.png"); salir = new ImageIcon("salir1.png"); btTranspuesta = new JButton("Transpuesta",trans); btMultiplica = new JButton("Multiplica",multi); btRestar = new JButton("Restar",resta); btSumar = new JButton("Sumar",suma); btCrear = new JButton("Crear",crear); btSalir = new JButton("Salir",salir); //Tipo de letra ArialBlack18 = new Font("Arial Black",Font.BOLD,18); //Color green = new Color(0,255,0); //Formato labelTitulo labelTitulo.setBounds(80,-60,200,150); labelTitulo.setFont(ArialBlack18); labelTitulo.setForeground(blue); labelTitulo.setVisible(true); //Formato de CrearMatriz btCrear.setBounds(80,50,130,30); btCrear.setToolTipText("Crea una matriz"); //Formato de Muliplica btMultiplica.setBounds(80,100,130,30); btMultiplica.setToolTipText("Mat[A] * Mat[B]"); //Formato de botonRestar btRestar.setBounds(80,150,130,30); btRestar.setToolTipText("Mat[A] - Mat[B]"); //Formato del botonSumar btSumar.setBounds(80,200,130,30); btSumar.setToolTipText("Mat[A] + Mat[B]"); //Formato de Transpuesta btTranspuesta.setBounds(80,250,130,30); btTranspuesta.setToolTipText("Mat[A]^-1"); //Formato del botonSalir btSalir.setBounds(80,300,130,30); //Agregando componentes al panel1 panel2.add(labelTitulo); panel2.add(btMultiplica); panel2.add(btCrear); panel2.add(btRestar); panel2.add(btSumar); panel2.add(btSalir); panel2.add(btTranspuesta); //Formato panel2 panel2.setBackground(green); panel2.setVisible(true); panel2.setBounds(0,0,300,380); //Argregamos componentes al panelPrincipal= panel.add(panel2); //BotonCrear btCrear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) //throws IOException { if(ventanaAbierta==false) { ventanaAbierta=true; new CrearMatriz(); } else { JOptionPane.showMessageDialog(null,"Ya se crearon las Matrices"); } } }); m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); //BotonSalir btSalir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); panel.setVisible(true); panel.setBounds(0,0,350,380); } class VentanaMatriz { private JFrame ventana; private JPanel panel; private JTextArea textArea1,textArea2; private JLabel mat1,mat2; private JTextField textField1; public VentanaMatriz() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Creacion de Matrices"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { ventana.dispose(); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(200,100,850,420); } public void inicializarComponentes() { //Colores black = new Color(0,0,0); white = new Color(255,255,255); blue = new Color(0,0,255); green = new Color(0,255,0); red = new Color(255,0,0); //Tipo de letra Verdana14 = new Font("Verdana",Font.BOLD,14); //Tipos de borde borderRed2 = BorderFactory.createLineBorder(red,2); borderBlue2 = BorderFactory.createLineBorder(blue,2); borderGreen2 = BorderFactory.createLineBorder(green,2); borderGreen4 = BorderFactory.createLineBorder(green,4); //Agregando componentes al panel1 panel.add(mat1); panel.add(textArea1); panel.add(mat2); panel.add(textArea2); //Formato panel2 panel.setBackground(blue); panel.setVisible(true); panel.setBounds(0,0,850,420); } } class CrearMatriz { public int col1,re1,ren2,col2; public Matriz m1,m2,m3; public CrearMatriz() { int col1,ren1,ren2,col2; ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz A: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz A: ")); final Matriz m1= new Matriz(ren2,col2); ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz B: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz B: ")); final Matriz m2= new Matriz(ren2,col2); m3 = new Matriz(ren2,col2); m1.llenarMatriz(); m2.llenarMatriz(); m1.printMat(); m2.printMat(); } public void SUMA(Matriz m1,Matriz m2) { Matriz m3; if(ventanaAbierta==false) { m3 = new Matriz(ren2,col2); if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } } } public void RESTA() { } //btSumar = new JButton("Sumar",suma); //BotonSumar //Mostrar matriz 1 y 2 // System.out.println("\n\n\nMatriz 1="); // m1.imprimeMatriz(); // System.out.println("\nMatriz 2="); //Poner en botones /* if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } if(valida.validaSumayResta(m1,m2)) { m3=operacion.restaMat(m1,m2); JOptionPane.showMessageDialog(null,"La resta es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la resta"); } if(valida.validaMultiplicacion(m1,m2)){ m3=operacion.multiplicaMat(m1,m2); JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la multiplicacion"); } JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m1=operacion.transpuesta(m1); m2=operacion.transpuesta(m2); */ } class Matriz { public JTextField matriz; //public JTextArea texto; private JFrame ventanaPrintMatriz; private JPanel panel2; int ren; int col; int pos[][]; public Matriz(int ren1, int col1) { ren = ren1; col = col1; pos = new int [ren][col];/*una matriz de enteros de renglon por columan*/ } public void llenarMatriz() { for(int i=0;i<ren;i++) for(int j=0;j<col;j++) pos[i][j]=(int) (Math.random()*10);/*la posicion i y j crea un entero random*/ } /*vuelve a recorrer los espacio de i y j*/ } //Esta clase era un metodo de CrearMatriz class ImprimirMatriz { public void ImprimirMatriz() { panel2 = new JPanel(); panel2.setLayout(null); ventanaPrintMatriz = new JFrame("Matriz"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Practica2.ventanaAbierta=false; ventana.dispose(); } }); int i,j; int x=0,y=0; borderRed2 = BorderFactory.createLineBorder(red,2); white = new Color(255,255,255); red = new Color(255,0,0); black = new Color(0,0,0); blue = new Color(0,0,255); for(i=0;i<ren;i++) { for(j=0;j<col;j++) { matriz = new JTextField(" "+pos[i][j]); matriz.setBorder(borderRed2); matriz.setForeground(white); matriz.setBounds(x+25,y+25,25,25); matriz.setBackground(black); matriz.setEditable(false); matriz.setVisible(true); //Se incrementa la coordenada en X //para el siguiente Textfield no se encime x=x+35; //Agregamos el textField al panel panel2.add(matriz); } //Regreso las cordenadas de X a 0 para que el //siguiente renglon empieze en donde mismo x=0; //Incremento las coordenada Y para que se brinque //de linea y=y+35; } //Formato panel2 panel2.setBounds(150,150,350,380); panel2.setBackground(blue); //panel2.setEditable(false); panel2.setVisible(true); //Formato de Ventana ventanaPrintMatriz.setContentPane(panel2); ventanaPrintMatriz.setBounds(150,150,350,380); ventanaPrintMatriz.setResizable(false); ventanaPrintMatriz.setVisible(true); } } class Operaciones { public Matriz sumaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]+m2.pos[i][j]; return m3; } public Matriz restaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]-m2.pos[i][j]; return m3; } public Matriz multiplicaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m2.col); for(int i=0;i<m1.ren;i++) for(int j=0;j<m2.col;j++) { m3.pos[i][j]=0; for(int k=0;k<m1.col;k++) m3.pos[i][j]+=(m1.pos[i][k]*m2.pos[k][j]); } return m3; } public Matriz transpuesta(Matriz m1) { Matriz m3=new Matriz(m1.col,m1.ren); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[j][i]; return m3; } } class ValidacionesMatrices { public boolean validaSumayResta(Matriz m1, Matriz m2) { if((m1.ren==m2.ren) && (m1.col==m2.col)) return true; else return false; } public boolean validaMultiplicacion(Matriz m1, Matriz m2) { if(((m1.ren==m2.ren) && (m1.col==m2.col)) || (m1.col==m2.ren)) return true; else return false; } } public static void main(String[] args) { Practica2 practica2 = new Practica2(); practica2.inicializarComponentes(); } } Exc

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >