Reputation: 85
I'm trying to create a modular MVC swing app. So i have a Main
class that runs the code, a Frame
class (extendeds JFrame
) that represents the window, and within it there's a class (extendeds JPanel
) that has my GUI elements. My aim is to be able to easily update/repaint the Panel
class, when the View needs to change.
However, as my code is right now, it runs without errors, and it opens an empty Frame but the elements within the JPanel class won't show and I don't know why. - most probably a noob mistake, i know, but I can't see it any more.
So here's my main class:
package mvc;
public class Main {
public static void main(String[] args)
{
new Frame();
}
}
Here's the JFrame class
package mvc;
import java.awt.Container;
import javax.swing.JFrame;
public class Frame extends JFrame{
private static int width = 500;
private static int height = 500;
public Frame(){
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container pane = getContentPane();
Panel game = new Panel();
pane.add(game);
pack();
setSize(width, height);
setLocation(100,100);
setVisible(true);
}
}
and here's the JPanel
package mvc;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Panel extends JPanel {
private JButton b1;
private JLabel l1;
public Panel(){
Container pane = new JPanel();
b1 = new JButton("Button");
pane.add(b1);
l1 = new JLabel("Label for the button");
pane.add(l1);
}
}
Upvotes: 0
Views: 500
Reputation: 347314
I'm not sure why you're doing this...
public Panel(){
Container pane = new JPanel();
b1 = new JButton("Button");
pane.add(b1);
l1 = new JLabel("Label for the button");
pane.add(l1);
}
But you're not adding pane
to anything, so nothing is been shown on the screen
It'd be easier to just do something like...
public Panel(){
b1 = new JButton("Button");
add(b1);
l1 = new JLabel("Label for the button");
add(l1);
}
You should also be creating and modifying your UI's only from within the context of the Event Dispatching Thread, have a look at Initial Threads for more details
Upvotes: 3