Swing Busy Waiting Problem (JComboBox)

M

majin159

Gast
Hallo zusammen,

ich möchte mit dem Ergebnis der JComboBox in meinem Programm weiter arbeiten.
Also hab ich erstmal simpel darauf gewartet, aber folgendes passiert:

Java:
	public static void main(String[] args) {
		CustomComboBoxDemo asd = new CustomComboBoxDemo();
		asd.createAndShowGUI();
		while(true) {
			System.out.println(asd.a); //Sobald ich diese Zeile auskommentiere, ist es eine Endlosschleife
			if(asd.a != 99) {
				break;
			}
		}
		System.out.println("#" + asd.getA());
	}

Warum ist das so?
 
B

bygones

Gast
ui - while(true) schaut schonmal gar nicht gut aus....

ansonsten ist es schwer zu sagen was [c]asd.a[/c] macht bzw dann [c]asd.getA()[/c] ohne code
 
M

majin159

Gast
Ich kann die Bedingung auch in die Schleife schreiben, das ist ja nur ein Beispiel.
und asd.a und asd.getA() tun das gleiche, sie holen sich einfach das selected item nachdem
eins ausgewählt wurde. Wobei ich getA() mitlerweile entfernt habe.


Java:
package graphiti.help;

public class CustomComboBoxDemo extends JPanel {
    ImageIcon[] images;
    static String[] petStrings = {"dog", "cat", "pig", "bird"};
    static JComboBox petList;
    public int a = 99;

	/*
     * Despite its use of EmptyBorder, this panel makes a fine content
     * pane because the empty border just increases the panel's size
     * and is "painted" on top of the panel's normal background.  In
     * other words, the JPanel fills its entire background if it's
     * opaque (which it is by default); adding a border doesn't change
     * that.
     */
    public CustomComboBoxDemo() {
        super(new BorderLayout());

        //Load the images and create an array of indexes.
        images = new ImageIcon[petStrings.length];
        Integer[] intArray = new Integer[petStrings.length];
        for (int i = 0; i < petStrings.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = createImageIcon("images/" + petStrings[i] + ".gif");
            if (images[i] != null) {
                images[i].setDescription(petStrings[i]);
            }
        }

        //Create the combo box.
        petList = new JComboBox(intArray);
        ComboBoxRenderer renderer = new ComboBoxRenderer();
        renderer.setPreferredSize(new Dimension(200, 130));
        petList.setRenderer(renderer);
        petList.setMaximumRowCount(3);

        //Lay out the demo.
        add(petList, BorderLayout.PAGE_START);
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = CustomComboBoxDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
                return null;
        }
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    public void createAndShowGUI() {
        //Create and set up the window.
        final JFrame frame = new JFrame("CustomComboBoxDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton jButton1 = new JButton("Button");

        //Create and set up the content pane.
        JComponent newContentPane = new CustomComboBoxDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        final JList jList1 = new JList(petStrings);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
              Object contents = petList.getSelectedItem();
              a = petList.getSelectedIndex();
              System.out.println(contents + " " + a);
              frame.setVisible(false);
              frame.dispose();
//              WindowEvent closingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
//              Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent);
            }
          });
        frame.add(jButton1,"South");
        
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    class ComboBoxRenderer extends JLabel implements ListCellRenderer {
        private Font uhOhFont;

        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
        }

        /*
         * This method finds the image and text corresponding
         * to the selected value and returns the label, set up
         * to display the text and image.
         */
        public Component getListCellRendererComponent(
                                           JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
            //Get the selected index. (The index param isn't
            //always valid, so just use the value.)
            int selectedIndex = ((Integer)value).intValue();

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }

            //Set the icon and text.  If icon was null, say so.
            ImageIcon icon = images[selectedIndex];
            String pet = petStrings[selectedIndex];
            setIcon(icon);
            if (icon != null) {
                setText(pet);
                setFont(list.getFont());
            } else {
                setUhOhText(pet + " (no image available)",
                            list.getFont());
            }

            return this;
        }

        //Set the font and text when no image was found.
        protected void setUhOhText(String uhOhText, Font normalFont) {
            if (uhOhFont == null) { //lazily create this font
                uhOhFont = normalFont.deriveFont(Font.ITALIC);
            }
            setFont(uhOhFont);
            setText(uhOhText);
        }
    }
}
 

