Can I increase the size of a JPanel? - java

I have some code here, and when the button is pressed, I'm trying to extend the JPanel. However, it remains at the height it was previously. Is there a way to do this or is it fixed on the dimensions it was set when it was created?
public class GUITest extends JFrame {
JPanel jp;
JButton one;
public static void main(String[] args) {
new GUITest();
}
public GUITest() {
initWidgets();
}
public void initWidgets() {
setSize(250, 250);
setTitle("Stretch Panel Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
one = new JButton("Click me!");
ActionListener extend = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 80; i++) {
jp.setPreferredSize(new Dimension(200,(i+70)));
}
//System.out.println(jp.getHeight());
}
};
one.addActionListener(extend);
add(one, BorderLayout.NORTH);
jp = new JPanel();
jp.setBackground(Color.BLACK);
jp.setPreferredSize(new Dimension(200,70));
add(jp, BorderLayout.CENTER);
setVisible(true);
}
}

alternatively, you can call revalidate() on the jpanel after the button click
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 80; i++) {
jp.setPreferredSize(new Dimension(200,(i+70)));
**jp.revalidate();**
}
//System.out.println(jp.getHeight());
}
to clarify, once you change the dimensions, it has to be redrawn. the thing has been changed, but it hasn't been told to update that change visually

You should use the validate() method in order to do that.
I hope i was able to help!
Have a great day!

try this:
jp.setSize(new Dimension(200,(i+70)));
instead of jp.setPreferredSize(new Dimension(200,(i+70)));
in this code on eachclick the size will be increase by 10 :
ActionListener extend = new ActionListener() {
int count=0;
public void actionPerformed(ActionEvent e) {
count=count+10;
jp.setSize(new Dimension(100+count,70+count));
System.out.println("in listener");
}
};
one more thing setPrefferedsize is the default size which is called whenever component re-validates. to change the setPrefferedSize on each click :
count=count+10;
jp.setSize(new Dimension(100+count,70+count));
jp.setPreferredSize(new Dimension(100+count,70+count));

Related

Create independent objects of a class

I want to create more than one object of a class that are independent one from the other.
I call class constructor multiple time in a for loop, but how can I identify this objects?
I tried using a static variable that takes the value of the for loop index, but this variable assume the value of last index of the for loop.
Here is the code:
Maingui.java
public class Maingui extends JFrame {
public static JFrame frame;
public static JButton runButton;
public Maingui() throws IOException {
frame = new JFrame("maingui");
setSize(1024,700);
setTitle("maingui");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
runButton = new JButton("Run");
runButton.addActionListener(new RunBtnListener());
add(runButton);
}
}
RunBtnListener.java
public class RunBtnListener implements ActionListener {
ArrayList<SecondGui> menus = new ArrayList<SecondGui>();
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 2; i++) {
menus.add(new SecondGui(i));
}
}
}
SecondGui.java
public class SecondGui extends JFrame {
public static int c;
JFrame frame;
JButton button;
public SecondGui(int i) {
this.c = i;
frame = new JFrame("Test");
setSize(1024,700);
setTitle("Menu");
setLocationRelativeTo(null);
setVisible(true);
this.setLocation(50*i, 50*i);
// Set layout manager
setLayout(new BorderLayout());
button = new JButton("B");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("C: " + c);
}
});
add(button);
}
}
When I click on the button button in SecondGui GUI, the output is always 1.
But I want that the output will be 0 or 1 based on in which GUI I select the button.
I want to create more than one object of a class that are independent
one from the other.
Your current code creates 2 independent objects inside this loop
for(int i = 0; i < 2; i++) {
menus.add(new SecondGui(i));
}
But as you made it static, it is not bounded to any instance you creates.
What you need is an instance variable to keep the ID for the SecondGui instance. You can create a new constructor and pass the index of the loop.
public class SecondGui extends JFrame {
private int c = 0;
private JFrame frame;
private JButton button;
public SecondGui(int i) {
this.c = i;
initialize();
}
void initialize() {
frame = new JFrame("Test");
setSize(1024,700);
setTitle("Menu");
setLocationRelativeTo(null);
setVisible(true);
this.setLocation(50*i, 50*i);
// Set layout manager
setLayout(new BorderLayout());
button = new JButton("B");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("C: " + c);
}
});
add(button);
}
}

Why is my showMessageDialog displaying twice?

