How do I display multiple JPanels with multiple layouts? - java

I've been working on this project for an assignment and I've been stuck on this problem. I new and don't understand much of the programming jargon so if someone could help explain why my program isn't working that would be great.
The programs purpose is to display a randomly generated matrix of 1's and 0's in a 10x10 layout and have some buttons on the top that have functions. I'm just stock on how to get everything to display.
Thanks in advance.
UPDATE:: Told providing all my code would help
public class Module5 extends JFrame {
private static JTextArea area = new JTextArea();
private static JFrame frame = new JFrame();
private static JPanel general = new JPanel();
private static JPanel buttons = new JPanel();
private static JPanel numbers = new JPanel();
private static JButton button0 = new JButton("Reset to 0");
private static JButton button1 = new JButton("Resset to 1");
private static JButton buttonReset = new JButton("Reset");
private static JButton quit = new JButton("Quit");
public static class Numbers extends JPanel {
public Numbers() {
area.setText(Integer.toString((int) Math.round(Math.random())));
this.add(area);
}
public void Module5(){
numbers.setLayout(new GridLayout(10, 10));
for (int i = 0; i < 100; i++) {
this.add(new Numbers());
}
}
}
public static void main (String[] args) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
general.setLayout(new BoxLayout(general, BoxLayout.Y_AXIS));
general.add(buttons);
general.add(numbers);
buttons.add(button0);
buttons.add(button1);
buttons.add(buttonReset);
buttons.add(quit);
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
}

Since this does look like homework I'll give you some pointers but am not going to give you the code.
Move your constructor for Module5 out of the numbers class and into its own class. Also remove the void return type from this to make it a correct constructor.
Move the code in your main into the constructor for Module5. This is the main frame so when you build a new one it should be initialised here, not in main. And remove the setVisible call for now (this is addressed in number 6)
After doing 1 and 2, get rid of your frame variable, your Module5 is a JFrame so anything to do with frame can just be changed to the keyword this (meaning this Module5 object)
Also move the area variable to be within the Numbers class - otherwise every Number is essentially going to share the same text area and This is not what you want.
Don't have your variables as static they should not need to be.
Once this is all done make sure it is running on the Event Dispatch Thread by making your main method like this (the one piece of code I will give you)
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
Module5 mod5 = new Module5();
mod5.setVisible(true);
}
});
}

Related

Extending variable scope from one frame to another frame

I have two JFrame based windows: SeatLayout and BillSummary. I need to get the seatnumber from the SeatLayout frame and display it in BillSummary but the variable scope is limited to the first frame.
How can I do this?
Using multiple JFrame is a bad practice and it should be avoided.
Reason being, it will add more problems in the future and it will be nightmare to maintain.
To answer your question , how to pass variable from your parent(JFrame) to a child(JDialog) .This can achive by using JDialog.
I am going to run through an example.
lets say, your BillSummary.java is ....
//BillSummary Class
public class billSummary {
JFrame frame;
billSummary(JFrame frame) {
this.frame = frame;
}
public void launchbillSummary(int seatNumber) {
// Create a dialog that suits your ui , you can use JPanel as your layout container
JDialog dialog = new JDialog(frame, "Bill Summary", true);
dialog.setLayout(new BorderLayout());
dialog.setSize(100, 100);
dialog.add(new JLabel(Integer.toString(seatNumber)), BorderLayout.CENTER);
dialog.setVisible(true);
}
}
Your seatLayout.java
public class seatLayout {
seatLayout(){
//Lets say you have seleted seat number 10
int defaultSeatNumber = 10;
//Lets say you have a button and when it is clicked , you pass the data to billsummary page
JButton enter = new JButton("Enter");
//Your seatLayout GUI
JFrame frame = new JFrame("seat layout");
frame.setSize(300,300);
frame.add(enter);
enter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//Do your passing of data/ price of calculation here
//You pass the data that to your custom dialog -> Bill summary
new billSummary(frame).launchbillSummary(defaultSeatNumber);
}
});
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new seatLayout();
}
});
}
}
I hope this help and answers your question. Good luck :)

reusing action listener and jframe in main class

