Creating a Panel of Button GUI - java

I'm trying to create a board for a game, i first made a frame then if the user //enters the rows and columns as numbers and pushes the start button, it should remove all //whats on frame and add a panel with a grid layout having buttons everywhere
Here is the code ( Problem is the frame gets cleared and nothing appears)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JButton newButton;
JButton Start;
JTextArea row;
JTextArea col;
JLabel background;
JLabel rows;
JLabel columns;
JLabel Error;
JPanel myPanel;
JCheckBox box;
public Frame()
{
//adding frame
setTitle("DVONN Game");
setSize(1000, 700);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
//making start button
Start = new JButton(new ImageIcon("Start"));
Start.setBounds(500, 30, 300, 300);
Start.setOpaque(true);
Start.addActionListener(this);
//make background
background = new JLabel();
background.setBounds(0, -300, 2000, 1500);
background.setIcon(Color.BLUE));
rows = new JLabel("Enter the rows");
columns = new JLabel("Enter the columns");
rows.setForeground(Color.WHITE);
columns.setForeground(Color.WHITE);
rows.setBounds(10,10,100,30);
columns.setBounds(10,45,105,30);
row = new JTextArea();
col = new JTextArea();
row.setBounds(120,10,100,30);
col.setBounds(120,45,100,30);
Error = new JLabel("Enter numbers plz!");
Error.setBounds(10, 100, 400, 30);
Error.setForeground(Color.RED);
Error.setVisible(true);
box = new JCheckBox("Enable Random Filling");
box.setBounds(10, 200, 150, 20);
box.setVisible(true);
myPanel = new JPanel();
myPanel.setBounds(30, 30, 700, 500);
myPanel.setVisible(true);
newButton = new JButton();
newButton.setOpaque(true);
getContentPane().add(box);
getContentPane().add(rows);
getContentPane().add(columns);
getContentPane().add(row);
getContentPane().add(col);
getContentPane().add(Start);
getContentPane().add(background);
this.validate();
this.repaint();
}
public static void main(String[]args)
{
new Frame();
}
//adding actions for start button
public void actionPerformed(ActionEvent e) {
boolean flag = true;
String r1 = row.getText();
String c1 = col.getText();
int x = 0,y = 0;
try{
x = Integer.parseInt(r1);
y = Integer.parseInt(c1);
} catch(NumberFormatException l) {
flag = false;
}
int size = x * y;
if (flag == true) {
this.getContentPane().removeAll();
this.validate();
this.repaint();
myPanel.setLayout(new GridLayout(x, y));
while(size != 0)
{
myPanel.add(newButton);
size --;
}
this.getContentPane().add(myPanel);
} else {
this.getContentPane().add(Error);
}
}
}

There are several issues with this code
Is it really needed to post that much code. A simple UI with one button to press, and then another component which should appear would be sufficient for an SSCCE
The use of null layout's. Please learn to use LayoutManagers
Each Swing component can only be contained once in the hierarchy. So this loop is useless since you add the same component over and over again (not to mention that a negative size would result in an endless loop)
while(size != 0){
myPanel.add(newButton);
size --;
}
Have you tried debugging to see whether size is actually >0. Since you silently ignore ParseExceptions you might end up with a size of 0 which will clean the content pane and add nothing
Then do as goldilocks suggests and call validate after adding the components. See the javadoc of the Container#add method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.

Call validate() and repaint() after the new elements have been added instead of after the old ones have been removed.
You don't need to be calling setVisible() on individual components, call it after pack() on the Frame itself, and you shouldn't use validate() and repaint() in the constructor. Ie, replace those with:
pack();
setVisible(true);
or you can do that on the object after the constructor is called.

Try to replace
public static void main(String[]args)
{
new Frame();
}
by
public static void main(String[]args)
{
new Frame().setVisible(true);
}

Remove the call to this.setVisible in the constructor and make this your main method.
public static void main(String[] args) {
final Frame fr = new Frame();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
fr.setVisible(true);
}
});
}
This will make sure that the frame elements will be in place before it becomes visible.

Related

Why i need to click twice to let my JButton work?

