The JFrame window needs to display a random dice image. When the button is clicked, the random dice image needs to change. I have figured out how to display the random dice image, but I cannot figure out how to use the actionlistener to generate a new random dice image. I am only in my third Java class, so any guidance would be greatly appreciated!
package guiDice;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.event.ActionEvent;
public class LabGuiDice extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LabGuiDice frame = new LabGuiDice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LabGuiDice() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnRollem = newDiceRoll();
contentPane.add(btnRollem, BorderLayout.SOUTH);
JLabel lblDice = newDiceImage();
contentPane.add(lblDice, BorderLayout.CENTER);
}
private JLabel newDiceImage() {
Random rnd = new Random();
int rand1 = 0;
rand1 = rnd.nextInt(6)+1;
JLabel lblDice = new JLabel("");
switch (rand1) {
case 1:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-1.png")));
break;
case 2:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-2.png")));
break;
case 3:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-3.png")));
break;
case 4:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-4.png")));
break;
case 5:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-5.png")));
break;
case 6:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-6.png")));
break;
}
return lblDice;
}
private JButton newDiceRoll() {
JButton btnRollem = new JButton("Roll 'Em");
btnRollem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnRollem.setBorderPainted(false);
btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
btnRollem.setOpaque(true);
btnRollem.setBackground(new Color(255, 0, 0));
return btnRollem;
}
}
Create a method that generates the integer and sets the icon to the label. But in order to do that, label should be a field in the class, so all methods can access it. For example:
private void rollDice() {
Random random = new Random();
int randomInt = random.nextInt(6) + 1;
String resource = String.format("/Dice/die-%d.png", randomInt);
Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
diceIconLabel.setIcon(icon);
}
and then:
btnRollem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rollDice();
}
});
with full code:
public class LabGuiDice extends JFrame {
private JPanel contentPane;
private JLabel diceIconLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
LabGuiDice frame = new LabGuiDice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LabGuiDice() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnRollem = newDiceRoll();
contentPane.add(btnRollem, BorderLayout.SOUTH);
diceIconLabel = newDiceImage();
contentPane.add(diceIconLabel, BorderLayout.CENTER);
rollDice();
pack();
}
private void rollDice() {
Random random = new Random();
int randomInt = random.nextInt(6) + 1;
String resource = String.format("/Dice/die-%d.png", randomInt);
Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
diceIconLabel.setIcon(icon);
}
private JLabel newDiceImage() {
JLabel lblDice = new JLabel("");
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
return lblDice;
}
private JButton newDiceRoll() {
JButton btnRollem = new JButton("Roll 'Em");
btnRollem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rollDice();
}
});
btnRollem.setBorderPainted(false);
btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
btnRollem.setOpaque(true);
btnRollem.setBackground(new Color(255, 0, 0));
return btnRollem;
}
}
Related
I decided to take a java class and the prof wants all the .java files to run in jGrasp but I am much more familiar with eclipse so I've been using that. I have two files who will compile fine in eclipse but when I open their .java files in jGrasp they either don't execute correctly or some of the import statements cause errors.
This one will compile but the JFrame will be empty:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class JDisappearingFriends {
static int i = 1;
static void increase_i() {
++i;
}
public static void main(String[] args) {
JFrame frame1 = new JFrame();
frame1.setVisible(true);
frame1.setSize(303, 286);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel[] friends = new JLabel[6];
friends[0] = new JLabel(
"Hello. To begin changing friends press the button");
friends[1] = new JLabel("Laura");
friends[2] = new JLabel("Kendra");
friends[3] = new JLabel("Nicole");
friends[4] = new JLabel("Melissa");
friends[5] = new JLabel("Elizabeth");
frame1.add(friends[0]);
JButton btnChangeFriends = new JButton("Change Friends");
btnChangeFriends.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (i < 6) {
frame1.getContentPane().add(friends[i]);
frame1.remove(friends[i - 1]);
frame1.revalidate();
frame1.repaint();
increase_i();
} else {
JLabel done = new JLabel("That's it, your out of friends");
frame1.remove(friends[5]);
frame1.add(done);
frame1.revalidate();
frame1.repaint();
}
}
});
frame1.getContentPane().add(btnChangeFriends, BorderLayout.SOUTH);
}
}
This code won't compile at all. jGrasp claims the import statement for jGoodies is invalid but it works fine in eclipse.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.RowSpec;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class JPhotoFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JPhotoFrame frame = new JPhotoFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JPhotoFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 505, 274);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
panel.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("46px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),},
new RowSpec[] {
FormFactory.LINE_GAP_ROWSPEC,
RowSpec.decode("23px"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JLabel lblNewLabel_2 = new JLabel("Please select a number of people. Pets Optional");
panel.add(lblNewLabel_2, "2, 2, 7, 1, fill, center");
JCheckBox single = new JCheckBox("Single ");
panel.add(single, "4, 4, left, top");
JCheckBox more_people = new JCheckBox("2+ People");
panel.add(more_people, "6, 4, left, top");
JCheckBox pets = new JCheckBox("Pet");
panel.add(pets, "8, 4, left, top");
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.NORTH);
panel_1.setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("87px"),
ColumnSpec.decode("46px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),},
new RowSpec[] {
FormFactory.LINE_GAP_ROWSPEC,
RowSpec.decode("23px"),}));
JLabel lblNewLabel_3 = new JLabel("Please select a location");
panel_1.add(lblNewLabel_3, "1, 2, 3, 1, left, center");
JCheckBox studio = new JCheckBox("Studio");
panel_1.add(studio, "4, 2, left, top");
JCheckBox other = new JCheckBox("Other");
panel_1.add(other, "6, 2, left, top");
studio.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if((e.getStateChange() == ItemEvent.SELECTED)){
other.setEnabled(false);
}
}
});
other.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if((e.getStateChange() == ItemEvent.SELECTED)){
studio.setEnabled(false);
}
}
});
single.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if((e.getStateChange() == ItemEvent.SELECTED)){
more_people.setEnabled(false);
}
}
});
more_people.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if((e.getStateChange() == ItemEvent.SELECTED)){
single.setEnabled(false);
}
}
});
JLabel lblNewLabel = new JLabel("Press Button to calculate total cost");
contentPane.add(lblNewLabel, BorderLayout.SOUTH);
JButton btnCalculateTotal = new JButton("Calculate Total");
btnCalculateTotal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int total = 0;
int other_price=0;
int single_price=0;
int more_people_price=0;
int pets_price=0;
if(studio.isSelected() == false && other.isSelected()== false){
lblNewLabel.setText("Please enter a least one location value");
}
else if(single.isSelected() == false && more_people.isSelected() == false){
lblNewLabel.setText("Please enter at least one subject value");
}
else{
if(single.isSelected() == true) single_price = 40;
if(other.isSelected() ==true ) other_price = 90;
if(more_people.isSelected() == true) more_people_price = 75;
if(pets.isSelected() == true) pets_price = 95;
total = calculate(single_price,other_price, more_people_price, pets_price);
lblNewLabel.setText("Your Total is: $" + total);
}
lblNewLabel.revalidate();
lblNewLabel.repaint();
studio.setEnabled(true);
other.setEnabled(true);
single.setEnabled(true);
more_people.setEnabled(true);
studio.setSelected(false);
other.setSelected(false);
single.setSelected(false);
more_people.setSelected(false);
pets.setSelected(false);
}
});
contentPane.add(btnCalculateTotal, BorderLayout.EAST);
}
int calculate(int single, int other, int more_people, int pets){
int total = single + other + more_people + pets;
return total;
}
}
When you create a project in eclipse it creates certain dependencies to packages and modules based on its configuration.
The program is showing an empty JFrame because the project in eclipse uses those dependancies but jGrasp can't find them because it is not familiar with project structure of eclipse.
I'm developing a tic tac toe game and have one problem - Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException, it occurs when i try to press the button. The buttonText is changed to X, but after that i get the problem. I believe there is something wrong with if statements:
The source code of Main.java:
package mytictactoegame;
public class Main {
public static boolean playerTurn = true;
public static boolean playerWon = false;
public static boolean compWon = false;
public static boolean playing = true;
public static ticgame board = new ticgame ();
public static void main(String[] args) {
board.setVisible(true);
}
public static void checkforwin (){
//147
if (board.button1.getText().equals("X")){
if (board.button4.getText().equals("X")){
if (board.button7.getText().equals("X")){
playerWon = true;
compWon = false;
board.labelWon.setText ("Player X won!");
}
}
}
}
}
And ticgame (GUI):
package mytictactoegame;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.GridLayout;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.RowSpec;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JLabel;
public class ticgame extends JFrame {
Main main = new Main ();
/**
*
*/
public static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ticgame frame = new ticgame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ticgame() {
setTitle("Tic Tac Toe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(new Color(204, 255, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(3, 3, 0, 0));
JButton button1 = new JButton("");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (button1.getText().equals("")){
if (Main.playerTurn == true){
button1.setText("X");
Main.checkforwin();
Main.playerTurn = false;
} else {
button1.setText("O");
Main.checkforwin();
Main.playerTurn = true;
}
}
}
});
panel.add(button1);
JButton button4 = new JButton("");
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (button4.getText().equals("")){
if (Main.playerTurn == true){
button4.setText("X");
Main.checkforwin();
Main.playerTurn = false;
} else {
button4.setText("O");
Main.checkforwin();
Main.playerTurn = true;
}
}
}
});
panel.add(button4);
JButton button7 = new JButton("");
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (button7.getText().equals("")){
if (Main.playerTurn == true){
button7.setText("X");
Main.checkforwin();
Main.playerTurn = false;
} else {
button7.setText("O");
Main.checkforwin();
Main.playerTurn = true;
}
}
}
});
panel.add(button7);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.EAST);
panel_1.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("117px"),},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("29px"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JButton buttonNewGame = new JButton("New Game");
buttonNewGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button1.setText("");
button2.setText("");
button3.setText("");
button4.setText("");
button5.setText("");
button6.setText("");
button7.setText("");
button8.setText("");
button9.setText("");
Main.playerTurn = true;
Main.playerWon = false;
Main.compWon = false;
}
});
buttonNewGame.setForeground(Color.RED);
buttonNewGame.setBackground(new Color(153, 255, 0));
panel_1.add(buttonNewGame, "2, 2, left, top");
JButton buttonHistory = new JButton("History");
buttonHistory.setForeground(Color.RED);
panel_1.add(buttonHistory, "2, 4");
JButton buttonExit = new JButton("Exit");
buttonExit.setForeground(Color.RED);
buttonExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panel_1.add(buttonExit, "2, 6");
JLabel labelWon = new JLabel();
labelWon.setText ("Who won?");
labelWon.setForeground(Color.GREEN);
panel_1.add(labelWon, "2, 10, left, default");
}
public JButton button1;
public JButton button2;
public JButton button3;
public JButton button4;
public JButton button5;
public JButton button6;
public JButton button7;
public JButton button8;
public JButton button9;
public JLabel labelWon;
}
Here is first lines of the error log, the rest doesnt fit due to number of words:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mytictactoegame.Main.checkforwin(Main.java:20)
at mytictactoegame.ticgame$2.actionPerformed(ticgame.java:71)
You're shadowing your variables such as your button1 variable and others like it. By shadowing, I mean that you declare them in the class, but then re-declare and initialize the re-declared variable in your class's constructor. When you do that, the field (the variable declared in the class) remains null. Solution: don't shadow your variables by not re-declaring them in the constructor.
e.g., you do this:
// should be named TicGame to comply with Java naming standards
public class ticgame extends JFrame {
public ticgame() {
// ....
// here you re-declare the button1 variable
// by doing this, you initialize the local variable that
// is present int he constructor but leave the class field null
JButton button1 = new JButton("");
//....
}
public JButton button1; // this guy remains null
// .....
}
When you should be doing this:
public class TicGame extends JFrame {
public TicGame() {
// ....
// JButton button1 = new JButton("");
button1 = new JButton(""); // note the difference?
//....
}
public JButton button1; // now he's not null!
// .....
}
I am working on a Java Swing application.
My Requirement :-
In my JFrame, I have a JList with values "One", "Two", "Three" etc. When I select one list item, I want to show "n" buttons where "n" is the value selected.
Example :- If I select "Three" from the list, there should be 3 buttons in the JFrame.
Below is my code :-
public class Details extends JFrame {
String[] navData = new String{"One","Two","Three","Four"};
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Details frame = new Details();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Details() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
//frame.setSize(xSize,ySize);
setTitle("Test");
setBounds(0, 0, 776, 457);
setResizable(false);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JList list = new JList(navData);
list.setBounds(0, 0, 140, ySize);
contentPane.add(list);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setFixedCellHeight(50);
list.setFixedCellWidth(70);
list.setBorder(new EmptyBorder(10,10, 10, 10));
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
int numButtons;
String selectedItem = navData[list.getSelectedIndex()];
switch (selectedItem) {
case "One":
addButtons(1);
break;
case "Two":
addButtons(2);
break;
case "Three":
addButtons(3);
break;
case "Four":
addButtons(4);
break;
default:
break;
}
}
});
list.setSelectedIndex(0);
}
public void addButtons(int n)
{
revalidate();
for(int i = 0; i<n;i++)
{
JButton button = new JButton(" "+navData[i]);
button.setBounds(200 + (i*50), 150, 50, 50);
contentPane.add(button);
}
}
}
- Problem :-
When I change the selected item in the list, the JPanel is not getting updated. In other words, I don't get 3 buttons when I select "Three" from the List. I get only 1 button which was created by the default selection.
I made these changes:
I put the JList in a JPanel, and the JButtons in another JPanel.
I used the FlowLayout for the JList JPanel, and the FlowLayout for the JButtons JPanel. You're free to change these Swing layouts if you wish.
I changed the default to 4 buttons, so the JFrame would pack properly for up to 4 JButtons.
I added a method to remove the JButtons from the JPanel before trying to add JButtons to the JPanel.
I revalidated and repainted the JButton JPanel.
Here's the code:
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Details extends JFrame {
private static final long serialVersionUID = -555805219508469709L;
private String[] navData = { "One", "Two", "Three", "Four" };
private JPanel buttonPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Details frame = new Details();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Details() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("Test");
buttonPanel = new JPanel();
JPanel listPanel = new JPanel();
final JList<String> list = new JList<String>(navData);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setFixedCellHeight(50);
list.setFixedCellWidth(70);
list.setBorder(new EmptyBorder(10, 10, 10, 10));
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent event) {
String selectedItem = navData[list.getSelectedIndex()];
switch (selectedItem) {
case "One":
removeButtons(buttonPanel);
addButtons(buttonPanel, 1);
break;
case "Two":
removeButtons(buttonPanel);
addButtons(buttonPanel, 2);
break;
case "Three":
removeButtons(buttonPanel);
addButtons(buttonPanel, 3);
break;
case "Four":
removeButtons(buttonPanel);
addButtons(buttonPanel, 4);
break;
default:
break;
}
}
});
list.setSelectedIndex(3);
listPanel.add(list);
add(listPanel, BorderLayout.WEST);
add(buttonPanel, BorderLayout.CENTER);
pack();
}
public void removeButtons(JPanel panel) {
Component[] components = panel.getComponents();
for (int i = 0; i < components.length; i++) {
panel.remove(components[i]);
}
}
public void addButtons(JPanel panel, int n) {
for (int i = 0; i < n; i++) {
JButton button = new JButton(navData[i]);
panel.add(button);
}
panel.revalidate();
panel.repaint();
}
}
Replace contentPane.setLayout(null); with some kind of layout such as contentPane.setLayout(new GridBagLayout());
Add
contentPane.removeAll() as the first line in addButtons().
You can create a "wrapper" panel for buttons, i.e.
...
private JPanel buttonsWrapper;
...
// in the constructor
buttonsWrapper = new JPanel();
buttonsWrapper.setLayout(null);
buttonsWrapper.setBounds(200, 150, 200, 50);
buttonsWrapper.add(wrapperPanel);
and add buttons to this panel
public void addButtons(int n) {
buttonsWrapper.removeAll();
for(int i = 0; i < n; i++) {
JButton button = new JButton(" " + navData[i]);
button.setBounds((i*50), 0, 50, 50);
buttonsWrapper.add(button);
}
buttonsWrapper.revalidate();
buttonsWrapper.repaint();
}
My Java GUI application wont display data from the PersonUI.java class with the layout details im using MIGLayout in Netbeans 8.0.
All the files i n the project have no errors it wont display the GUI. May help me with displaying the MIGlayout .
package View;
import Model.Person;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
/**
/**
*
* #author Mbano
*/import Controller.PersonBean;
public class PersonUI extends JPanel {
private JTextField idField = new JTextField(10);
private JTextField fNameField = new JTextField(30);
private JTextField mNameField, lNameField, emailField, phoneField;
private JButton createButton = new JButton("New...");
private JButton updateButton, deleteButton, firstButton, prevButton, nextButton,
lastButton;
private PersonBean bean = new PersonBean();
public PersonUI() {
setBorder(new TitledBorder
(new EtchedBorder(),"Person Details"));
setLayout(new BorderLayout(5, 5));
add(initFields(), BorderLayout.NORTH);
add(initButtons(), BorderLayout.CENTER);
setFieldData(bean.moveFirst());
}
private JPanel initButtons() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
panel.add(createButton);
createButton.addActionListener(new ButtonHandler());
//...
panel.add(lastButton);
lastButton.addActionListener(new ButtonHandler());
return panel;
}
private JPanel initFields() {
JPanel panel = new JPanel();
panel.setLayout(new MigLayout());
panel.add(new JLabel("ID"), "align label");
panel.add(idField, "wrap");
idField.setEnabled(false);
panel.add(new JLabel("First Name"), "align label");
panel.add(fNameField, "wrap");
//...
panel.add(new JLabel("Phone"), "align label");
panel.add(phoneField, "wrap");
return panel;
}
private Person getFieldData() {
Person p = new Person();
p.setPersonId(Integer.parseInt(idField.getText()));
p.setFirstName(fNameField.getText());
p.setMiddleName(mNameField.getText());
p.setLastName(lNameField.getText());
p.setEmail(emailField.getText());
p.setPhone(phoneField.getText());
return p;
}
private void setFieldData(Person p) {
idField.setText(String.valueOf(p.getPersonId()));
fNameField.setText(p.getFirstName());
mNameField.setText(p.getMiddleName());
lNameField.setText(p.getLastName());
emailField.setText(p.getEmail());
phoneField.setText(p.getPhone());
}
private boolean isEmptyFieldData() {
return (fNameField.getText().trim().isEmpty()
&& mNameField.getText().trim().isEmpty()
&& lNameField.getText().trim().isEmpty()
&& emailField.getText().trim().isEmpty()
&& phoneField.getText().trim().isEmpty());
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Person p = getFieldData();
switch (e.getActionCommand()) {
case "Save":
if (isEmptyFieldData()) {
JOptionPane.showMessageDialog(null,
"Cannot create an empty record");
return;
}
if (bean.create(p) != null)
JOptionPane.showMessageDialog(null,
"New person created successfully.");
createButton.setText("New...");
break;
case "New...":
p.setPersonId(new Random()
.nextInt(Integer.MAX_VALUE) + 1);
p.setFirstName("");
p.setMiddleName("");
p.setLastName("");
p.setEmail("");
p.setPhone("");
setFieldData(p);
createButton.setText("Save");
break;
case "Update":
if (isEmptyFieldData()) {
JOptionPane.showMessageDialog(null,
"Cannot update an empty record");
return;
}
if (bean.update(p) != null)
JOptionPane.showMessageDialog(
null,"Person with ID:" + String.valueOf(p.getPersonId()
+ " is updated successfully"));
break;
case "Delete":
if (isEmptyFieldData()) {
JOptionPane.showMessageDialog(null,
"Cannot delete an empty record");
return;
}
p = bean.getCurrent();
bean.delete();
JOptionPane.showMessageDialog(
null,"Person with ID:"
+ String.valueOf(p.getPersonId()
+ " is deleted successfully"));
break;
case "First":
setFieldData(bean.moveFirst()); break;
case "Previous":
setFieldData(bean.movePrevious()); break;
case "Next":
setFieldData(bean.moveNext()); break;
case "Last":
setFieldData(bean.moveLast()); break;
default:
JOptionPane.showMessageDialog(null,
"invalid command");
}
}
}
}
package View;
import java.awt.FlowLayout;
import javax.swing.JFrame;
/**
*
* #author Mbano
*/
public class AppMain {
public static void main(String[] args) {
JFrame f =new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
f.getContentPane().add(new PersonUI());
f.setSize(600, 280);
f.setVisible(true);
}
}
Check the console for any exceptions. Try
new MigLayout("debug")
to see your Layout in debg mode.
You could also set different background colors to the differen JPanels, to see what size they have.
I create an Team application in java. I add a logo which is the combination of Rectangle and Circle in JFrame but after add logo in application JTextArea not shown... Also adding new player not shown...
Here is my code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MainGUI extends JFrame
{
private JLabel teamName;
private JLabel playerCount;
private JLabel maxPlayer;
private JButton createTeam;
private JButton addOnePlayer;
private JButton addRemining;
private JButton exit;
private Team team;
private boolean teamCreated;
private JTextArea text;
Logo logo;
public static void main(String[] args)
{
new MainGUI();
}
public MainGUI()
{
super.setTitle("Team manager");
super.setSize(500,400);
super.setLocation(150,150);
super.setLayout(new BorderLayout());
add(addTopPanel(), BorderLayout.NORTH);
add(textArea(), BorderLayout.CENTER);
add(buttonPanel(), BorderLayout.SOUTH);
Logo logo = new Logo();
logo.setBounds(100, 100, 150,150);
getContentPane().add(logo);
// logo.addSquare(10, 10, 100, 100);
super.setVisible(true);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel buttonPanel()
{
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2,2));
createTeam = new JButton("Create Team");
addOnePlayer = new JButton("Add one player");
addRemining = new JButton("Add remaining players");
exit = new JButton("Exit");
buttonPanel.add(createTeam);
buttonPanel.add(addOnePlayer);
buttonPanel.add(addRemining);
buttonPanel.add(exit);
createTeam.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(!teamCreated)
{
teamCreated = true;
team = new Team();
teamName.setText("Team name: "+team.getName());
playerCount.setText("Players count: "+team.getCount());
maxPlayer.setText("Max team size: "+team.getSize());
}
else
{
JOptionPane.showMessageDialog(null,"The team has been already created, and no further Team instances are instantiated");
}
}
});
addOnePlayer.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(team != null)
{
Player pl = Team.createPlayer();
team.addPlayer(pl);
playerCount.setText("Players count: "+team.getCount());
text.setText(team.toString());
}
else
{
JOptionPane.showMessageDialog(null,"Create a team first ");
}
}
});
addRemining.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(team != null)
{
team.addPlayers();
playerCount.setText("Players count: "+team.getCount());
text.setText(team.toString());
}
else
{
JOptionPane.showMessageDialog(null,"Create a team first ");
}
}
});
exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(1);
}
});
return buttonPanel;
}
private JTextArea textArea()
{
text = new JTextArea();
return text;
}
private JPanel addTopPanel()
{
JPanel top = new JPanel();
top.setLayout(new GridLayout(1,3));
teamName = new JLabel("Team name: ");
playerCount = new JLabel("Players count: ");
maxPlayer = new JLabel("Max team size: ");
top.add(teamName);
top.add(playerCount);
top.add(maxPlayer);
return top;
}
class Logo extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.drawRect(350,80,70,70);
g.setColor(Color.blue);
g.drawRoundRect(360, 30, 50, 50, 50, 50);;
}
}
}
after add logo in application JTextArea not shown
Reason is this Line:
logo.setBounds(100, 100, 150,150);
getContentPane().add(logo);
setBounds wont work with the layouts of Swing components. So when you are adding the logo in container of JFrame it is adding it to the center , hiding out the JTextArea added in center.