So if someone would take a look at the code below and give me hand I would owe you my life. So here's the issue, obviously I can get this to work if I were to put playerCreationSelectionin its own class, my questions is getting it to work, inside class superClass I cannot for the life of me move things around to make it work. Any help would be great, thanks everyone!
forgot to actually put what goes wrong! So what will happen is it says playerCreationSelection is not a symbol
public class superClass
{
public static void main(String[] args)
{
playerCreationSeletion gui = new playerCreationSeletion();
}
public class playerCreateSelection extends JFrame implements ActionListener
{
//create label
public JLabel playerCreatedLabel;
public void playerCreationSeletion()
{
setSize(WIDTH,HEIGHT);
WindowDestroyer listener = new WindowDestroyer();
addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setLayout(new FlowLayout());
//create button
JButton playerCreationButton = new JButton("Create New Player");
playerCreationButton.addActionListener(this);
contentPane.add(playerCreationButton);
//create label
playerCreatedLabel = new JLabel("Welcome New Player!");
playerCreatedLabel.setVisible(false);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
Container contentPane = getContentPane();
if(actionCommand.equals("Create New Player"))
{
contentPane.setBackground(Color.LIGHT_GRAY);
playerCreatedLabel.setVisible(true);
}
}
}
}
Well, you have a typo "playerCreationSeletion()". Also, You need to call an inner class constructor like this and use setVisible and setSize.
public static void main(String[] args) {
playerCreateSelection gui = new superClass().new playerCreateSelection();
gui.setSize(500, 500);
gui.setVisible(true);
}
Try that.

int and boolean not changing after action performed

I copied all of the relevant code below, and my problem is that after running the action performed (which is connected to a button) the values I tried to change in the action performed didn't actually change.
I put a sout(ques) at the end of the action performed and I can see the change in value but when I move outside of it, it reverts back to the 0;
public class GameRunner extends JPanel implements ActionListener{
private int x=50,y=600;
private Ball b = new Ball(x,y);
private Timer timer;
private boolean correct , incorrect;
private JButton button;
private JTextField f;
private int ques = 0;
private String[][] math = {{"2X^2","4x"},{"q2","a2"},{"q3","a3"},{"q4","a4"},{"q5","a5"},
{"q6","a6"},{"q7","a7"},{"q8","a8"}};
public void actionPerformed(ActionEvent actionEvent) {
if (f.getText().equals(math[ques][1])) {
correct = true;
} else {
incorrect = true;
}
f.setText("");
if(ques<7)
ques++;
else
ques = 0;
System.out.println(ques);
//I can see the change here
}
public void paint(Graphics g){//called whenever refreshed...
System.out.println(ques);
// But now outside of the action performed the ques and the correct incorrect do not change
if(correct)
b.move();
if(incorrect)
b.move2();
}
public static void main(String[] args) {
GameRunner gui = new GameRunner ();
gui.go();
}
public void go(){
button = new JButton("Guess");
f = new JTextField(15);
button.addActionListener(this);
JFrame frame = new JFrame("Derivative Game");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(700, 700));
JPanel pan = new JPanel(new BorderLayout());
JPanel pan2 = new GameRunner();
JPanel pan3 = new JPanel();
pan3.add( f);
pan3.add(button);
pan3.setBackground(new Color(80, 218, 213));
pan.add( pan3,BorderLayout.CENTER);
pan.setBackground(new Color(80, 218, 213));
frame.add(pan2);
frame.getContentPane().add(BorderLayout.SOUTH, pan);
frame.setSize(700, 760);
frame.setVisible(true);
frame.setResizable(false);
}
}
The basic problem is that you've actually got two instances of GameRunner here: the one you create in main(), and another one that you add to the JFrame. Since you only call go() on the one not in the JFrame, that instance's paint() method will never be called.
You need to refactor your code to eliminate that second stray GameRunner instance. While you're at it, you should also use paintComponent() instead of paint(), and you should take any "business logic" (like those calls to move()) out of your painting code.
In other words, get rid of this line:
JPanel pan2 = new GameRunner();
Since you're already "in" an instance of GameRunner, you shouldn't be creating another one. Then to use the "current" instance of GameRunner, you can use the this keyword:
frame.add(this);
Edit- You also aren't telling your GameRunner JPanel to repaint itself after the button is clicked. You might want to add a call to repaint() in your actionPerformed() method.

using listeners with both list and button