I'm building a program that draws random (User input) rectangles on a JPanel.
Problem 1:
Whenever I type a number in my JTextfield,I need to click twice on
the JBUtton for Rectangles to show up.
Problem 2:
When i type a new number in the JTextField the number of that don't
show the rectangle but it shows the rectangles I typed in previous.
CODE:
private void init() {
final int FRAME_WIDHT = 800;
final int FRAME_HEIGHT = 1000;
int input = 3;
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDHT, FRAME_HEIGHT);
frame.setTitle("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
west = new JPanel();
west.setSize(500, 500);
west.setBorder(BorderFactory.createLineBorder(Color.black));
east = new JPanel();
east.setSize(300, 1000);
button = new JButton("Add squares");
field = new JTextField(10);
button.setSize(100, 50);
east.add(button);
east.add(field);
east.setBorder(BorderFactory.createLineBorder(Color.black));
button.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton1ActionPerformed(evt);
}
public void JButton1ActionPerformed(ActionEvent evt) {
int aantalRect = Integer.parseInt(field.getText());
MyDrawing draw = new MyDrawing(aantalRect);
west.add(draw);
draw.revalidate();
draw.repaint();
}
});
frame.add(west, BorderLayout.CENTER);
frame.add(east, BorderLayout.EAST);
frame.setResizable(true);
frame.setVisible(true);
}
public static void main(String[] a) {
P1027 form = new P1027();
}
}
class MyDrawing extends JPanel {
int input = 0;
public MyDrawing(int i) {
this.input = i;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Random r = new Random();
setPreferredSize(new Dimension(500, 1000));
for (int i = 0; i < input; i++) {
int x = r.nextInt(460);
int y = r.nextInt(960);
g.drawRect(x, y, 40, 40);
}
}
Can any one tell me how to fix that?
Problem 1: You're not be seeing the squares being drawn on your MyDrawing JPanel the first time because you are calling the setPreferredSize(...) method, when you really should be overriding the getPreferredSize() method as explained by this answer. It is also possible that they are being drawn off-screen. You set the preferred height of MyDrawing to 1000, which doesn't fit on my laptop's screen (The green line is the border of a MyDrawing).
To fix Problem 1, override the method and lower the preferred height if necessary:
class MyDrawing extends JPanel {
... //Constructor
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500); //Changed from 1000 to 500
}
... //paintComponent(...)
//If you change 1000 to 500, don't forget to change 960 to 460 too
}
Problem 2: You're seeing the amount of rectangles you typed into the JTextField previously because:
You are forgetting to remove the previously added MyDrawing from west before adding the new one.
You are calling revalidate() and repaint() on draw when you should be calling it on its parent component, west.
To fix problem 2, remove the old MyDrawing from west, add the new one, then call revalidate() and repaint():
...
public void JButton1ActionPerformed(ActionEvent evt) {
west.removeAll(); //If the old MyDrawing is the only thing
//that has been added to west. Otherwise use
//remove(int index) or remove(Component comp)
west.add(draw);
west.revalidate();
west.repaint();
}
...
Other things:
You switched the T and H around in FRAME_WIDTH.
You could put the code in JButton1ActionPerformed(...) into the actual actionPerformed method.
Your JFrame looks exactly the same with and without the calls to setSize(...) on west, east, and button and that answer I mentioned earlier suggests not using those methods, so consider removing them.

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.

Trying to display images in multiple JPanels

