my name is Gab.
I'm making a program that will make vanish one page for an other by clicking a button. The thing is, I can't pass the appropriate datas from my two classes. It may sounds weird like this, but here's my code:
My first class (class1):
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
contenu.setLayout(gridBag);
boolean start = false;
JLabel label1 = new JLabel(
"<html><p><span style = 'font-size: 18px; font-color: blue'>The Number's Genius </span>(version 1.4)</p></html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 4;
c.ipadx = 500;
panel.add(label1, c);
JLabel xxx = new JLabel("");
c.gridx = 0;
c.gridy = 4;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 550;
panel.add(xxx, c);
JButton start = new JButton("<html><p><b>Start</b></p></html>");
c.gridx = 3;
c.gridy = 4;
c.gridwidth = 1;
c.ipadx = 1;
c.anchor = GridBagConstraints.LINE_END;
panel.add(start, c);
JLabel msg1 = new JLabel(
"<html><p style = 'background-color: white; font-size: 10px'>Click on Start to begin.</p></html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 3;
c.gridwidth = 4;
panel.add(msg1, c);
JLabel msg2 = new JLabel(
"<html><p style = 'background-color: white; font-size: 10px'>Ok, let's begin.</p><p style = 'background-color: white; font-size: 10px'>First question: Is your number even?</html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 3;
c.gridwidth = 4;
panel.add(msg1, c);
Moteur moteur = new Moteur();
start.addActionListener(moteur);
frame.setContentPane(contenu);
frame.setSize(700, 300);
frame.setVisible(true);
frame.setResizable(false);
}
}
You might notice that the second class has some text in french, but don't worry, it's not important. Here's my second class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Moteur implements ActionListener {
public void actionPerformed(ActionEvent e) {
msg1.setVisible(false);
msg2.setVisible(true);
}
}
In fact, I want the program to make 'msg1' visibility to false and 'msg2' visibility to true, but I can't make the program work because the second class don't know what is 'msg1' and 'msg2'. Please, help me!
Regards, -Gab
For a method to be able to use an object, it needs a reference to this object. You're creating a Moteur instance, but you don't pass any object to this Moteur instance, so it doesn't have a reference to any object except itself.
For the Moteur class to be able to call methods of msg1 and msg2, you need to pass a reference to these two objects to Moteur:
public class Moteur implements ActionListener {
private JLabel messageToHide;
private JLabel messageToShow;
public Moteur(JLabel messageToHide, JLabel messageToShow) {
this.messageToHide = messageToHide;
this.messageToShow = messageToShow;
}
public void actionPerformed(ActionEvent e) {
messageToHide.setVisible(false);
messageToShow.setVisible(true);
}
}
And then, when you create the Moteur, you give them the two labels to hide and show:
Moteur moteur = new Moteur(msg1, msg2);
Use getters and setters for msg's.
Related
(Sorry if this question is not done properly, I'm new. But at least I researched a lot before asking my own question)
Hello. I'm writing a blackjack game in java and it's turning quite massive. My problem is how to handle multiple instances of swing components, I guess you can call it. I can't figure out wether to create the components (such as jpanels and jbuttons) as class level, or in specific methods.
If I create them in their corresponding method, then my action listener can't see them, but if I create them as class level, then they get deleted when I call dispose().
class BlackjackGame extends JFrame implements ActionListener{
public void mainMenu(){
JPanel menuPane = new JPanel(new GridBagLayout()); //Init of main menu
GridBagConstraints c = new GridBagConstraints();
menuPane.setBackground(new Color(125,0,0));
menuPane.setBounds(620,220,175,250);
JLabel menuTitle = new JLabel("Welcome to Blackjack!");//Main menu-content
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0,0,20,0);
menuPane.add(menuTitle, c);
JButton playButton = new JButton("Play!");
playButton.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
c.ipadx = 25;
c.ipady = 25;
c.insets = new Insets(0,0,0,0);
menuPane.add(playButton, c);
JButton exitButton = new JButton("Exit!");
exitButton.addActionListener(this);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
menuPane.add(exitButton, c);
JButton rulesButton = new JButton("Set rules.");
rulesButton.addActionListener(this);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 3;
menuPane.add(rulesButton, c);
this.add(menuPane,0);
}
//This is where I get problems
public void actionPerformed (ActionEvent event){
if(event.getSource() == playButton){
//I want the menuPane to disappear, and a transition into the game.
menuPane.dispose();
//Call method for the rest of the game.
}else if(event .getSource() etcetera etcetera){
etcetera etcetera
}
}
}
When done this way, the actionlistener cannot find my components, such as playButton or menuPane. But if I had introduced them as class level objects:
class BlackjackGame extends JFrame implements ActionListener{
JPanel menuPane = new JPanel(new GridBagLayout());
JLabel menuTitle = new JLabel("Welcome to Blackjack!");
JButton playButton = new JButton("Play!");
JButton exitButton = new JButton("Exit!");
JButton rulesButton = new JButton("Set rules.");
public void mainMenu(){
//Rest of code
}
public void actionPerformed(ActionEvent event){
menuPane.dispose();
//Rest of code
}
}
...then as I call menuPane.dispose(), how can I get it back when I want to call mainMenu() again? If I want to go back to the main menu, then I would need to create a new instance of menuPane, as well as all the buttons, but as they are class level and already disposed I can't.
Please help me, and thank you!
PS. I can post my full code as it is atm if it would help.
Edit: Dan's answer has been accepted, as it was indeed the correct answer and it worked for my specific program very well. Thank you and merry christmas!
First, unless I've misunderstood your code, menuPane.dispose() shouldn't work as JPanel does not have a function called dispose()
The best way to do what you want to do if you want to use the same menuPane for the menu. Instead of menuPane.dispose(); use remove(menuPane); and then add(yourOtherPanel);
Working Example
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class BlackjackGame extends JFrame implements ActionListener {
private JPanel menuPane;
private JLabel menuTitle;
private JButton playButton;
private JButton exitButton;
private JButton rulesButton;
private JPanel otherPane;
private JLabel otherTitle;
private JButton otherButton;
public BlackjackGame() {
mainMenu();
otherPanel();
setSize(400, 400);
setVisible(true);
}
private void mainMenu() {
menuPane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
menuPane.setBackground(new Color(125,0,0));
menuPane.setBounds(620,220,175,250);
menuTitle = new JLabel("Welcome to Blackjack!");
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0,0,20,0);
menuPane.add(menuTitle, c);
playButton = new JButton("Play!");
playButton.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
c.ipadx = 25;
c.ipady = 25;
c.insets = new Insets(0,0,0,0);
menuPane.add(playButton, c);
exitButton = new JButton("Exit!");
exitButton.addActionListener(this);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
menuPane.add(exitButton, c);
rulesButton = new JButton("Set rules.");
rulesButton.addActionListener(this);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 3;
menuPane.add(rulesButton, c);
add(menuPane);
}
private void otherPanel() {
otherPane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
otherPane.setBackground(new Color(125,0,0));
otherPane.setBounds(620,220,175,250);
otherTitle = new JLabel("Welcome to Second Pane!");
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0,0,20,0);
otherPane.add(otherTitle, c);
otherButton = new JButton("Go Back!");
otherButton.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
c.ipadx = 25;
c.ipady = 25;
c.insets = new Insets(0,0,0,0);
otherPane.add(otherButton, c);
}
public void actionPerformed (ActionEvent event) {
if(event.getSource() == playButton) {
remove(menuPane);
add(otherPane);
validate();
repaint();
} else if(event.getSource() == otherButton) {
remove(otherPane);
add(menuPane);
validate();
repaint();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new BlackjackGame());
}
}
Edit for comments
So the java method remove() only removes the object from the container, which in this case is the JFrame. This method does not effect the object it moves so the object can be reused later. Hence why in the code above I can just use the remove() and add() methods without redeclaring or remaking menuPane and otherPane.
As for why I declare the objects like this
`private JPanel menuPane;`
And then initialize like this
menuPane = new JPanel(new GridBagLayout());
This is because I want the ActionListener to be able to see the objects without initializing them straight away. The line private JPanel menuPane; makes the object a global variable and the line menuPane = new JPanel(new GridBagLayout()); makes it into what I am going to use. Doing it this way instead of JPanel menuPane = new JPanel(new GridBagLayout()); also means I can reuse the same variable in multiple methods. For example
private JPanel panel;
private void createPanelOne() {
panel = new JPanel(new FlowLayout());
...
add(panel);
}
private void createPanelTwo() {
panel = new JPanel(new GridBagLayout());
...
add(panel);
}
After doing this, you will have two JPanels in your JFrame and they will be different, but you only need to use one JPanel
This is the other way of declaring it and it makes a local variable. Local variables aren't visible to other methods outside of the method you are using unless you pass them through.
JPanel panel = new JPanel();
I wouldn't say this is a con in the slightest. I think sometimes it is good to use local variables in a method that shouldn't be visible to other methods.
Finally to pass local variables through to other methods you can use arguments in a method you have made. For example
public void setSomeValue(int val) {
someValue = val;
}
i'm trying to make a window with GridBagLayout, here are my code:
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ReadMessage extends JFrame implements ActionListener
{
JButton Last;
JButton Delete;
JButton Store;
JButton Next;
JTextArea MessageBox;
public ReadMessage()
{
setLayout(new FlowLayout());
JPanel Panel = new JPanel();
add(Panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
MessageBox = new JTextArea();
MessageBox.setEditable(false);
JScrollPane scrollPane = new JScrollPane(MessageBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
MessageBox.setLineWrap(true);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
c.weightx = 0.0;
c.ipady = 300;
c.ipadx = 300;
Panel.add(scrollPane, c);
Last = new JButton("Last");
c.gridx = 0;
c.gridy = 1;
c.ipady = 0;
c.weightx = 0.5;
Panel.add(Last, c);
Last.addActionListener(this);
Delete = new JButton("Delete");
c.gridx = 1;
c.gridy = 1;
c.ipady = 0;
c.weightx = 0.5;
Panel.add(Delete, c);
Delete.addActionListener(this);
Store = new JButton("Store");
c.gridx = 2;
c.gridy = 1;
c.ipady = 0;
c.weightx = 0.5;
Panel.add(Store, c);
Store.addActionListener(this);
Next = new JButton("Next");
c.gridx = 3;
c.gridy = 1;
c.ipady = 0;
c.weightx = 0.5;
Panel.add(Next, c);
Next.addActionListener(this);
}
}
and it turns out to be something like this
what i really want is like this
I know i did terribly wrong but i can't figure out what exactly i did wrong, I read the docs on oracle but couldn't find a thing, could you point out what i did wrong, and how to fix it? thank you very much
All your buttons have a gridwidth of 4 instead of 1.
You can nest panels each using a different layout manager to achieve your desired layout.
Create a main panel with a BorderLayout and add this panel to the frame
Add the JTextArea to the BorderLayout.CENTER of the main panel
Create a second panel for the buttons and use a FlowLayout. Then add the buttons to this panel. Then this panel can be added to the main panel at the BorderLayout.PAGE_END.
Why are my constraints for my buttons not working? I looked at the Java Docs and am doing the same thing the tutorials are doing, but for me the buttons stay the same regardless of what gridx, y, width, or fill I use. Any ideas? Here's my code:
class MyWindow
{
public static void main(String [] arg)
{
MyJFrame f = new MyJFrame("My GUI 2015");
f.setVisible(true);
f.setSize(10, 20);
f.add(f.p);
}
}
and
public class MyJFrame extends JFrame {
public JPanel p;
JButton close = new JButton("close");
JButton drawing = new JButton("drawing");
JButton image = new JButton("image");
JButton browser = new JButton("browser");
public MyJFrame(String title) {
super(title);
p = new JPanel();
buildButtons();
}
void buildButtons() {
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(0,40,0,150);
c.gridx = 0;
c.gridy = 0;
p.add(drawing, c);
c.gridx = 2;
c.gridy = 0;
p.add(close, c);
c.insets = new Insets(50,225,50,150);
c.gridx = 0;
c.gridy = 1;
p.add(image, c);
c.insets = new Insets(0,125,0,125);
c.gridx = 0;
c.gridy = 100;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(browser, c);
}
}
The LayoutManager for the container is not specified in your current code (the default for a JPanel is FlowLayout). If you wish to use a GridBagLayout on the container, you must explicitly specify the LayoutManager:
p = new JPanel(new GridBagLayout());
//or
p.setLayout(new GridBagLayout());
I am having troubles getting the layout right.
I have a Class which extends JFrame and has a JPanel which has a the GridBagLayout as layout manager. I want 4 buttons which should be layout in this way
Somehow the vertical filling does not work.
I tried various ways but can't figure out how to make this work.
Sorry if this is a noob question, but tried it for more than an hour without any change :/
public class ButtonPanel extends JFrame {
private static final long serialVersionUID = 1L;
public ButtonPanel() {
this.setSize(800, 600);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
frame();
}
JButton objectsBtn = new JButton("Objekte"); //TODO Strings einfügen
JButton tenantBtn = new JButton("Mieter"); //TODO Strings einfügen
JButton ownerBtn = new JButton("Eigentümer"); //TODO Strings einfügen
JButton optionsBtn = new JButton("Einstellungen"); //TODO Strings einfügen
JPanel panel = new JPanel();
public void frame(){
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.RELATIVE;
c.gridheight = GridBagConstraints.RELATIVE;
//Elemente
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
panel.add(objectsBtn, c);
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 1;
c.gridy = 0;
panel.add(optionsBtn, c);
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 1;
panel.add(ownerBtn, c);
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 1;
c.gridy = 1;
panel.add(tenantBtn, c);
this.add(panel);
objectsBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new Object();
}
});
ownerBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//TODO Eigentümer erstellen
}
});
}
}
greets
THE-E
EDIT: Found the bug
I used Seaglass as Look and Feel in the main-method
//Set Theme
try {
UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
It works fine with the default Look and Feel Theme.
I have added the answer in the first post. It was a bug caused by the LookAndFeel skin. :/
greets
THE-E
I have a question regarding making a specific Layout, first I'll show examples then I will add some extra clarification.
Layout when Friends and Messages are closed:
Layout when Friends and Messages are opened:
I intend to make this layout with Java Swing.
My intention is to firstly have the Frame divided in three areas, the top menu row, the main panel and the bottom menu row.
I was thinking of using a BorderLayout for this part.
Then the Friends and Messages buttons should be toggle button's, and on toggle they should show an overlay on top of the mainpanel (or whatever is there), containing a friend list and a message area. I realised I need to use a LayeredPane somehow for this.
Another important part is that the Layout should be viewable in any size, that is the user may resize the application and it will be used on a various amount of resolutions, so I don't really want anything with a fixed width and height.
But I am really lost as how to combine this, so therefore I ask your help.
Hopefully I have explained enough about the situation.
Regards.
this could be about overlay, because JPanel can contains other JComponents
use JLayer (Java7) based on JXLayer(Java6),
use GlassPane with JComponents layed to rellative to....
easiest could be to use JDialog(undecorated) layed to Point (setLocation(int, int)), setVisible() must be wrapped into invokeLater
I will use gridBagLayout.
Here is small example including button which hide your yellow panels:
package Core;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridBagLayoutDemo {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
add1row(pane);
addmainRow(pane);
addLastRow(pane);
}
private static void addLastRow(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.PAGE_END;
JPanel bottonPanel = new JPanel();
bottonPanel.setBackground(Color.BLUE);
bottonPanel.setLayout(new GridBagLayout());
pane.add(bottonPanel, c);
JPanel messagePanel = new JPanel();
messagePanel.setBackground(Color.GRAY);
messagePanel.add(new JLabel("MESSAGES"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_END;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
bottonPanel.add(messagePanel, c);
}
private static void addmainRow(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.CENTER;
JPanel mainManel = new JPanel();
mainManel.setBackground(Color.GREEN);
mainManel.setLayout(new GridBagLayout());
pane.add(mainManel, c);
final JPanel friendListPanel = new JPanel();
friendListPanel.setBackground(Color.YELLOW);
friendListPanel.add(new JLabel("FRIEND LIST"));
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.FIRST_LINE_END;
mainManel.add(friendListPanel, c);
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 1;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.CENTER;
JButton button = new JButton("On/Off");
mainManel.add(button, c);
final JPanel messageAreaPanel = new JPanel();
messageAreaPanel.setBackground(Color.YELLOW);
messageAreaPanel.add(new JLabel("MESSAGE PANEL"));
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 2;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.LAST_LINE_END;
mainManel.add(messageAreaPanel, c);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
friendListPanel.setVisible(!friendListPanel.isVisible());
messageAreaPanel.setVisible(!messageAreaPanel.isVisible());
}
});
}
private static void add1row(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.PAGE_START;
Panel headerPanel = new Panel();
headerPanel.setLayout(new GridBagLayout());
headerPanel.setBackground(Color.BLUE);
pane.add(headerPanel, c);
JPanel quitPanel = new JPanel();
quitPanel.setBackground(Color.GRAY);
quitPanel.add(new JLabel("QUIT"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
headerPanel.add(quitPanel, c);
JPanel friendsPanel = new JPanel();
friendsPanel.setBackground(Color.GRAY);
friendsPanel.add(new JLabel("FRIENDS"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_END;
c.gridx = 1;
c.gridy = 0;
headerPanel.add(friendsPanel, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame);
// uncoment to use full screen
// frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
frame.setSize(new Dimension(400, 400));
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}