RISK GUI component higherarchies

I have also posted the same question in the Applet section. Sorry for the repost but I didn't know where to post this question. Thanks for your time!
I am trying to make a game of Risk (The world domination board game). My design has a gamePanel that extends JPanel and has children attackPanel and placePanel. The idea is that when the user clicks the radio buttons in a seperate panel (by the way this panel works fine and the buttons can be clicked) the gamePanel intance named board will polymophically change from type gamePanel, attackPanel, or placePanel to, depeding on the button clicked, placePanel or attackPanel. To debug I tried having gamePanel have its paintComponent class paint a green square, the attackPanel paint a red square, and the placePanel print a white square. I don't have the code with me now, but the radio button's listener method looked something like this in psedo-code.
//class variables
gamePanel board;
attackPanel aBoard;
placePanel pBoard;
//Method name parameters etc...
if (attack mode was clicked)
board=aBoard;
if(place mode was clicked)
board=pBoard;
repaint()
At one point i also had board.repaint() but that just made the whole applet redo its self in the board component. At another time I had the green square displaying (board of type gameBoard) and clicking wouldn't change that, but now I have only a gray background and when I click the radio buttons nothin changes at all. Help would be greatly appriciated, thanks!

Sorry to spam my own thread, but I am at school where my code is now and can post it.
public class gamePanel extends JPanel
//private variables etc...
public gamePanel()
public void paintComponent (Graphics page)
super.paintComponent(page);
page.setColor(Color.green);
page.fillRect(100,100,500,500);
//other methods not shown
public class placePanel extends gamePanel
public placePanel()
public void paintComponent (Graphics page)
super.paintComponent(page);
page.setColor(Color.white);
page.fillRect(100,100, 500, 500);
public class attackPanel extends gamePanel
public attackPanel()
public void paintComponent (Graphics page)
super.paintComponent(page);
page.setColor(Color.red);
page.fillRect(100,100, 500, 500);
//This is the driver applet that uses all the components. This is a code segment at the end of the class
board = new gamePanel ();
aBoard = new attackPanel();
pBoard = new placePanel();
appletPanel = new JPanel();
appletPanel.setLayout(new BoxLayout (appletPanel, BoxLayout.Y_AXIS));
appletPanel.add (tools);
appletPanel.add (board);
getContentPane().add (appletPanel);
//Subclass that listens to the radio buttons in the tools Component
// Determines which button was pushed, and either changes the mode
// or ends the turn of the player.
public void actionPerformed (ActionEvent event)
//buttons being pushed
if (event.getSource()==attackMode)
board=aBoard;
else if (event.getSource()==addUnitsMode)
board=pBoard;
else if (event.getSource()==done)
board.nextTurn();
board.repaint();
This will display a green rectangle, but clicking the radio buttons does nothing. Is the repaint()method in the wrong place? Please help me understand why the polymorphism isn't making the different color rectangles display when I click different buttons!?!?