Very new to Java, but I am slowly picking my way through things. So please be kind. I understand most things I've tried so far, and built a version of the following that uses console output, but now I'm trying to make a GUI. I tried the netbeans GUI maker, but it created so much new code that when I tried to pick through it, I got lost. I'm much better at learning by piecing new things together myself, not having an IDE generate a ton of code and then attempt to find where I want to work.
I am trying to build an window that has a list with three choices on the left side, a button in the middle that confirms your choice, and an answer output on the right. Once the button is pressed, the input from the list is read and is converted into a corresponding answer. As of right now, all I get is "We recommend... null" after selecting an option in the list. The button appears to do nothing at the moment.
I have used tutorials, hacked up others' code from online, and referenced a few books, but I'm stuck.
Here is what I have:
package diffguidegui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DiffGuideGUI extends JPanel implements ListSelectionListener {
private JList resultsTabList;
private DefaultListModel listModel;
private static final String recommendString = "Recommend a Option";
private JButton recommendButton;
private String recommendOutput;
final JLabel output = new JLabel("We recommend..." + recommendOutput);
//build list
public DiffGuideGUI () {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("A");
listModel.addElement("B");
//create the list and put it in the scroll pane
resultsTabList = new JList(listModel);
resultsTabList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultsTabList.setSelectedIndex(0);
//listener for user input
resultsTabList.addListSelectionListener(this);
resultsTabList.setVisibleRowCount(2);
JScrollPane listScrollPane = new JScrollPane(resultsTabList);
//build the button at the bottom to fire overall behavior
recommendButton = new JButton(recommendString);
recommendButton.setActionCommand(recommendString);
recommendButton.addActionListener(new RecommendListener());
//create a panel that uses Boxlayout for the button
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(recommendButton);
//create a panel that uses Boxlayout for the label
JPanel outputPane = new JPanel();
outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.LINE_AXIS));
outputPane.add(output);
add(listScrollPane, BorderLayout.WEST);
add(buttonPane, BorderLayout.CENTER);
add(outputPane, BorderLayout.EAST);
}
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
}
}
public void valueChanged(ListSelectionEvent e) {
if(e.getValueIsAdjusting() == false) {
if(resultsTabList.getSelectedIndex() == -1) {
recommendButton.setEnabled(false);
} else {
recommendButton.setEnabled(true);
}
}
}
//Create GUI and show it
private static void createAndShowGUI() {
JFrame frame = new JFrame("Recommend Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create and set up content pane
JComponent newContentPane = new DiffGuideGUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The button appears to do nothing at the moment.
It does something. It calculates the value for your recommendOutput varable. But you never output this value.
try the following:
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
System.out.println(recommendOutput); // <-###################
}
}
This should print the value to stdout
To put the value into your label try this instead:
output.setText(recommendOutput);
where do you set the text for the JLabel? It says "We recommend NULL" because recommenedOutput is null when the object is created. I dont see
output.setText("We recommend "+value) anywhere. You probably need output.invalidate() also. Try putting setText(String text)/invalidate() in the RecommendListener.actionPerformed() method.
output.setText("We recommend A");
output.invalidate();

Only one component shows up in JFrame

As an improvement to my encryption project I decided to make a little GUI. However, when I run the program, only the top element shows up on the screen and it appears to obscure the others, though I have no way of checking. Does anyone know why?
Below is my code in its entirety besides e() and d() because those simply encrypt a string and have nothing to do with a GUI. I would also like a way to speed it up as much as possible without editing the encryption, just to make it as great as possbile.
#SuppressWarnings("serial")
public class EncDecExample extends JFrame implements ActionListener {
final static JPanel top = new JPanel();
final static JPanel mid = new JPanel();
final static JPanel bot = new JPanel();
final static JTextField in = new JTextField(10);
final static JTextField out = new JTextField(10);
final static JButton enc = new JButton("Encrypt");
final static JButton dec = new JButton("Decrypt");
final static JFrame f = new JFrame("Encryption/decryption");
public static void main(String[] args) {
// EncDec.exampleImplement();
f.setSize(500, 500);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
out.setEditable(false);
out.setText("Hello");
in.setVisible(true);
out.setVisible(true);
enc.setVisible(true);
dec.setVisible(true);
top.add(in);
mid.add(enc);
mid.add(dec);
bot.add(out);
f.add(top);
f.add(mid);
f.add(bot);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == enc && !in.getText().equalsIgnoreCase("")) {
out.setText(EncDec.e(in.getText(), 5));
}
else if(e.getSource() == dec && !in.getText().equalsIgnoreCase("")) {
out.setText(EncDec.d(in.getText()));
}
}
}
The content pane of a JFrame has a BorderLayout. If you place a component in a BL with no constraints it ends up in the CENTER. The center can only display one component.
For an immediate effect, I suggest:
f.add(top, BorderLayout.PAGE_START);
f.add(mid);
f.add(bot, BorderLayout.PAGE_END);
Other points.
Take out f.setSize(500, 500); and call pack() immediately before setVisible(true)
For a better way to end the GUI, change f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
in.setVisible(true); Except for the frame itself, take these out. A component automatically becomes visible when it is added to a top level container and that container is itself made visible.
Change public class EncDecExample extends JFrame to public class EncDecExample This code keeps a reference to a frame, and that is the right way to go.

Categories