I've got the following button...
public void actionPerformed(ActionEvent arg0) {
Contacts contact = new Contacts();
contact.setVisible(true);
}
Contacts is just a simple JApplet...
public class Contacts extends JApplet {
private JPanel jContentPane = null;
public Contacts() {
super();
}
public void init() {
this.setSize(500, 260);
this.setContentPane(getJContentPane());
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJList(), null);
jContentPane.add(getJButton(), null);
jContentPane.add(getJButton1(), null);
}
return jContentPane;
}
}
Why is what I'm doing not working? How would I launch this JFrame?
Like JFrame and JDialog, JApplet is a top-level container. You can't put one inside the other. Instead, do something like this:
class Contacts extends JFrame { ... }
...
Contacts contact = new Contacts();
contact.setVisible(true);
If you have an existing JApplet that you want to display in a JFrame, you can create a hybrid, as shown in the examples examined here.
Related
i have a program with a frame that contains a main panel with the cardlayout layout, and i want it to display different cards/panel.
In my case i'm really struggling to call a new card from a button action listener.
I want a new card to appear after i click on a button but none of the codes i put in my action listener displayed the card i wanted.
I know my actionListener work because i did a println inside.
here's my code. i got rid of anything that was unnecessary so it's easier to read. Thanks for the help!
i'll take all advices about code structuration
the mainFrame :
public class MainFrame extends JFrame{
final static String CONNEXION_VIEW = "connexionView";
final static String CONNEXION_FAILED_VIEW = "connexionRefusee";
public MainFrame()
{
super();
initialize();
}
private void initialize()
{
getMainPanel();
add(getMainPanel());
}
CardLayout cardLayout;
public CardLayout getCardLayout()
{
if (cardLayout == null)
{
cardLayout = new CardLayout();
}
return cardLayout;
}
JPanel mainPanel;
public JPanel getMainPanel()
{
if (mainPanel == null)
{
mainPanel = new JPanel();
mainPanel.setLayout(getCardLayout());
mainPanel.add(CONNEXION_VIEW, getConnexionView());
mainPanel.add(CONNEXION_FAILED_VIEW, getConnexionFailedView());
}
return mainPanel;
}
ConnexionView connexionView;
protected ConnexionView getConnexionView()
{
if (connexionView == null)
{
connexionView = new ConnexionView();
}
return connexionView;
}
ConnexionFailedView connexionFailedView;
protected ConnexionFailedView getConnexionFailedView()
{
if (connexionFailedView == null)
{
connexionFailedView = new ConnexionFailedView();
}
return connexionFailedView;
}
the connexion view, the one with the button to click with the action listener where i want to put my code
public class ConnexionView extends JPanel{
GridBagLayout gbl = new GridBagLayout();
private JButton btnConnexion;
Dimension dimensionBouton = new Dimension(170, 30);
public ConnexionView()
{
super();
initialise();
}
private void initialise()
{
setLayout(gbl);
GridBagConstraints gbcbtnConnexion = new GridBagConstraints();
gbcbtnConnexion.gridwidth = GridBagConstraints.REMAINDER;
gbcbtnConnexion.gridheight = GridBagConstraints.REMAINDER;
gbcbtnConnexion.gridx = 1;
gbcbtnConnexion.gridy = 2;
add(getBtnConnexion(), gbcbtnConnexion);
}
private JButton getBtnConnexion()
{
if (btnConnexion == null)
{
btnConnexion = new JButton("Connexion");
btnConnexion.setPreferredSize(dimensionBouton);
btnConnexion.setMinimumSize(dimensionBouton);
btnConnexion.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
/////code to display the connexion_Failed_View
System.out.println("test");
}
});
}
return btnConnexion;
}
}
and the connexion failed view, the one i want to display after the button is clicked
public class ConnexionFailedView extends JPanel{
public ConnexionFailedView()
{
super();
initialise();
}
private void initialise()
{
setBackground(Color.YELLOW);
}
thanks in advance
You will need to keep the component in your Button somehow, so you can access it.
class ConnexionView {
private JComponent mainPanel;
public ConnexionView(JComponent mp) { mainPanel = mp; }
}
Obviously, that means the MainFrame needs to pass it then.
Now, the listener can do
// it would be cleaner if you passed the layout in the constructor as well
CardLayout cl = (CardLayout) mainPanel.getLayoutManager();
cl.show(mainPanel, MainFrame.CONNEXION_FAILED_VIEW);
I can add/remove elements to/from a panel and repaint it when the method used to fill the panel is called by one of its parent JFrame events, but I can not repaint it by events from other classes even if their sources have been added to it, or that is how I understand the problem for now.
I want to understand what is going on here, Thank you.
Main Class
public class Principal extends JFrame implements ActionListener{
private static Principal instPrincipal = null;
private SubClass subClassInst =new SubClass();
public JPanel panelPrincipal;
public static Principal getInstance() {
if (instPrincipal != null)
return instPrincipal ;
else {
instPrincipal = new Principal ();
return instPrincipal ;
}
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
try {
if(source == btnSub)
{
subClassInst.fillPanelPrincipal();
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Sub Classes Example
public class SubClass implements ActionListener {
private JPanel tempPanel;
private JButton btnSave;
private Principal instPrincipal;
public void fillPanelPrincipal() {
instPrincipal = Principal.getInstance();
instPrincipal.panelPrincipal.removeAll();
//Start adding elements..
tempPanel = new JPanel();
instPrincipal.panelPrincipal.add(tempPanel);
btnSave = new JButton("Save");
btnSave.addActionListener(this);
tempPanel.add(btnSave);
//End.
instPrincipal.panelPrincipal.repaint();
}
public void actionPerformed(ActionEvent event) {
instPrincipal = Principal.getInstance();
Object source = event.getSource();
if (source == btnSave) {
// modify local data, Database .. ; //work but need to be repainted on panelPrincipal
instPrincipal.panelPrincipal.repaint();//does not work
}
}
}
Update
To clarify the problem more, I have one single JPanel on a JFrame and there are different classes to fill it for multiple functionalities, I call their methods using JMenuItems on the main frame, these Classes implement ActionListener, passing the panel didn't work, and also the method I am trying here.
I thought about changing the design to use CardLayout, but it was very difficult.
You are calling Principal as a static reference, so how is it supposed to know what frame to repaint? You should pass the instance of the JFrame through the constructor of the subclass. Like so:
private SubClass subClassInst = new SubClass(this);
And create the constructor like this
private JFrame parent;
public SubClass(JFrame parent) { this.parent = parent; }
You can then use it like so
this.parent.repaint();
Looking at other answers, i have followed exactly what they say, but i just keep getting the nullPointerException error. I have 4 classes, the 2 below, a GUI class and main menu class. Main manages the card layout and i would like a button in the Insert class to change the "Active" card to main menu class.
Main:
public class Main extends JPanel implements ChooserListener{
MainMenu mm;
Insert InsertCustomer;
public JPanel mPanel;
CardLayout cl;
private String c;
public Main(){
super();
//add mPanel, set to CardLayout and add the Main
mPanel = new JPanel();
this.add(mPanel);
cl = new CardLayout();
mPanel.setLayout(cl);
//add classes
mm = new MainMenu(this);
InsertCustomer = new Insert();
//add classes to mPanel
mPanel.add(mm, "mm");
mPanel.add(InsertCustomer, "InsertCustomer");
}
public void tell(Object o) {
c = o.toString();
cl.show(mPanel, c);
}
public void swapView(String key) {
CardLayout cl = (CardLayout)(mPanel.getLayout());
cl.show(mPanel, key);
}
}
Insert:
public class Insert extends JPanel{
private JButton logoutbutton;
private LogoutListener lListener;
public Insert() {
super();
//BUTTONS
//logout button
JButton logoutbutton = new JButton("Main Menu");
this.add(logoutbutton);
lListener = new LogoutListener(null);
logoutbutton.addActionListener(lListener);
}
private class LogoutListener implements ActionListener{
private Main main;
public LogoutListener(Main main){
this.main = main;
}
public void actionPerformed(ActionEvent e) {
main.swapView("mm");
}
}
}
lListener = new LogoutListener(null);
Your LogoutListener takes your Main-class, but you give him null. Of course you will get a NullPointerException (at least on your logoutButton-click).
Your problem in next lines :
lListener = new LogoutListener(null);
main.swapView("mm");
You need to put reference to your Main class, not null as you done. Because of your main in LogoutListener is null and you catch NPE.
Simple solution is to transfer reference of your Main to Insert with help of constructor and then transfer that to LogoutListener.
I have a problem that the JFrame is not showing upmy components.
When i opened the GasStationPanel in WindowBuilder it show well, but the MainFrame is show as a blank windows.
Please, I need you help here.
Thanks!
The JFrame code is:
public class MainFrame extends JFrame {
private GasStationPanel pnlMainGasStation;
public MainFrame() throws SecurityException, IOException {
try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
getContentPane().setLayout(new BorderLayout());
this.pnlMainGasStation = new GasStationPanel("all cars","pumps","coffee");
this.add(pnlMainGasStation, BorderLayout.CENTER);
setLocationRelativeTo(null);
setTitle("GasStation");
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
Utils.closeApplication(MainFrame.this);
}
});
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = new Dimension();
frameSize.setSize(screenSize.width*0.7, screenSize.height*0.9);
setSize(frameSize);
setVisible(true);
}
public GasStationPanel getMainPanel() {
return pnlMainGasStation;
}
}
The GasStationPanel Code:
public class GasStationPanel extends JPanel {
private JSplitPane splinterRight, splinterLeft;
private AllCarsPanel allCarsPanel;
private FuelPumpListPanel fuelPumpsListPanel;
private CoffeeHousePanel coffeeHousePanel;
private List<GasStationController> allListeners;
public AllCarsPanel getAllCarsPanel() {
return allCarsPanel;
}
public FuelPumpListPanel getFuelPumpsListPanel() {
return fuelPumpsListPanel;
}
public CoffeeHousePanel getCoffeeHousePanel() {
return coffeeHousePanel;
}
public GasStationPanel(String allCarsStr, String fuelPumpsListStr,
String coffeeHousePanelStr) throws SecurityException, IOException {
// Init Listeners List
this.allListeners = new ArrayList<GasStationController>();
// Layout and size
setLayout(new BorderLayout());
// Build panels
allCarsPanel = new AllCarsPanel();
fuelPumpsListPanel = new FuelPumpListPanel();
coffeeHousePanel = new CoffeeHousePanel();
// Split the screen to three
splinterRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splinterLeft = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splinterLeft.setLeftComponent(allCarsPanel);
splinterLeft.setRightComponent(fuelPumpsListPanel);
splinterRight.setLeftComponent(splinterLeft);
splinterRight.setRightComponent(coffeeHousePanel);
}
public void registerListener(GasStationController gasStationController) {
this.allListeners.add(gasStationController);
}
In short, you never add any components to your container. For example, in your GasStationPanel code, perhaps you should try invoking add(Component) by passing in your JSplitPanes as an argument. For example:
add(splinterLeft, BorderLayout.CENTER);
I have played for a while with History in gwt because i intend to implement it in my current project, so i created a small demo project just to see how it works and do some practice.
So, for some reasons it does not work.
Here is the code - very simple back and forward.
here is the iframe
<iframe id="__gwt_historyFrame" style="width:0;height:0;border:0"></iframe>
then the entry point
public class EntryPoint implements com.google.gwt.core.client.EntryPoint {
private FirstPanel panel;
public void onModuleLoad() {
ContentPanel panel = ContentPanel.getInstance();
panel.setContent(FirstPanel.getInstance());
RootPanel.get().add(panel);
}
}
and 3 singleton forms, content where form are being loaded and 2 form.
public class ContentPanel extends Composite
{
private static ContentPanel instance;
private static VerticalPanel panel = new VerticalPanel();
private ContentPanel()
{
initWidget(panel);
}
public void setContent(Widget widget)
{
panel.clear();
panel.add(widget);
}
public static ContentPanel getInstance()
{
if(instance == null)
return instance = new ContentPanel();
else
return instance;
}
}
and ..
public class FirstPanel extends Composite implements HistoryListener {
private static FirstPanel instance;
private VerticalPanel panel;
public FirstPanel() {
History.addHistoryListener(this);
panel = new VerticalPanel();
panel.setStyleName("panelstyle");
Button button2 = new Button("Next page");
button2.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
History.newItem("second_page");
}
});
panel.add(button2);
initWidget(panel);
}
public static FirstPanel getInstance()
{
if(instance == null)
return instance = new FirstPanel();
else
return instance;
}
public Widget getWidget() {
return panel;
}
public void onHistoryChanged(String historyToken) {
if(historyToken.equalsIgnoreCase("second_page"))
ContentPanel.getInstance().setContent(SecondPanel.getInstance());
}
}
and the last but not least :))
public class SecondPanel extends Composite implements HistoryListener
{
private static SecondPanel instance;
public SecondPanel()
{
History.addHistoryListener(this);
VerticalPanel verticalPanel = new VerticalPanel();
TextBox firstnameBox = new TextBox();
TextBox lastnameBox = new TextBox();
Button submitButton = new Button("Click");
verticalPanel.add(firstnameBox);
verticalPanel.add(lastnameBox);
verticalPanel.add(submitButton);
submitButton.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
History.newItem("first_panel");
alert("You are in second panel");
}
});
initWidget(verticalPanel);
}
public static SecondPanel getInstance()
{
if(instance == null)
return instance = new SecondPanel();
else
return instance;
}
public void onHistoryChanged(String historyToken)
{
if(historyToken.equalsIgnoreCase("first_panel"))
ContentPanel.getInstance().setContent(FirstPanel.getInstance());
}
}
The problem is that i click the button in FirstPanel and SecandPanel is loaded then press "Back" in the browser does not do anything.In onHistoryChanged method the param historyToken is empty string, should't be a value from the stack (first_page)?
I will be grateful if someone find the problem or explain me where i do mistakes.
Thanks
On first page load you are calling onHistoryChanged(INIT_STATE) by hand. This does not change history. Replace with this:
public FirstPanel() {
History.addHistoryListener(this);
String token = History.getToken();
if (token.length() == 0) {
History.newItem(INIT_STATE);
} else {
History.fireCurrentHistoryState();
}
.. rest of code
Better practice would be to register History listeners History.addHistoryListener(..) only in the top-most panel (EntryPoint or ContentPanel) and switch panels based on history from there.