Reputation: 25
I have built a small program in java to fetch a result from an input.
It works in console, but now I want it to have a GUI, for which I'm using swing JFrames.
And that's where I'm stuck: I manage to display a form, creating it from my main code. But then I want to manipulate this form at will, using simple setters and getters.
I've made a setter to change the value of my form panel, but the main code won't recognize the method.
I'm very new to GUI, so I wager that I'm just lacking the right logic to use Swing, but if anyone would be kind enough to find what gross mistake I'm making, here's my code, striped down to the bare minimum of what I'm stuck with:
NB: here I've put my main code directly into the class out of convenience, but I've tried separating my GUI class from my main with the same result.
public class mainform {
public JPanel panel1;
private JLabel output;
public void setRes()
{
output.setText("hello");
}
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("mainform");
frame.setContentPane(new mainform().panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setRes(); // HERE IS WHERE "setRes" won't be recognized as a method...
}
}
Upvotes: 1
Views: 1591
Reputation: 25
Thank you for all of your answers! So rooky mystake, I didn't extend my mainform class into a JFrame.
The following will actually compile but the text of the label won't change. Why is that ?
(Also, yeah sorry for the naming conventions, it was my interntion to juste fiddle a bit on a phony project before actually coding the real GUI with proper naming.)
<!-- language: java -->
public class mainform extends JFrame {
public JPanel panel1;
private JLabel output;
public void setRes()
{
output.setText("hello");
}
public static void main(String[] args) throws IOException {
mainform frame = new mainform();
frame.setContentPane(new mainform().panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setRes();
}
}
Upvotes: 0
Reputation: 48288
JFrame class doesn't have a setRes() method.... so you can't call frame.asetRes()
because there is no such a method.
What you need is the instance of the mainform class instead.
Upvotes: 2
Reputation: 140475
You declared frame to be of type JFrame. And the compiler doesn't care about the right hand side of the assignment.
For the compiler, frame is a JFrame. And JFrames do not have that method. So you have to change the type of the variable to mainform. And of course, in order to make mainform a JFrame, you have to make your class a frame:
class mainform extends JFrame
Besides: please study java naming conventions. Class names always go UpperCase, so maybe "TestFrame" would be a much better name here. Also avoid "abbreviations" for method names. And then "setRes()" doesn't say anything; you better call it "placeTextOnPanel" or something alike.
Upvotes: 2