I'm just starting out in Java, and only ever used PHP before - finding it hard to get my head round the object-orientated thing. I am using the Eclipse IDE.
I am trying to make a program that will tell you your weight on another planet - seems simple enough
All I have done so far is make half the interface in Swing (is that what it's called?)
Sometimes I run it, and it comes up as I would expect, with the title, textboxes etc....
other times (when absolutely no changes have been made), it just comes up with a blank screen

The image shows what it looks like when it is working. When it's not working, there are just no objects. It works about 20% of the time.
I think this might have been because of my drop down menu - or JComboBox, this has been such a head ache - Eclipse made me add "< Object>" after each mention of JComboBox - it said "JComboBox is a raw type. References to generic type JComboBox should be parameterized"
I have no idea why this is, and I'm probably just being really thick, sorry if this is a stupid question, but how can I fix this problem, what's wrong with my code?
package calc;
import javax.swing.*;
import java.awt.*;
public class View extends JFrame {
static String titleText = "Calculate your Mass on another Plannet";
public View(){
super(titleText);
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
FlowLayout flo = new FlowLayout();
setLayout(flo);
JPanel inputData = new JPanel();
//Labels
JLabel lblTitle = new JLabel (titleText, JLabel.CENTER);
lblTitle.setFont(new Font("Arial", Font.BOLD, 24));
JLabel lblInputMass = new JLabel ("Weight", JLabel.LEFT);
JLabel lblInputUnits = new JLabel("Units");
//Input Boxes and Lists
JTextField txtInputMass = new JTextField(5);
JComboBox<Object> comInputUnits;
String arrUnits[] = {"Kilos", "Stone", "Pounds"};
comInputUnits = new JComboBox<Object>(arrUnits);
comInputUnits.setSelectedIndex(1);
//Buttons
JButton btnCalculate = new JButton("Calculate");
//Append objects
add(lblTitle);
inputData.add(lblInputMass);
inputData.add(txtInputMass);
inputData.add(lblInputUnits);
inputData.add(comInputUnits);
inputData.add(btnCalculate);
add(inputData);
}
/**
* @param args
*/
public static void main(String[] args) {
View sal = new View();
}
}
Sorry it's quite a long question, and I'd be so grateful to any suggestions or answers, as I said, I know barley anything about Java, and am just starting out - thank you :)
You should
setVisible(true) only after all the components have been added to the frame;The <Object> that "Eclipse made you add" are called generic types. Read the tutorial on generics.
You need to do everything dealing with Swing components inside the EventDispatchThread (EDT).
wrap the call to new View() in a call to SwingUtilities.invokeAndWait()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With