Marco13

Top Contributor
Dafür muss man die Threads mit wait/notifyAll oder den java.util.concurrent-Klassen synchronisieren. Wichtig könnte sein, welcher Thread denn dort auf das Ergebnis der ComboBox-Auswahl warten soll...?!
 
M

majin159

Gast
Dafür muss man die Threads mit wait/notifyAll oder den java.util.concurrent-Klassen synchronisieren. Wichtig könnte sein, welcher Thread denn dort auf das Ergebnis der ComboBox-Auswahl warten soll...?!

?
Die Schleife wartet und ich wills einfach ausgeben, wenn ich das kann, kann ich alles andere ja auch...

warum nicht einfach mit einem listener arbeiten?

tu ich ja, aber ich frag mich halt, warum der nicht merkt das sich a geändert hat.
Das merkt er nur, wenn ich in der Schleife _irgendetwas_ ausgebe...
 

Marco13

Top Contributor
In welchem Thread läuft die Schleife, und warum läuft die Schleife (wenn das, was dort gemacht wird, auch vom Listener gemacht werden könnte)
 
M

majin159

Gast
?
Mein erster Post, mehr existiert nicht. Die Schleife ist mein busy waiting, wie soll ich da n Listener
implementieren?
 
M

majin159

Gast
Habs gefixed, bin aber ehrlich ich weiß nicht genau warum es funktioniert.
Vllt kann mir das jemand erklären.
Marco hatte recht, ich habe mir hier ja n MultiThreading erzeugt, also muss ich die Zugriffe
auf die Variable synchronisieren, daher hab ich nun


Java:
    private synchronized void changeIndex(int selectedIndex) {
		this.a = selectedIndex;
	}
    
    public synchronized int getSelectedIndex() {
    	return this.a;
    }

in der ComboBox hinzugefügt und in der anderen Klasse frag ich dann die Methode ab.
Aber warum funktioniert das nun?
 
M

majin159

Gast
Hab die Antwort:

The most likely explanation is that the variable is only read once, turning the while into an infinite loop (or a no-op). Since you haven't declared test as volatile, the compiler is allowed to perform such an optimization.

Once you call an external function from within the loop, the compiler can no longer prove that test remains invariant across loop iterations, and doesn't perform the optimization.
 

bERt0r