I'm creating a program that features a grid of 12 JPanels. When the "add image" button is pressed, an image appears in the first JPanel in the grid and a counter is incremented by one. From then onwards, every time the "add image" is clicked again, an image would be added to the next JPanel. For some reason, the button only adds an image to the first JPanel and then stops working. Here's the code I've got so far.
public class ImageGrid extends JFrame {
static JPanel[] imageSpaces = new JPanel[12];
int imageCounter = 0;
ImageGrid() {
this.setTitle("Image Grid");
setSize(750, 750);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(3, 4, 10, 5));
p3.setBackground(Color.WHITE);
p3.setOpaque(true);
p3.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
for (int j = 0; j < imageSpaces.length; j++) {
imageSpaces[j] = setImageSpace();
p3.add(imageSpaces[j]);
}
MyButtonPanel p1 = new MyButtonPanel();
add(p1, BorderLayout.SOUTH);
add(p3, BorderLayout.CENTER);
}
public JPanel setImageSpace() {
JPanel test;
test = new JPanel();
test.setOpaque(true);
test.setPreferredSize(new Dimension(100, 100));
return test;
}
class MyButtonPanel extends JPanel implements ActionListener {
final JButton addImage = new JButton("Add Image");
ImageIcon lorryPicture = new ImageIcon(ImageGrid.class.getResource("/resources/lorry.png"));
JLabel lorryImage = new JLabel(lorryPicture);
MyButtonPanel() {
add(addImage);
addImage.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addImage) {
imageSpaces[imageCounter].add(lorryImage);
revalidate();
repaint();
imageCounter++;
}
}
}
public static void main(String[] args) {
ImageGrid test = new ImageGrid();
test.setVisible(true);
}
}
You should be revalidating and repainting the panel, (which is the containter being affected by the addition), not the frame
imageSpaces[imageCounter].add(lorryImage);
imageSpaces[imageCounter].revalidate();
imageSpaces[imageCounter].repaint();
Diclaimer: This may work as a simple fix, but also note that a component (in this case your JLabel lorryImage) can only have one parent container. The reason the above fix still works is because you don't revalidate and repaint the previous panel, the label was added to. So you may want to think about doing it correctly, and adding a new JLabel to each panel.
if (e.getSource() == addImage) {
JLabel lorryImage = new JLabel(lorryPicture);
imageSpaces[imageCounter].add(lorryImage);
imageSpaces[imageCounter].revalidate();
imageSpaces[imageCounter].repaint();
imageCounter++;
}
Disclaimer 2: You should add a check, to only add a label if the count is less than the array length, as to avoid the ArrayIndexOutOfBoundsException
Side Notes
Swing apps should be run from the Event Dispatch Thread (EDT). You can do this by wrapping the code in the main in a SwingUtilities.invokeLater(...). See more at Initial Threads
You could also just use a JLabel and call setIcon, instead of using a JPanel

Resize JButtons in a BoxLayout

I'm trying to make a simple menu for my game. I have 4 buttons in the center and I want to make them a little bit bigger and center them.
The last part worked but I can't seem to call any of my JButtons and do a .setSize / .setPreferedSize(new Dimension()) on it.
public class mainMenu extends JFrame {
private JButton start, highscore, help, stoppen;
public mainMenu() {
super("Master Mind");
maakComponenten();
maakLayout();
toonFrame();
}
private void maakComponenten() {
start = new JButton("Start");
start.setBackground(Color.gray);
highscore = new JButton("Higscores");
help = new JButton("Help");
stoppen = new JButton("Stoppen");
}
private void maakLayout() {
JPanel hoofdmenu = new JPanel();
hoofdmenu.setLayout(new BoxLayout(hoofdmenu, BoxLayout.Y_AXIS ));
hoofdmenu.add(start);
start.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(highscore);
highscore.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(help);
help.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(stoppen);
stoppen.setAlignmentX(CENTER_ALIGNMENT);
super.add(hoofdmenu);
}
private void toonFrame() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args) {
new mainMenu();
}
}
As an example, to change the size of the "Start" button,
change :
start1 = new JButton("Start");
to
start1 = new JButton("Start") {
{
setSize(150, 75);
setMaximumSize(getSize());
}
};
The problem is that JFrames use BorderLayout by default, which means that your JPanel will naturally fill the space.
Before adding your JPanel, call the following code to change the JFrame's layout to null and use the JPanel's settings instead.
this.setLayout(null);
JPanel hoofdmenu = new JPanel();
hoofdmenu.setBounds(0,0, 400, 100);
Alternatively, you could set the maximum size of the JButtons
Dimension maxSize = new Dimension(100, 100);
start.setMaximumSize(maxSize);
highscore.setMaximumSize(maxSize);
help.setMaximumSize(maxSize);
stoppen.setMaximumSize(maxSize);
Here's another example following behind the previous two - I'm making a soundboard program, and this is actually a sample from it - The JPanel actually is needed, agreeing to the second post.
JFrame frame = new JFrame();
JPanel menuPanel = new JPanel();
JButton Button1 = new JButton("<BUTTON NAME 1>");
Button1.setSize(80, 30);
Button1.setLocation(4, 4);
JButton Button2 = new JButton("<BUTTON NAME 2>");
Button2.setSize(80, 30);
Button2.setLocation(90, 4);
Ah, and another thing - You created the buttons in a different block from the second piece of code. Doing that causes the other blocks to not see it. You need to declare them outside the block so all the blocks can see them.