Similar Messages

  • A sort of KeyListener without a GUI Component?

    a sort of KeyListener without a GUI Component? ( or any trick that will do)?
    please be patient with my question
    I can't express myself very well but it's very important.
    Please help me I need an example how to implement
    a way to detect some combination of keystrokes in java without
    any GUI ( without AWT or Swing frames ...)
    just the console (DOS or Linux shell window) or with a minimzed
    java frame (awt or swing...) you know, MINIMIZED= not in focus.
    in other words if the user press ctrl + alt +shift ...or some
    other combination... ANYTIME ,and the java program is running in the
    background, is there a way to detect that,
    ... my problem if I use a frame (AWT or SWING) the windows must
    be in focus and NOT MINIMIZED..
    if I use
    someObject.addKeylistener(someComponent);
    then the "someComponent" must be in focus, am I right?
    What I'm coding is a program that if you highlight ANY text in
    ANY OS window, a java window (frame) should pop up and match the
    selected text in a dictionary file and brings me the meaning
    ( or a person's phone number , or
    a book author ...etc.)
    MY CHALLENGE IS WITHOUT PRESSING (Ctrl+C) to copy and paste
    ...etc. and WITHOUT MONITORING THE OS's CLIPBOARD ...I just want to
    have the feature that the user simply highlight a text in ANY
    window anywhere then press Ctrl+shift or some other combination,
    then MY JAVA PROGRAM IS TRIGGERED and it should EMULATE SOME
    KEYSTROKES OF Ctrl+C and then paste the clipboard
    somewhere in my program...with all that AUTOMATION BEING in the background.
    remember that my whole program ALL THE TIME MUST BE MINIMIZED AND
    NOT IN FOCUS
    or just running in the background (using javaw)..
    is there any trick ? pleeeeeeze!!!
    i'm not trying to write a sort of the spying so-called "key-logger"
    purely in java but it's a very similar challenge.
    please reply if you have questions
    I you could please answer me , then guys this would be very
    valuable technique that I need urgently. Thanks!

    DO NOT CROSS POST especially since this has nothing to do with game development at all. I can understand if it was in Java programming and New to Java but even then pick a forum and post it to that one and that one only.

  • Using my new GUI component in an applet :Help!!!

    I am seeking help for the following
    Define class MyColorChooser as a new component so it can be reused in other applications or applets. We want to use the new GUI component as part of an applet that displays the current Color value.
    The following is the code of MyColorChooser class
    * a) We define a class called MyColorChooser that provides three JSlider
    * objects and three JTextField objects. Each JSlider represents the values
    * from 0 to 255 for the red, green and blue parts of a color.
    * We use wred, green and blue values as the arguments to the Color contructeur
    * to create a new Color object.
    * We display the current value of each JSlider in the corresponding JTextField.
    * When the user changes the value of the JSlider, the JTextField(s) should be changed
    * accordingly as weel as the current color.
    * b)Define class MyColorChooser so it can be reused in other applications or applets.
    * Use your new GUI component as part of an applet that displays the current
    * Color value.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    public class MyChooserColor extends JFrame{
         private int red, green, blue;  // color shade for red, green and blue
         private static Color myColor;  // color resultant from red, green and blue shades
         private JSlider mySlider [];      
         private JTextField textField [];
    // Panels for sliders, textfields and button components
         private JPanel mySliderPanel, textFieldPanel, buttonPanel;
    // sublcass objet of JPanel for drawing purposes
         private CustomPanel myPanel;
         private JButton okButton, exitButton;
         public MyChooserColor ()     
              super( "HOME MADE COLOR COMPONENT; composition of RGB values " );
    //       setting properties of the mySlider array and registering the events
              mySlider = new JSlider [3];
              ChangeHandler handler = new ChangeHandler();
              for (int i = 0; i < mySlider.length; i++)
              {     mySlider[i] = new JSlider( SwingConstants.HORIZONTAL,
                               0, 255, 255 );
                   mySlider.setMajorTickSpacing( 10 );
                   mySlider[i].setPaintTicks( true );
    //      register events for mySlider[i]
                   mySlider[i].addChangeListener( handler);                     
    //      setting properties of the textField array           
              textField = new JTextField [3];          
              for (int i = 0; i < textField.length; i++)
              {     textField[i] = new JTextField("100.00%", 5 );
                   textField[i].setEditable(false);
                   textField[i].setBackground(Color.white);
    // initial Background color of each slider and foreground for each textfield
    // accordingly to its current color shade
              mySlider[0].setBackground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );
              textField[0].setForeground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );           
              mySlider[1].setBackground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              textField[1].setForeground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              mySlider[2].setBackground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
              textField[2].setForeground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
    // initialize myColor to white
              myColor = Color.WHITE;
    // instanciate myPanel for drawing purposes          
              myPanel = new CustomPanel();
              myPanel.setBackground(myColor);
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
    //      instanciate exitButton with its inanymous class
    //      to handle its related events           
              exitButton = new JButton("Exit");
              exitButton.setToolTipText("Exit the application");
              exitButton.setMnemonic('x');
              exitButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed (ActionEvent e)
                             {     System.exit( 0 );     
    // define the contentPane
              Container c = getContentPane();
              c.setLayout( new BorderLayout() );
    //     panel as container for sliders
              mySliderPanel = new JPanel(new BorderLayout());
    //      panel as container for textFields           
              textFieldPanel = new JPanel(new FlowLayout());
    //      panel as container for Jbuttons components           
              buttonPanel = new JPanel ();
              buttonPanel.setLayout( new BoxLayout( buttonPanel, BoxLayout.Y_AXIS ) );
    //add the Jbutton components to buttonPanel           
              buttonPanel.add(okButton);
              buttonPanel.add(exitButton);
    //     add the mySlider components to mySliderPanel
              mySliderPanel.add(mySlider[0], BorderLayout.NORTH);
              mySliderPanel.add(mySlider[1], BorderLayout.CENTER);
              mySliderPanel.add(mySlider[2], BorderLayout.SOUTH);
    //add the textField components to textFieldPanel     
              for (int i = 0; i < textField.length; i++){
                   textFieldPanel.add(textField[i]);
    // add the panels to the container c          
              c.add( mySliderPanel, BorderLayout.NORTH );
              c.add( buttonPanel, BorderLayout.WEST);
              c.add( textFieldPanel, BorderLayout.SOUTH);
              c.add( myPanel, BorderLayout.CENTER );
              setSize(500, 300);          
              show();               
    //     inner class for mySlider events handling
         private class ChangeHandler implements ChangeListener {          
              public void stateChanged( ChangeEvent e )
    // start by collecting the current color shade
    // for red , forgreen and for blue               
                   setRedColor(mySlider[0].getValue());
                   setGreenColor(mySlider[1].getValue());
                   setBlueColor(mySlider[2].getValue());
    //The textcolor in myPanel (subclass of JPanel for drawing purposes)
                   myPanel.setMyTextColor( ( 255 - getRedColor() ),
                             ( 255 - getGreenColor() ), ( 255 - getBlueColor() ) );
    //call to repaint() occurs here
                   myPanel.setThumbSlider1( getRedColor() );
                   myPanel.setThumbSlider2( getGreenColor() );
                   myPanel.setThumbSlider3( getBlueColor() );
    // display color value in the textFields (%)
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   for (int i = 0; i < textField.length; i++){
                        textField[i].setText("" + twoDigits.format(
                                  100.0* mySlider[i].getValue()/255) + " %") ;
    // seting the textcolor for each textField
    // and the background color for each slider               
                   textField[0].setForeground(
                             new Color ( getRedColor(), 0, 0 ) );
                   mySlider[0].setBackground(
                             new Color ( getRedColor(), 0, 0) );
                   textField[1].setForeground(
                             new Color ( 0, getGreenColor() , 0 ) );
                   mySlider[1].setBackground(
                             new Color ( 0, getGreenColor(), 0) );
                   textField[2].setForeground(
                             new Color ( 0, 0, getBlueColor() ) );
                   mySlider[2].setBackground(
                             new Color ( 0, 0, getBlueColor() ) );
    // color of myPanel background
                   myColor = new Color (getRedColor(),
                             getGreenColor(), getBlueColor());
                   myPanel.setBackground(myColor);               
    // set methods to set the basic color shade
         private void setRedColor (int r){
              red = ( (r >= 0 && r <= 255) ? r : 255 );
         private void setGreenColor (int g){
              green = ( (g >= 0 && g <= 255) ? g : 255 );
         private void setBlueColor (int b){
              blue = ( (b >= 0 && b <= 255) ? b : 255 );
    // get methods (return the basic color shade)
         private int getRedColor (){
              return red ;
         private int getGreenColor (){
              return green;
         private int getBlueColor (){
              return blue;
         public static Color getMyColor (){
              return myColor;
    // main method                
         public static void main (String args []){
              MyChooserColor app = new MyChooserColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {     System.exit( 0 );
    // inner class CustomPanel for drawing purposes
         private class CustomPanel extends JPanel {
              private int thumbSlider1 = 255;
              private int thumbSlider2 = 255;
              private int thumbSlider3 = 255;
              private Color myTextColor;
              public void paintComponent( Graphics g )
                   super.paintComponent( g );
                   g.setColor(myTextColor);
                   g.setFont( new Font( "Serif", Font.TRUETYPE_FONT, 12 ) );
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   g.drawString( "The RGB values of the current color are : "
                             + "( "     + thumbSlider1 + " , " + thumbSlider2 + " , "
                             + thumbSlider3 + " )", 10, 40);
                   g.drawString( "The current background color is composed by " +
                             "the folllowing RGB colors " , 10, 60);
                   g.drawString( "Percentage of RED from slider1 : "
                        + twoDigits.format(thumbSlider1*100.0/255), 10, 80 );
                   g.drawString( "Percentage of GREEN from slider2 : "
                        + twoDigits.format(thumbSlider2*100.0/255), 10, 100 );
                   g.drawString( "Percentage of BLUE from slider3 : "
                        + twoDigits.format(thumbSlider3*100.0/255), 10, 120 );
    // call to repaint occurs here     
              public void setThumbSlider1(int th){
                   thumbSlider1 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider2(int th){
                   thumbSlider2 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider3(int th){
                   thumbSlider3 = (th >= 0 ? th: 255 );
                   repaint();
              public void setMyTextColor(int r, int g, int b){
                   myTextColor = new Color(r, g, b);
                   repaint();
    //The following method is used by layout managers
              public Dimension getPreferredSize()
              {     return new Dimension( 150, 100 );
    The following is the code of application that tests the component
    //Application used to demonstrating
    // the homemade GUI MyChooserColor component
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ShowMyColor extends JFrame {
         private JButton changeColor;
         private Color color = Color.lightGray;
         private Container c;
         MyChooserColor colorComponent;
         public ShowMyColor()
         {     super( "Using MyChooserColor" );
              c = getContentPane();
              c.setLayout( new FlowLayout() );
              changeColor = new JButton( "Change Color" );
              changeColor.addActionListener(
                        new ActionListener() {
                             public void actionPerformed( ActionEvent e )
                             {     colorComponent = new MyChooserColor ();
                                  colorComponent.show();
                                  color = MyChooserColor.getMyColor();
                                  if ( color == null )
                                       color = Color.lightGray;
                                  c.setBackground( color );
                                  c.repaint();
              c.add( changeColor );
              setSize( 400, 130 );
              show();
         public static void main( String args[] )
         {     ShowMyColor app = new ShowMyColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {  System.exit( 0 );

    Yes, I want help for the missing code to add in actionPerformed method below. As a result, when you confirm the selected color (clicking the OK button), it will be transferred to a variable color of class ShowMyColor.
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
              );

  • Updating a GUI component from a runnable class that doesn't know that GUI

    Hi. I have a problem that I think isn't solvable in an elegant way, but I'd like to get confirmation before I do it the dirty way.
    My application allows the user to save (and load) his work in sessions files. I implemented this by a serializable class "Session" that basically stores all the information that the user created or the settings he made in its member variables.
    Now, I obviously want the session files created by this to be as small as possible and therefore I made sure that no GUI components are stored in this class.
    When the user has made all his settings, he can basically "run" his project, which may last for a long time (minutes, hours or days, depending on what the user wants to do....). Therefore I need to update the GUI with information on the progress/outcome of the running project. This is not just a matter of updating one single GUI component, but of a dynamic number of different internal frames and panels. So I'd need a reference to a GUI component that knows all these subcomponents to run a method that does the update work.
    How do I do that? I cannot pass the reference to that component through the method's argument that "runs" the project, because that needs to be a seperate thread, meaning that the method is just the run() method of that thread which has no arguments (which I cannot modify if I'm not mistaken).
    So the only thing I can think of is passing the reference through the constructor of the runnable class (which in turn must be stored in the session because it contains critical information on the user's work). As a result, all components that need to be incorporated in that updating process would be part of the session and go into the exported file, which is exactly what I wanted to avoid.
    I hope this description makes sense...
    Thanks in advance!

    Thanks for the quick answer! Though to be honest I am not sure how it relates to my question. Which is probably my fault rather than yours :-)
    But sometimes all it takes me to solve my problem is posting it to a forum and reading it through again :)
    Now I wrote a seperate class "Runner" that extends thread and has the gui components as members (passed through its constructor). I create and start() that object in the run method of the original runnable class (which isn't runnable anymore) so I can pass the gui component reference through that run method's argument.
    Not sure if this is elegant, but at least it allows me to avoid saving gui components to the session file :-)
    I am realizing that probably this post shouldn't have gone into the swing forum...

  • Accessing a gui component directly via getSource()

    Hi,
    to access a gui component I can access it by getting its object variable and casting it to its class type, e.g.:
    public class Tab02 extends JFrame {
         JTable tab = new JTable (rows, head);
         JTextField txt = new JTextField ("dimensions");
         JTree tree = new JTree(node.getRoot());
    class DragDropNode implements TreeSelectionListener, MouseMotionListener, MouseListener {
    public void mouseDragged (MouseEvent me ) {
         Cursor dragcurs = new Cursor(13);
    // me.getSource().setCursor (mdragcurs) does not work as getSource delivers an object type
         JTree tmp = (JTree)me.getSource();
    // me.getSource().setCursor (mdragcurs)
         tmp.setCursor (mdragcurs);     // as me.getSource().setCursor (mdragcurs)
         JTable tmp = (JTable )me.getSource();
         tmp.setCursor (mdragcurs);
    How can I cast the object automatically to the genuine type?
    Is there a method that returns the type and I can use this method to cast me.getSource()?
    Thanks

    Navigate to the folder enclosing it and enter Library in the Go to Folder command.
    (70632)

  • What is this gui component?

    HI all, I'm writing a program and I wish to use a gui component but I don't know what it is called and I was wondering if any of you could help.
    Its kind of like a text area but the text is separated into columns and each of the columns have headings. Each of the headings can be extended to show more of the text. It's like in microsoft windows when you view files showing all their detail and you get the headings name, size, date created etc.
    Any help on this matter would be greatly appreciated.
    Thanks

    It's not a jTable as that is more like a spreadsheet, it's similar but the edges of the cells aren't visible in what i'm talking about. and also what i'm after has 'tabs' at the top with headings in. If anyone uses a peer to peer file sharing application, its like what the results of a search are displayed in.
    Thanks for the help but if anyone has any more ideas they are very welcome

  • Calling a GUI component form jbase program

    Hello all,
    I have created a GUI component in Java. When I run it form DOS prompt its works fine,
    but when I call it form a Jbase subroutine the GUI is never displayed....the component runs in the background but for some reason its not visible.....plz help....
    Ankit.

    I am facing the same problem It calls the AWT but doesnt display it. Please help Thanks
    Divesh

  • Help - Bean Binding an SQL join to a gui component(jtable) in Netbeans?

    Good afternoon. I'd like to ask if there is a way to data bind an SQL Join from 2 or more tables to a
    GUI component(Jtable) in Netbeans. All the tutorials show is how to bind all the fields of 1 database table
    to the component. Under the BIND/ELements option the IMPORT DATA TO FORM menu only allows
    you to choose 1 among the database tables from a selected database.
    Is there a way to configure an SQL query and attach it to the component?
    Thanks.

    This is not a Swing problem. Try a NetBeans forum.

  • Trying to create Netbeans Swing/GUI component

    Hello,
    I'm trying to create a GUI component from the following code. The main idea is to create a component consisting of a checkbox and a panel. The panel can contain several other swing components. By checking or unchecking the checkbox I want all by components in the panel to be enabled or disabled.
    The important thing is that this component should work in the Netbeans GUI designer. I'm using Netbeans 5.5.
    My problem is the following:
    When adding my swing component to the Netbeans swing component palette and dragging onto a new form, I cannot assign other components to the main panel of my component. Even if I use the Inspector tree to drag components to be children of my component, the mouse icon shows a denying icon.
    If I add swing components programmatically, it works.
    Can somebody give me an advice what I should change in my code to make it work with the Netbeans GUI designer?
    Below you can find the current code of my standalone component. It includes a main() method so one can give it a try.
    Many thanks in advance!
    package test.swing;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class JEnabler extends JPanel {
        private JCheckBox checkEnabler = new JCheckBox();
        private JPanel contentPane = new JPanel();
        public JEnabler() {
            super.setLayout(new BorderLayout());
            checkEnabler.setSelected(true);
            checkEnabler.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            checkEnabler.setMargin(new Insets(0, 0, 0, 0));
            checkEnabler.setVerticalAlignment(SwingConstants.TOP);
            checkEnabler.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    checkEnablerActionPerformed(evt);
            super.addImpl(checkEnabler, BorderLayout.WEST, -1);
            super.addImpl(contentPane, BorderLayout.CENTER, -1);
        private void checkEnablerActionPerformed(ActionEvent evt) {
            Component[] list = contentPane.getComponents();
            for (int i=0; i<list.length; i++)
                list.setEnabled(checkEnabler.isSelected());
    protected void addImpl(Component comp, Object constraints, int index) {
    contentPane.add(comp, constraints, index);
    public LayoutManager getLayout() {
    return contentPane.getLayout();
    public void setLayout(LayoutManager mgr) {
    if (contentPane!=null)
    contentPane.setLayout(mgr);
    public void remove(Component comp) {
    contentPane.remove(comp);
    public void remove(int index) {
    contentPane.remove(index);
    public void removeAll() {
    contentPane.removeAll();
    public static void main(String args[]) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JEnabler enabler = new JEnabler();
    JTextField tf = new JTextField("Test");
    enabler.add(tf);
    JButton test = new JButton("Click");
    enabler.add(test);
    frame.getContentPane().add(enabler);
    frame.pack();
    frame.setVisible(true);

    Can anyone tell me what I am missing?
    public void paintComponents(Graphics g)you're not 'missing' anything, in fact you've gained an 's'

  • How to get change a GUI component from another class?

    Hi there,
    I'm currently trying to change a GUI component in my 'Application' class from my 'Dice' class.
    So the Application class sets up some GUI including a JLabel that initially displays "Change".
    The 'Dice' class contains the ActionPerformed() method for when the 'Change' button (made from Application class) is clicked.
    And it returns an 'int' between 1 and 6.
    Now I want to set this number back int he JLabel from the Application class.
    APPLICATION CLASS
    import javax.swing.*;
    import java.awt.*;
    import java.util.Random;
    import java.awt.event.*;
    public class Application extends JFrame implements ActionListener{
         public JPanel rollDicePanel = new JPanel();
         public JLabel dice = new JLabel("Loser");
         public Container contentPane = getContentPane();
         public JButton button = new JButton("Change");
         public Dice diceClass = new Dice();
         public Application() {}
         public static void main(String[] args)
              Application application = new Application();
              application.addGUIComponents();
         public void addGUIComponents()
              contentPane.setLayout(new BorderLayout());
              rollDicePanel.add(dice);
            button.addActionListener(diceClass);
            contentPane.add(rollDicePanel, BorderLayout.SOUTH);
            contentPane.add(button,BorderLayout.NORTH);
              this.setSize(460, 655);
              this.setVisible(true);
              this.setResizable(false);
         public void changeDice()
              dice.setText("Hello");
         public void actionPerformed(ActionEvent e) {}
    }DICE
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Dice implements ActionListener
         public Dice() {}
         public void actionPerformed(ActionEvent e)
              //super.actionPerformed(e);
              String event = e.getActionCommand();
              if(event.equals("Change"))
                   System.out.println("Will be about to change the 'dice' label");
                   Application application = new Application();
                   application.dice.setText("Hello");
    }

    It's all about references, baby. The Dice object needs a way to communicate with the Application object, and so Dice needs a reference to Application. There are many ways to pass this. In my example I pass the application object directly to Dice, but a better way would use interfaces and some indirection. Look up the Observer pattern for a better way to do this that scales much better than my brute-force approach.
    import javax.swing.*;
    import java.awt.*;
    public class Application extends JFrame // *** implements ActionListener
        // *** make all of these fields private ***
        private JPanel rollDicePanel = new JPanel();
        private JLabel dice = new JLabel("Loser");
        private Container contentPane = getContentPane();
        private JButton button = new JButton("Change");
        // *** pass a reference to your application ("this")
        // *** to your Dice object:
        private Dice diceClass = new Dice(this);
        public Application()
        public static void main(String[] args)
            Application application = new Application();
            application.addGUIComponents();
        public void addGUIComponents()
            contentPane.setLayout(new BorderLayout());
            rollDicePanel.add(dice);
            button.addActionListener(diceClass);
            contentPane.add(rollDicePanel, BorderLayout.SOUTH);
            contentPane.add(button, BorderLayout.NORTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setPreferredSize(new Dimension(460, 655));
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
            setResizable(false);
        // *** I'm not sure what this is supposed to be doing, so I commented it out.
        //public void changeDice()
            //dice.setText("Hello");
        // *** ditto.  I strongly dislike making a GUI class implement ActionListeenr
        //public void actionPerformed(ActionEvent e)
        // *** here's the public method that the Dice object calls
        public void setTextDiceLabel(String text)
            dice.setText(text);
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Dice implements ActionListener
        // *** have a variable that holds a reference to your application object
        private Application application;
        private boolean hello = true;
        public Dice(Application application)
            // *** get that reference via a constructor parameter (one way to do this)
            this.application = application;
        public void actionPerformed(ActionEvent e)
            String event = e.getActionCommand();
            if (event.equals("Change"))
                System.out.println("Will be about to change the 'dice' label");
                if (hello)
                    // *** call the application's public method
                    application.setTextDiceLabel("Hello");
                else
                    application.setTextDiceLabel("Goodbye");
                hello = !hello;
                //Application application = new Application();
                //application.dice.setText("Hello");
    }

  • GUI component for horizontal multi-record blocks?

    Hi,
    is there a GUI component in ADF to show multi-record blocks (e.g. with af:inputText, af:inputListOfVAlues) which repeats the record not vertical but horizontal?
    regards
    Peter

    Hello Shay,
    With your help I managed the horizontal layout with af:foreach too.
                    <af:panelGroupLayout binding="#{backing_we_vertical.panelGroupLayout2}"
                                         id="panelGroupLayout2" layout="horizontal">
                      <af:forEach var="row"
                                  items="#{bindings.Lieferanten.rangeSet}">
                        <af:inputText value="#{row.Code}" id="inputText1"/>
                      </af:forEach>
                    </af:panelGroupLayout>But the same with af:iterator doesn't work (records are still shown in vertical layout)
                    <af:panelGroupLayout binding="#{backing_we_vertical.panelGroupLayout2}"
                                         id="panelGroupLayout2" layout="horizontal">
                      <af:iterator binding="#{backing_we_vertical.iterator1}"
                                   id="iterator1"
                                   var="row"
                                   value="#{bindings.Lieferanten.collectionModel}">
                        <af:inputText value="#{row.Code}" id="inputText1"/>
                      </af:iterator>
                    </af:panelGroupLayout>here my pagedef:
    <?xml version="1.0" encoding="UTF-8" ?>
    <pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel"
                    version="11.1.1.49.49" id="we_verticalPageDef"
                    Package="view.pageDefs">
      <parameters/>
      <executables>
        <iterator id="TestIterator" Binds="Lieferanten" RangeSize="25"
                  DataControl="AppModuleDataControl"/>
      </executables>
      <bindings>
        <tree IterBinding="TestIterator" id="Lieferanten">
          <nodeDefinition DefName="model.view.lov.tlsboblag.Lieferanten">
            <AttrNames>
              <Item Value="Code"/>
              <Item Value="Bezeichnung"/>
            </AttrNames>
          </nodeDefinition>
        </tree>
      </bindings>
    </pageDefinition>Where is my mistake?
    I'll also try the capabilities of pivottable.
    regards
    Peter

  • Thread wont update GUI component

    I'm developing an RMI application. I can't seem to get the gui components to show their value once their value has been set. I know the value has been set because i can retrieve it and print it out using System.out.println("Client status : " + lblYourStatus.getText());
    My thread gets called when there's a Property ChangeEvent, the code executes correctly but the gui component still doesn't show the correct value.
    Am i implementing the code for the thread incorrectly? or am i missing something else?
    Any help would be appreciated, this has been wrecking my head for a while now.
    private void jPanel1PropertyChange(java.beans.PropertyChangeEvent evt) {
    System.out.println("in propertyChange()");
    // lblYourStatus.setText(clientStatus);
    Thread t = new Thread(this);
    t.setDaemon(true);
    t.start();
    public void run()
    // while (true)
    try
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    lblYourStatus.setText(clientStatus);
    System.out.println("Client status : " + lblYourStatus.getText());
    catch (Exception e)
    try
    Thread.sleep(1000);
    catch(Exception e) {}
    // } //end while
    }

    I don't think the RMI can affect it. It's the same for one client as it is for multiple clients. All the clients receive the correct values. I have been using System.out.println() statements to follow the program as it's been executing and everything seems to work as it should. I changed the code using the example you directed me to.
    It still receives all the correct values but when i set the label text the gui still doesn't show the text if i pass it in as a variable eg lblPlayer1Name.setText(m_player1Name), it still shows literal values eg lblPlayer1Name.setText( "test")
    I know the variable names contain valid values as i use System.out.println() statements to view them.
    any more ideas? thanks for your help so far.
        private void jPanel1PropertyChange(java.beans.PropertyChangeEvent evt) {
            Thread t = new Thread(this);
           // t.setDaemon(true);
            t.start();
        public void updateDetails(boolean gameInProgress, String status, String player1Name, String player2Name, int numSpectators)
            m_clientStatus = m_clientStatus + status;
            m_player1Name = player1Name;
            m_player2Name = player2Name;
            lblYourStatus.setText(m_clientStatus);       
            lblPlayer1Name.setText(m_player1Name);
            lblPlayer2Name.setText(m_player2Name);
        public void run()          
            //  SwingUtilities makes sure code is executed in the event thread.                                        
            SwingUtilities.invokeLater(new Runnable()                              
                public void run()                              
                    //this line wont print the value to the screen eventhough the next System.out.println() statement shows that the variable contains a valid string                              
                    lblPlayer1Name.setText(m_player1Name);     
                    System.out.println("Player 1 variable value: " + m_player1Name);
                    System.out.println("Player 1 label value: " + lblPlayer1Name.getText());
                    lblPlayer1Name.setText(lblPlayer1Name.getText());
                    //this line will print the literal string "Tom" to the label
                    lblPlayer1Name.setText("Tom");     
            // simulate log running task                              
          //  try { Thread.sleep(1000); }                         
          //  catch (Exception e) {}                    
            SwingUtilities.invokeLater(new Runnable()               
                public void run()                              
                    lblPlayer2Name.setText(m_player2Name);
                    System.out.println("Player 2 variable value: " + m_player2Name);
                    System.out.println("Player 2 label value: " + lblPlayer2Name.getText());
        }

  • A sort of KeyListener with a MINIMIZED GUI Component MINIMIZED?

    a sort of KeyListener without a GUI Component? ( or any trick that will do)?
    please be patient with my question
    I can't express myself very well but it's very important.
    Please help me I need an example how to implement
    a way to detect some combination of keystrokes in java without
    any GUI ( without AWT or Swing frames ...)
    just the console (DOS or Linux shell window) or with a minimzed
    java frame (awt or swing...) you know, MINIMIZED= not in focus.
    in other words if the user press ctrl + alt +shift ...or some
    other combination... ANYTIME ,and the java program is running in the
    background, is there a way to detect that,
    ... my problem if I use a frame (AWT or SWING) the windows must
    be in focus and NOT MINIMIZED..
    if I use
    someObject.addKeylistener(someComponent);
    then the "someComponent" must be in focus, am I right?
    What I'm coding is a program that if you highlight ANY text in
    ANY OS window, a java window (frame) should pop up and match the
    selected text in a dictionary file and brings me the meaning
    ( or a person's phone number , or
    a book author ...etc.)
    MY CHALLENGE IS WITHOUT PRESSING (Ctrl+C) to copy and paste
    ...etc. and WITHOUT MONITORING THE OS's CLIPBOARD ...I just want to
    have the feature that the user simply highlight a text in ANY
    window anywhere then press Ctrl+shift or some other combination,
    then MY JAVA PROGRAM IS TRIGGERED and it should EMULATE SOME
    KEYSTROKES OF Ctrl+C and then paste the clipboard
    somewhere in my program...with all that AUTOMATION BEING in the background.
    remember that my whole program ALL THE TIME MUST BE MINIMIZED AND
    NOT IN FOCUS
    or just running in the background (using javaw)..
    is there any trick ? pleeeeeeze!!!
    i'm not trying to write a sort of the spying so-called "key-logger"
    purely in java but it's a very similar challenge.
    please reply if you have questions
    I you could please answer me , then guys this would be very
    valuable technique that I need urgently. Thanks!

    I asked the very same question some time ago. From what I've heard you can not do this purely in java cause it would be a major secrity flaw and it could make whole systems extremely buggy since it could cause the program not to overload the keys assigned to end it.
    However if anyone knows a way to "hack" win xp's windowsystem or any other way to deal with this let us know plzzz (is it possible to make some kind of dll file etc.)

  • Suitable GUI component

    hi,
    i got a gui screen to show availability of a badminton court.Currently I have a set of buttons side by side to indicate each hour.
    If venue is free for that hour,I would set colour as green,other wise red.
    My question is there any other bettern gui component to set colour to mark availability of the court?
    Thanks

    if its just a colored component with text you can you a JLabel.
    if you need a button its exactly as much work to use a JButton.
    *though if i recall correctly, people sometime have problems changing JButton colors?                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Please Help : GUI component

    My plan is to create a GUI based page-editor(html) for text(bold,italic,underline etc..), images(not creation of image, just insert) and some more basic component with limited functionalities. This contains drag&drop option also.
    Hope Swing will be the best solution for this.
    Can anybody please help by providing any useful information for this. No problem even if the information you have is very basic level.
    Thanks in advance

    Yes swing is a better idea than AWT, build a class for each type of object you want to put on the page(JLabels will be a good solution for text and images).
    If you just want to move the object around the page you don't need to use DAD, implementing mousedrag will do the job.
    Noah

Maybe you are looking for

  • After updating to iOS 8.3, my iPhone 5 no longer can connect to cellular service

    After updating my iPhone 5 this morning to iOS 8.3, I am no longer able to get service. Upon rebooting the phone, or removing and replacing the SIM, it connects for about 30 seconds, then drops the network connectivity and is constantly 'Searching...

  • Recording audio from another application

    My kids use a program called Smart Music which plays the accompianment parts for them. Is there any way to record the audio that that 3rd party software application in Garage Band?

  • JSF - spring - hibernate and session

    Hi, I'm currently using hibernate spring and JSF 1/ the first problem In the JSF common header page I try to test if a bean is in the session scope in order to show login or logout link, and the test always fails : the logout link is always displayed

  • How to install a sotfware to read an eBook on an iPad 2

    Hello, I need to read an eBook on my iPad 2. Right now, it is hanging at each serach, so I'll uninstall it. What is the right detailled process, step by step, to install such a software? I installed Adobe Digital Editions What is the use of Bluefire?

  • Wait for the execution end of a Thread

    Hi every body, How to make a program waiting the execution end of a thread, the instruction join did not work fine. Computation c = new Computation(); Thread t = new Thread(c); t.start(); t.join(); // here my thread dead System.out.println("done"); R