Top Contributor
Schau:
Java:
comboBox.addItemListener(new ItemListener() 
               {
			public void itemStateChanged(ItemEvent e) 
			{
				if(e.getStateChange()==ItemEvent.SELECTED)
				{
					System.out.println(e.getItem());
				}
			}
		});
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
G Problem mit der Anzeige von jLabel. Unlesbar wenn der Text geändert wird. AWT, Swing, JavaFX & SWT 28
H 2D-Grafik Problem mit Paint AWT, Swing, JavaFX & SWT 1
S Layout - Problem AWT, Swing, JavaFX & SWT 1
Tassos JavaFX/Problem mit der Maussteuerung in Stackpane AWT, Swing, JavaFX & SWT 7
sserio Java Fx - Problem AWT, Swing, JavaFX & SWT 3
A Problem Spiel auf Panel der GUI zu bringen AWT, Swing, JavaFX & SWT 1
A JavaFX Controller Problem AWT, Swing, JavaFX & SWT 1
TheWhiteShadow JavaFX ListView Problem beim Entfernen von Elementen AWT, Swing, JavaFX & SWT 1
E LayoutManager Welcher Layout-Mix löst mein Problem? AWT, Swing, JavaFX & SWT 3
Umb3rus JavaFX Problem mit PropertyValueFactory: can not read from unreadable property AWT, Swing, JavaFX & SWT 1
T Problem mit paintComponent() AWT, Swing, JavaFX & SWT 17
AmsananKING Java Menü-Problem AWT, Swing, JavaFX & SWT 1
K JavaFX Resizing-Problem beim BorderLayout (Center Component) beim Arbeiten mit mehreren FXMLs AWT, Swing, JavaFX & SWT 2
G Instance OF Problem AWT, Swing, JavaFX & SWT 9
FrittenFritze Ein Problem mit der CSSBox, die Größe wird nicht angepasst AWT, Swing, JavaFX & SWT 5
M Problem mit dem Anzeigen von Frames im Vordergrund AWT, Swing, JavaFX & SWT 5
Badebay Problem mit JButton AWT, Swing, JavaFX & SWT 2
newJavaGeek Grid-Layout problem AWT, Swing, JavaFX & SWT 7
J JavaFX Löschen im Tabelview macht Problem AWT, Swing, JavaFX & SWT 15
JavaTalksToMe JavaFx ExekutorService Problem AWT, Swing, JavaFX & SWT 2
Zrebna Problem bei Eventhandling (Value soll nach jedem erneutem Klick gelöscht werden) AWT, Swing, JavaFX & SWT 4
B Problem mit JavaFX AWT, Swing, JavaFX & SWT 5
J css Problem AWT, Swing, JavaFX & SWT 5
B JavaFX habe mein Problem fett markiert AWT, Swing, JavaFX & SWT 2
A Swing Filter-Problem AWT, Swing, JavaFX & SWT 1
temi JavaFX Problem mit IntelliJ und JavaFx 11 unter XUbuntu AWT, Swing, JavaFX & SWT 3
L Java FX Problem mit Ubuntu 18 und JavaFx AWT, Swing, JavaFX & SWT 27
H JTable TableCellEditor-Problem AWT, Swing, JavaFX & SWT 0
kodela Swing Problem mit Warten-Dialog AWT, Swing, JavaFX & SWT 16
B JavaFx Scene Builder Problem AWT, Swing, JavaFX & SWT 2
B [Problem] Java öffnet Word-Datein nicht AWT, Swing, JavaFX & SWT 14
T DataBinding Problem AWT, Swing, JavaFX & SWT 5
Blender3D Problem mit € Symbol Font Gotham Windows 10 Swing AWT, Swing, JavaFX & SWT 11
T Problem mit JTable Sortierung AWT, Swing, JavaFX & SWT 2
J Problem mit Platfrom run later AWT, Swing, JavaFX & SWT 15
J Problem mit Platfrom run later AWT, Swing, JavaFX & SWT 0
D Swing SwingUtils / Thread Problem AWT, Swing, JavaFX & SWT 3
L JavaFX Problem beim Aufrufen einer Methode AWT, Swing, JavaFX & SWT 5
T Swing Problem mit Datum und FormattedTextField AWT, Swing, JavaFX & SWT 2
S AWT Java print dialog Problem AWT, Swing, JavaFX & SWT 0
olfibits JavaFX Problem mit HTMLEditor AWT, Swing, JavaFX & SWT 0
W SWT hover-background-problem with first column in TreeViewer AWT, Swing, JavaFX & SWT 0
M Problem mit Add JScrollPane AWT, Swing, JavaFX & SWT 25
Mario1409 Swing JTextArea scroll Problem AWT, Swing, JavaFX & SWT 0
N Swing Problem mit loop AWT, Swing, JavaFX & SWT 2
S Swing Problem mit Button und ActionListener AWT, Swing, JavaFX & SWT 5
S Swing & Clean und build Problem AWT, Swing, JavaFX & SWT 12
S JLabel setText() Problem AWT, Swing, JavaFX & SWT 6
I 2D-Grafik Problem beim Ändern der Farbe eine 2d Objekts AWT, Swing, JavaFX & SWT 3
G Swing Splitpane Problem AWT, Swing, JavaFX & SWT 1
F Problem mit der FXML Rectangle Shape AWT, Swing, JavaFX & SWT 2
N JavaFX Stranges Problem mit der Autoscroll-Eigenschaft von Textareas AWT, Swing, JavaFX & SWT 0
E Java FX FXML Problem mit html Scriptausführung AWT, Swing, JavaFX & SWT 2
J JavaFX Intersect Problem mit Shapes AWT, Swing, JavaFX & SWT 10
R JavaFX MediaPlayer AVI-Problem AWT, Swing, JavaFX & SWT 1
M Swing Problem mit ListCellRenderer AWT, Swing, JavaFX & SWT 7
D Problem mit JTable AWT, Swing, JavaFX & SWT 1
F GUI Auflösung ändern - Koordianten und Proportions Problem AWT, Swing, JavaFX & SWT 21
J Problem mit Button darstellung AWT, Swing, JavaFX & SWT 23
M Problem mit Layoutmanagern... Hilfe wäre sehr nett. AWT, Swing, JavaFX & SWT 2
S 2D-Grafik Problem mit Variablen AWT, Swing, JavaFX & SWT 4
7 JavaFX Problem beim Zeichnen eines Dreiecks in einem GUI AWT, Swing, JavaFX & SWT 6
M Swing AttributiveCellTableModel addRow() Problem AWT, Swing, JavaFX & SWT 1
J Swing Problem mit Graphics Methode AWT, Swing, JavaFX & SWT 4
N JavaFX Problem mit table multiple selection AWT, Swing, JavaFX & SWT 5
K CheckBox Problem AWT, Swing, JavaFX & SWT 5
Grevak DisplayMode Problem seit Windows 10 AWT, Swing, JavaFX & SWT 2
S Swing Eigene JComboBox Problem! AWT, Swing, JavaFX & SWT 1
B Swing Problem mit Bildpfad AWT, Swing, JavaFX & SWT 4
N Swing Problem beim Scrollen mit JScrollPane AWT, Swing, JavaFX & SWT 6
V Graphics g - drawOval problem mit background AWT, Swing, JavaFX & SWT 1
C AWT Problem mit Protokol Fenster AWT, Swing, JavaFX & SWT 0
M Swing pack() Problem mit Taskleiste AWT, Swing, JavaFX & SWT 4
N Swing Choice- Problem! AWT, Swing, JavaFX & SWT 8
Q "AWT-EventQueue-0" Exception Problem AWT, Swing, JavaFX & SWT 4
D jButton Problem, ein Rieser Button bedeckt das ganze frame AWT, Swing, JavaFX & SWT 1
A Problem: repaint() - Schleife AWT, Swing, JavaFX & SWT 3
J Anfänger GUI Problem bei der Ausführung eines sehr einfachen Programms AWT, Swing, JavaFX & SWT 2
P AWT Problem mit Platzierung (GridBagLayout) AWT, Swing, JavaFX & SWT 2
N Swing JTree Problem beim erstellen der Knoten AWT, Swing, JavaFX & SWT 0
N Swing CardLayout: Problem beim Wechsel zwischen den JPanels AWT, Swing, JavaFX & SWT 3
A Mini-Menu-Schriften. Ein Problem bei hohen DPI Zahlen AWT, Swing, JavaFX & SWT 2
Z Canvas in Frame einfügen. Problem mit 4-Gewinnt AWT, Swing, JavaFX & SWT 1
C Thread-/ Simulations- Problem AWT, Swing, JavaFX & SWT 18
G Swing Setvisible problem AWT, Swing, JavaFX & SWT 1
J JTabbedPane: close Button Problem AWT, Swing, JavaFX & SWT 2
Tom299 JavaFX -> fxmlLoader -> getResourceAsStream Problem AWT, Swing, JavaFX & SWT 1
T Problem: ComboBox und addItem AWT, Swing, JavaFX & SWT 5
M JTextArea wird nicht aktualisiert (ActionListener-Problem) AWT, Swing, JavaFX & SWT 1
T LayoutManager LookAndFeel-Problem AWT, Swing, JavaFX & SWT 4
F Problem mit Implementierung von Kollisionsabfrage AWT, Swing, JavaFX & SWT 5
vodkaz (javafx) Image Problem AWT, Swing, JavaFX & SWT 2
T Problem beim Zeichnen von Rechteck AWT, Swing, JavaFX & SWT 3
B JavaFX Problem bei Kamera / Group, gesamte Scene bewegt sich mit AWT, Swing, JavaFX & SWT 0
L Swing Vier Gewinnt Problem AWT, Swing, JavaFX & SWT 2
Z GUI-Problem, finde meinen Fehler nicht! AWT, Swing, JavaFX & SWT 11
B JavaFX KeyEvent und Canvas draw Problem AWT, Swing, JavaFX & SWT 9
R Swing Problem: IOException bei ActionListener AWT, Swing, JavaFX & SWT 1
GianaSisters JFrame mit JInternalFrames, Keylistener-Problem AWT, Swing, JavaFX & SWT 9
Q JList Update Problem AWT, Swing, JavaFX & SWT 1

Ähnliche Java Themen

Neue Themen


Oben