pass value from one jframe to other jframe?

i created two classes one class is just like form the other class is main class and having jmenu and jinternal frames i want to print the input from the form class on the jinternal frame but i cannot understand how i recall the jinternalframe in the form classes, please guide me in this regard or any hint or some piece of code or tutorial that can help me here is code of both the classes. Moreover both classes are working fine .
JTextArea text;
static int openFrameCount = 0;
public form(){
super("Insert Form");
Container panel=getContentPane();
JPanel cc = new JPanel();
cc.setLayout(new FlowLayout());
JButton b=new JButton("print");
b.setPreferredSize(new Dimension(140,50));
b.setBounds(1000,500,350,50);
cc.add(b);
.......................................................
JLabel label1=new JLabel(" Question"+(++openFrameCount));
cc.add(label1);
text=new JTextArea();
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(750,50));
text.setBounds(80, 60,750,50);
cc.add(text);
JLabel symbol=new JLabel("Selection for Option?");
symbol.setBounds(200, 120,1000,100);
cc.add(symbol);
..................................................
JLabel op4=new JLabel("4th Option?");
JTextArea otext4=new JTextArea();
otext4.setLineWrap(true);
otext4.setWrapStyleWord(true);
otext4.setPreferredSize(new Dimension(750,50));
otext4.setBounds(10, 40,700,30);
cc.add( op4 ) ;
cc.add( otext4 ) ;
cc.revalidate();
validate();
............................................................
}
#Override
public void actionPerformed(ActionEvent ae) {
if ( e.getSource() == b1 ){
}
}
}
and the second class of jinternalframe is
public class Desktop1 extends JFrame
implements ActionListener {
Desktop p=new Desktop();
JDesktopPane desktop;
static int openFrameCount = 0;
public Desktop1() {
super("InternalFrameDemo");
//Make the big window be indented 50 pixels from each edge
//of the screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset,
screenSize.width - inset*2,
screenSize.height - inset*2);
//Set up the GUI.
desktop = new JDesktopPane(); //a specialized layered pane
createFrame(); //create first "window"
setContentPane(desktop);
setJMenuBar(createMenuBar());
//Make dragging a little faster but perhaps uglier.
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
//Set up the lone menu.
.................................................
return menuBar;
}
//React to menu selections.
public void actionPerformed(ActionEvent e) {
if ("new".equals(e.getActionCommand())) { //new
createFrame();
}
............................................
}
}
class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame() {
super("IFrame #" + (++openFrameCount), true, // resizable
true, // closable
true, // maximizable
true);// iconifiable
setSize(700, 700);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition
* openFrameCount);
}
}
//Create a new internal frame.
protected void createFrame() {
Desktop1.MyInternalFrame frame = new Desktop1.MyInternalFrame();
JPanel panel=new JPanel();//to add scrollbar in jinternalpane insert jpanel
panel.setBackground(Color.white);//set background color of jinternal frame
JScrollPane scrollBar=new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.add(scrollBar);
frame.setVisible(true);
desktop.add(frame);
try {
frame.setSelected(true);
frame.setMaximum(true);
} catch (java.beans.PropertyVetoException e) {}
}
public static void main(String[] args) {
Desktop1 d=new Desktop1();
d.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
d.setVisible(true);
}
}
i want to know hint about the work that come in this part of code to pass the value of form to internal frame when i click on print button
public void actionPerformed(ActionEvent ae) {
if ( e.getSource() == b1 ){
}
}
}
just call the constructor and pass the value
ClassName(parameter)
I guess you want to pass some text to your InternalFrame class on the button click from the main form.
Modify your createFrame() method to accept a String value
e.g-
protected void createFrame(String value){
//..your code
}
and when you call your InternalFrame class, pass this value to its constructor. e.g-
Desktop1.MyInternalFrame frame = new Desktop1.MyInternalFrame(value);
Parameterised constructor will solve your problem. Modify your InternalFrame constructor
e.g-
public MyInternalFrame(String value){
//..use this value
}

Categories