I am working on a simple counter swing app. I'm trying to make it so when you click the check box, it will stay on the top and display a message dialog being "On Top" or "Not On Top".
However, when I click the checkbox after compiling and running, both of the messages display, and after clicking OK on both messages, the checkbox isn't even enabled. If I were to remove the showMessageDialog, it would still function properly, but I want to learn how to appropriately implement this.
Thank you in advance. Here is all of the code for the program:
public Class Counter {
JFrame frame;
JPanel panel;
JButton button, clear;
JTextField textC;
JLabel label;
JCheckBox cbox;
boolean topC = false;
int icount = 0;
String scount;
String topStatus = "";
public Counter() {
gui();
setActions();
}
public void gui() {
frame = new JFrame("Counter Program");
panel = new JPanel();
label = new JLabel("Counter");
textC = new JTextField();
textC.setPreferredSize(new Dimension(72,28));
textC.setEditable(false);
button = new JButton("Click");
clear = new JButton("Clear");
cbox = new JCheckBox("Top");
frame.setSize(350,80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
panel.add(label);
panel.add(textC);
panel.add(button);
panel.add(clear);
panel.add(cbox);
frame.setVisible(true);
}
public void setActions() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
icount++;
scount = Integer.toString(icount);
textC.setText(scount);
}
});
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
icount = 0;
textC.setText("");
}
});
cbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
topC = !topC;
if (topC) {
topStatus = "Top";
}
else topStatus = "Not Top";
frame.setAlwaysOnTop(topC);
JOptionPane.showMessageDialog(frame, topStatus, "Top Setting", 1);
}
});
}
public static void main(String[]args) {
new Counter();
}
}
An ItemListener generates two events, one for the selection and one for the unselection (and vice versa). Read the section from the Swing tutorial on How to Write an ItemListener for more information and working exmaples if you really want to use an ItemListener.
Otherwise, use an ActionListener instead, it will only generate a single event.

Action listener java problems

Ok so im working on a game and right now i have an image and im trying to place buttons under the image in specific places so when the user clicks that part of the screen the image changes. I am having trouble trying to figure out how to format my program for the action listener.
public class TestJFrame{
private static JFrame frame = new JFrame();
private static JLabel label = new JLabel();
private static JButton buttons[] = new JButton[4];
private static int[][] location = new int[3][4];
public static void main(String args[]){
frame.getInsets().set(20, 5, 5, 5);
frame.setLayout(null);
frame.setPreferredSize(new Dimension(507, 528));
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test");
buttons[0] = new JButton("jbZero");
buttons[1] = new JButton("jbOne");
buttons[2] = new JButton("jbTwo");
buttons[3] = new JButton("jbThree");
frame.add(buttons[0]);
frame.add(buttons[1]);
frame.add(buttons[2]);
frame.add(buttons[3]);
setButtons();
frame.setVisible(true);
buttons[0].setLocation(100, 100);
}
private static void setButtons(){
for (int i=0;i<=3;i++){
buttons[i].setSize(10, 10);
buttons[i].setLocation(0, 0);
buttons[i].setVisible(true);
}
}
public void intializeListener(){
buttons[0].addActionListener((ActionListener) this);
}
public void buttonsZeroActionPreformed(java.awt.event.ActionEvent e){
System.out.println("button zero works");
}
}
So any help would be greatly appreciated.
Depends what do you want to implement in the listener:
If they do the same action you implement the listener inside setButtons function:
private static void setButtons(){
for (int i=0;i<=3;i++){
buttons[i].setSize(10, 10);
buttons[i].setLocation(0, 0);
buttons[i].setVisible(true);
buttons[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// listener implement btn 0
}
});
}
}
If each button need unique implementation I think that better implementation will be in a new function setBtnListeners and call it from your main after using setButtons();:
private static void setBtnListeners() {
buttons[0].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// listener implement btn 0
}
});
}
Update: Sorry i'd just noticed you have four buttons... you can just add another one :)

Cannot find a way to create a loading screen

I was just messing around with GUI in Java and created a little game. In it, 105 randomly placed buttons are created and then an instruction screen pops up, telling the user which button to find. I've tried to figure out how to program a "Loading..." JDialog, which will pop up while the buttons are being created in the background. The trouble is, when I run the program the JDialog doesn't load until AFTER all the buttons have been created, which kind of defeats the purpose of the box in the first place. How can I force the "Loading..." box to load BEFORE the buttons begin to be created??? Thanks in advance.
Because I've just been tinkering, my code is not perfect but here it is:
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.ProgressMonitor;
public class ButtonGame {
private static int butNum = 1;
private static JFrame frame;
private static ActionListener notIt;
private static ActionListener it;
private static Random rand = new Random();
private static int butToFind = rand.nextInt(105);
private static JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
//actionlistener for all incorrect buttons (buttons that are "not it")
notIt = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame5 = (JFrame) SwingUtilities.getRoot(component);
frame5.dispose();
}
};
//actionlistener for the correct button (the button that's "it")
it = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame youWin = new JFrame("YOU WON!");
//removes all panels to begin game again
JButton again = new JButton("Play again");
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
java.awt.Window windows[] = java.awt.Window.getWindows();
for(int i=0;i<windows.length;i++){
if (windows[i] != frame) { windows[i].dispose(); }
butToFind = rand.nextInt(105);
butNum = 1;
youWin.dispose();
}
frame.setVisible(true);
}
});
//quits game
JButton win = new JButton("Quit");
win.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//layout
youWin.setSize(775, 300);
youWin.setLayout(new FlowLayout());
JLabel label1 = new JLabel("Fantastic!");
Font font1 = new Font("Courier", Font.BOLD,120);
label1.setFont(font1);
label1.setHorizontalAlignment(JLabel.CENTER);
JLabel label2 = new JLabel("You beat the game!");
Font font2 = new Font("Courier", Font.BOLD,60);
label2.setFont(font2);
label2.setHorizontalAlignment(JLabel.CENTER);
youWin.add(label1);
youWin.add(label2);
JPanel panel = new JPanel();
youWin.add(panel);
panel.add(again);
panel.add(win);
youWin.setLocation(260, 100);
youWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
youWin.setVisible(true);
java.awt.Window windows[] = java.awt.Window.getWindows();
}
};
//start window
frame = new JFrame("Window");
frame.setLocation(400, 200);
JButton button1 = new JButton("Click to begin");
//button to begin game
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JDialog load = new JDialog();
// load.setAlwaysOnTop(true);
// load.setSize(500,500);
// load.setVisible(true);
// load.add(new Label("Loading..."));
// load.pack();
frame.setVisible(false); // "start" window's visibility
// try {
// Thread.sleep(100000);
// } catch (Exception t) {
// }
// creates buttons
for (int i = 0; i < 105; i++) {
JFrame nextFrame = newFrame(butNum);
nextFrame.setVisible(true);
butNum++;
}
//creates instructions and tells user what button to find
JFrame instructions = new JFrame("How to play");
instructions.setSize(300,175);
instructions.setLayout(new GridLayout(4,1));
JPanel instPanel = new JPanel();
//button to remove instruction panel
JButton ok = new JButton("Ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
instructions.dispose();
}
});
instPanel.add(ok);
instructions.setLocation(400,200);
//layout of instruction panel
JLabel find = new JLabel("Your goal is to find Button " + butToFind + ".");
find.setHorizontalAlignment(JLabel.CENTER);
JLabel find2 = new JLabel("Click a button to make it disappear.");
find2.setHorizontalAlignment(JLabel.CENTER);
JLabel find3 = new JLabel("Good luck!");
find3.setHorizontalAlignment(JLabel.CENTER);
instructions.add(find);
instructions.add(find2);
instructions.add(find3);
instructions.add(instPanel);
instructions.setVisible(true);
}
});
frame.add(button1);
frame.setSize(150,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//creates frame with button in it
public static JFrame newFrame(int num) {
JFrame frame2 = new JFrame();
JButton button = new JButton("Button " + num);
if (num == butToFind) {
button.addActionListener(it);
frameToClose = frame2;
} else {
button.addActionListener(notIt);
}
frame2.add(button);
frame2.setSize(randNum(90,200), randNum(50,100));
frame2.setLocation(rand.nextInt(1200), rand.nextInt(800));
frame2.getContentPane().setBackground(new Color(rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255)));
frame2.setVisible(true);
return frame2;
}
//provides random number between high and low
public static int randNum(int low, int high) {
int result = -1;
while (result < low || result > high) {
result = rand.nextInt(high);
}
return result;
}
}
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static? Thanks!
First take a look at The Use of Multiple JFrames, Good/Bad Practice? and understand why I freaked out when I ran your code...
Instead of creating a bunch of frames, why not use something like JButton on another JPanel and add it to the current frame (this would also be a good use for a CardLayout)
JPanel panel = new JPanel(new GridLayout(10, 0));
Random rnd = new Random();
// creates buttons
for (int i = 0; i < 105; i++) {
JButton btn = new JButton(String.valueOf(i));
panel.add(btn);
//JFrame nextFrame = newFrame(butNum);
//nextFrame.setVisible(true);
//butNum++;
}
frame.getContentPane().removeAll();
frame.add(panel);
frame.revalidate();
frame.pack();
Alternatively, if you're really hell bent on using "frames", consider using a JDesktopPane and JInternalFrame instead.
See How to Use Internal Frames for more details
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static?
As much as possible, none. Instead of trying to create the whole thing in the main method, use the classes constructor to initialise the UI and use another method to actually get the game rolling...
public class ButtonGame {
private int butNum = 1;
private JFrame frame;
private ActionListener notIt;
private ActionListener it;
private Random rand = new Random();
private int butToFind = rand.nextInt(105);
private JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
ButtonGame game = new ButtonGame();
game.start();
}
public ButtonGame() {
//... All the code that was once in main...
frame.add(button1);
frame.setSize(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
frame.setVisible(true);
}
Answering to your side questions:
a static method can only accept static global variables
You can put all your code in the constructor and use main to only run the program.
Constructor:
public ButtonGame() {
// All of your code goes here - except the static methods
}
You should also make all other methods non-static.
To run the program:
public static void main(String[] args) {
new ButtonGame();
}

How do I hide the current JPanel and show a new one with a button in Java?

I unfortunately have to use multiple windows in this program and I don't think CardLayout is going to work because I can't have any buttons constant between the different layouts. So I'm trying to code a button to hide the present JPanel (thePanel) and show a new one (thePlacebo).
I'm trying to hide thePanel in an ActionListener like this:
frame.getContentPane().remove(thePanel);
I thought this would work, but it just freezes my program as soon as I hit the button.
Here's a chunk of the code for context:
public class Reflexology1 extends JFrame{
JButton button1, button2;
JButton movingButton;
JTextArea textArea1;
int buttonAClicked, buttonDClicked;
private long _openTime = 0;
private long _closeTime = 0;
JPanel thePanel = new JPanel();
JPanel thePlacebo = new JPanel();
final JFrame frame = new JFrame("Reflexology");
public static void main(String[] args){
new Reflexology1();
}
public Reflexology1(){
frame.setSize(600, 475);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Reflexology 1.0");
frame.setResizable(false);
button1 = new JButton("Accept");
button2 = new JButton("Decline");
movingButton = new JButton("Click Me");
ListenForAcceptButton lForAButton = new ListenForAcceptButton();
ListenForDeclineButton lForDButton = new ListenForDeclineButton();
button1.addActionListener(lForAButton);
button2.addActionListener(lForDButton);
//movingButton.addActionListener(lForMButton);
JTextArea textArea1 = new JTextArea(24, 50);
textArea1.setText("Tracking Events\n");
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
textArea1.setSize(15, 50);
FileReader reader = null;
try {
reader = new FileReader("EULA.txt");
textArea1.read(reader, "EULA.txt");
} catch (IOException exception) {
System.err.println("Problem loading file");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
AdjustmentListener listener = new MyAdjustmentListener();
thePanel.add(scrollBar1);
thePanel.add(button1);
thePanel.add(button2);
thePlacebo.add(movingButton);
frame.add(thePanel);
ListenForWindow lForWindow = new ListenForWindow();
frame.addWindowListener(lForWindow);
frame.setVisible(true);
}
// Implement listeners
private class ListenForAcceptButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
Calendar ClCDateTime = Calendar.getInstance();
System.out.println(ClCDateTime.getTimeInMillis() - _openTime);
_closeTime = ClCDateTime.getTimeInMillis() - _openTime;
frame.getContentPane().remove(thePanel);
}
}
}
Does anybody know what I might be doing wrong?
After removing components from a container, it goes into the invalidate state. To bring it back to the valid state you have to revalidate and repaint that. In your case you are directly adding/removing components from JFrame so depending on the Java version you can do this :
frame.revalidate(); // For Java 1.7 or above
frame.getContentPane().validate(); // For Java 1.6 or below
frame.repaint();
Here is one working example for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Assignment
{
private JFrame frame;
private JPanel firstPanel;
private JPanel secondPanel;
private JButton forwardButton;
private JButton backButton;
private void displayGUI()
{
frame = new JFrame("Assignment");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstPanel = new JPanel();
firstPanel.setOpaque(true);
firstPanel.setBackground(Color.BLUE);
secondPanel = new JPanel();
secondPanel.setOpaque(true);
secondPanel.setBackground(Color.RED);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.remove(firstPanel);
frame.add(secondPanel);
frame.revalidate(); // For Java 1.7 or above.
// frame.getContentPane().validate(); // For Java 1.6 or below.
frame.repaint();
}
});
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.remove(secondPanel);
frame.add(firstPanel);
frame.revalidate(); // For Java 1.7 or above.
// frame.getContentPane().validate(); // For Java 1.6 or below.
frame.repaint();
}
});
firstPanel.add(forwardButton);
secondPanel.add(backButton);
frame.add(firstPanel);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Assignment().displayGUI();
}
});
}
}
correct way could be (only) by using CardLayout
otherwise have to remove JPanel from container and to call (as last code line and call only one times after all changes for container are done)
.
myJPanelsContainer#revalidate(); // in Java6 for JFrame validate()
myJPanelsContainer#repaint();

Categories