for(gbc.gridy = 3; gbc.gridy > 0; gbc.gridy--)
for(gbc.gridx = 0; gbc.gridx < 3;gbc.gridx++)
{
grid[btnNum] = new JButton("" + (btnNum+1));
grid[btnNum].setPreferredSize(new Dimension(75,75));
frame.add(grid[btnNum], gbc);
grid[btnNum].addActionListener(this);
grid[btnNum].addKeyListener(this);
btnNum++;
}
I have an array of buttons displayed in a 3x3 grid and each one has an action listener.
public void actionPerformed(ActionEvent e){
String output = "";
if(e.getSource() == grid[0]){
System.out.println("button 1");
}
}
Is this not correct?
Complete example in context:
public class ButtonGrid implements ActionListener, KeyListener{
JFrame frame=new JFrame(); //creates frame
JButton[] grid; //names the grid of buttons
public ButtonGrid(){ //constructor
frame.setTitle("MPC");
frame.setLayout(new GridBagLayout()); //set layout
JButton[] grid=new JButton[12]; //allocate the size of grid
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
int btnNum = 0;
grid[9] = new JButton("0");
grid[9].setPreferredSize(new Dimension(75,75));
grid[10] = new JButton("-");
grid[10].setPreferredSize(new Dimension(75,75));
grid[11] = new JButton("=");
grid[11].setPreferredSize(new Dimension(75,75));
frame.add(grid[9], gbc);
gbc.gridx++;
frame.add(grid[10], gbc);
gbc.gridx++;
frame.add(grid[11], gbc);
for(gbc.gridy = 3; gbc.gridy > 0; gbc.gridy--)
for(gbc.gridx = 0; gbc.gridx < 3;gbc.gridx++){
grid[btnNum] = new JButton("" + (btnNum+1));
grid[btnNum].setPreferredSize(new Dimension(75,75));
frame.add(grid[btnNum], gbc);
grid[btnNum].addActionListener(this);
grid[btnNum].addKeyListener(this);
btnNum++;
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
public static void main(String[] args) {
new ButtonGrid();//makes new ButtonGrid with 2 parameters
}
public void actionPerformed(ActionEvent e){
String output = "";
if(e.getSource() == grid[0]){
System.out.println("button one");
//playSound(abc.kick);
}}
Your grid variable is null in the ActionListener. My bet -- you're shadowing the variable.
Solution: make sure that you initialize the grid field, not a local grid variable
public class ButtonGrid implements ActionListener, KeyListener{
JFrame frame=new JFrame();
JButton[] grid; // grid field remains null
public ButtonGrid(){
frame.setTitle("MPC");
frame.setLayout(new GridBagLayout());
JButton[] grid=new JButton[12]; // ****** a LOCAL variable ******
At the indicated line you create the shadowed variable. This means because you redeclare grid within the constructor, you initialize only the local variable and not the field that was declared in the class leaving the field null. Solution: Don't re-declare grid. Change it to:
public class ButtonGrid implements ActionListener, KeyListener{
JFrame frame = new JFrame();
JButton[] grid;
public ButtonGrid(){
frame.setTitle("MPC");
frame.setLayout(new GridBagLayout());
grid = new JButton[12]; // ***** this initializes the field ******
Try this.
public void actionPerformed(ActionEvent e){
String output = "";
for(int i=0; i<=grid.length; i++){
if(e.getSource() == grid[i]){
System.out.println("button "+i);
}
}
}
Related
Creating a game called reversi also known as Othello and I am trying to add the starting position of my Black and Whites counters (using JLabel, labelled 'W' and 'B') in the middle of the board diagonally opposite from each other but for some reason only 2 show up and the other 2 don't show, which I don't understand why.
How do I go about fixing it?
import java.io.*;
import java.util.*;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
public class Reversi
{
// instance variables - replace the example below with your own
private JFrame frame;
private JLabel userName1;
private JLabel userName2;
private JTextField textUsername1;
private JTextField textUsername2;
private JButton startButton;
private JButton [][] squares = new JButton[8][8];
private JLabel whites = new JLabel("W");
private JLabel blacks = new JLabel("B");
/**
*
*/
public Reversi()
{
// initialise instance variables
gui();
}
/**
*
*/
public void gui()
{
frame = new JFrame("Reversi Game");
frame.setSize(800,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setLayout(new BoxLayout(frame, BoxLayout.X_AXIS));
JPanel userInterface = new JPanel(new GridBagLayout());
userInterface.setBackground(Color.LIGHT_GRAY);
userInterface.setBorder(BorderFactory.createBevelBorder(0));
//userInterface.setPreferredSize(new Dimension(350,700));
GridBagConstraints c = new GridBagConstraints();
//c.anchor = GridBagConstraints.NORTH;
JPanel board = new JPanel();
board.setBackground(Color.GRAY);
board.setBorder(BorderFactory.createBevelBorder(1));
board.setPreferredSize(new Dimension(750, 700));
userName1 = new JLabel("Enter First player: ");
userName2 = new JLabel("Enter Second player: ");
textUsername1 = new JTextField(15);
textUsername2 = new JTextField(15);
startButton = new JButton("START");
c.gridx = 0;
c.gridy = 0;
userInterface.add(userName1, c);
c.gridx = 1;
userInterface.add(textUsername1, c);
c.gridx = 0;
c.gridy = 1;
userInterface.add(userName2, c);
c.gridx = 1;
userInterface.add(textUsername2, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.anchor = GridBagConstraints.SOUTH;
userInterface.add(startButton, c);
userInterface.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Players/Scoreboard"));
board.setLayout(new GridLayout(8,8));
for(int i = 0; i< 8; i++){
for (int j = 0; j < 8; j++)
{
squares[i][j] = new JButton();
squares[i][j].setBackground(Color.GREEN);
board.add(squares[i][j]);
}
}
squares[4][3].add(blacks);
squares[4][4].add(whites);
squares[3][4].add(blacks);
squares[3][3].add(whites);
frame.add(board, BorderLayout.CENTER);
JPanel wrapper = new JPanel();
wrapper.add(userInterface);
frame.add(wrapper, BorderLayout.LINE_END);
makeMenuBar();
frame.pack();
frame.setVisible(true);
}
private void makeMenuBar()
{
//Finish coding later
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu fileMenu = new JMenu("File");
menubar.add(fileMenu);
JMenuItem saveFile = new JMenuItem("Save File");
fileMenu.add(saveFile);
JMenuItem quitGame = new JMenuItem("Quit");
fileMenu.add(quitGame);
quitGame.addActionListener(ev -> {quit(); });
}
private void quit()
{
System.exit(0);
}
}
Each component (i.e. your JLabels (whites and blacks)) can only be added to a container once, if you need to add more labels, even if they have the same String inside, you have to create a new object for those, otherwise these will be shown in the last container you've added them.
squares[4][3].add(blacks);
squares[4][4].add(whites);
squares[3][4].add(blacks); // Only this one is added
squares[3][3].add(whites); // Only this one is added
You'll need something like this, or have an array of JLabels and add them to all your squares, then just call yourJLabelArray[i][j].setText("W") (or "B")
squares[4][3].add(new JLabel("B"));
squares[4][4].add(new JLabel("W"));
squares[3][4].add(new JLabel("B"));
squares[3][3].add(new JLabel("W"));
Problem: below some code to make a frame filled with buttons. After the button is clicked, I would need to know the coordinates of the button clicked. The program will afterwards check the status of that specific tile and depending on the status it should change to a certain color. I'm having some issues when retracting this coordinate, could someone help me? (I'm only just learning how to program in Java, so my code might not be ideal)
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIBoard {
JPanel buttonPanel = new JPanel();
JButton button = new JButton();
JFrame frame;
ButtonClicked clicked = new ButtonClicked();
public GUIBoard(String title, int nbRows, int nbColumns) {
frame = new JFrame(title);
buttonPanel.setLayout(new GridLayout(nbRows, nbColumns));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
for (int i = 0; i < nbRows; i++) {
for(int j = 0; j < nbColumns; j++) {
button = new JButton();
button.setBackground(Color.LIGHT_GRAY);
button.addActionListener(clicked);
gbc.gridx = j;
gbc.gridy = i;
buttonPanel.add(button, gbc);
}
}
frame.setPreferredSize(new Dimension(1000, 600));
frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private class ButtonClicked implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new GUIBoard("Batlleship Board", 10,10);
}
});
}
}
If by coordinates you mean the actualx and y placement location of the button clicked upon then you can use this within your buttons ActionPerformed event:
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton)e.getSource();
System.out.println(btn.getX() + ", " + btn.getY());
}
Will print the top left location of the button clicked upon. This isn't very helpful however since these locations can change if the Form is resized in any way.
If you mean by grid location as in the row and column of the button clicked upon then the easiest would be to ensure that an identifier is applied to each of the buttons by placing the grid location into the buttons Name property, when creating your buttons, for example:
for (int i = 0; i < nbRows; i++) {
for (int j = 0; j < nbColumns; j++) {
button = new JButton();
// Apply an identifier to the Button:
button.setName(new StringBuilder("Button_").append(i)
.append(",").append(j).toString());
button.setBackground(Color.LIGHT_GRAY);
button.addActionListener(clicked);
gbc.gridx = j;
gbc.gridy = i;
buttonPanel.add(button, gbc);
}
}
Then in your buttons ActionPerformed event:
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton)e.getSource();
System.out.println(btn.getName());
}
Now that I think I have understood what you want to do I am going to give you a new and easier approach:
Here is the code, you just need to use the method getSource() to get an instance of the button which has been pressed. Then you change the color.
public class GUIBoar {
JPanel buttonPanel = new JPanel();
JButton button = new JButton();
JFrame frame;
public GUIBoar(String title, int nbRows, int nbColumns) {
frame = new JFrame(title);
buttonPanel.setLayout(new GridLayout(nbRows, nbColumns));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
for (int i = 0; i < nbRows; i++) {
for (int j = 0; j < nbColumns; j++) {
button = new JButton();
button.setBackground(Color.LIGHT_GRAY);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
JButton b = (JButton)source;
b.setBackground(Color.RED); //IMAGINE THATS THE COLOR
}
});
gbc.gridx = j;
gbc.gridy = i;
buttonPanel.add(button, gbc);
}
}
frame.setPreferredSize(new Dimension(1000, 600));
frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUIBoar("Batlleship Board", 10, 10);
}
});
}
}
So, I have a login JFrame which shows up when I run the code. The problem is if the user enters the correct userName and password this login frame needs to be disposed when the other frame is shown up but it doesn't. I tried dispose(), setVisible = false, but still no chance to be hidden or disposed.
class LoggingWindow extends JFrame {
static JFrame loginFrame = new JFrame();
JPanel loginPanel = new JPanel();
JTextField loginNameFld = new JTextField(10);
JPasswordField loginPassFld = new JPasswordField(10);
JTextField statusFld = new JTextField(11);
String userName = "user";
String password = "password";
//Initialize loginFrame
public static void initLoginFrame() {
JFrame loginWindow = new LoggingWindow();
//loginFrame.setTitle("\"Moflo Registration\"");
loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginWindow.setResizable(false);
loginWindow.setUndecorated(true);
loginWindow.setVisible(true);
loginWindow.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
loginWindow.setSize(new Dimension(220, 290));
loginWindow.setLocationRelativeTo(null);
loginWindow.pack();
LoggingWindow() {
loginFrame.add(loginPanel);
loginPanel.setLayout(new GridBagLayout());
GridBagConstraints gbb = new GridBagConstraints();
gbb.insets = new Insets(1, 1, 1, 1);
gbb.anchor = GridBagConstraints.CENTER;
JPanel loginNameAndPasswordPanel = new JPanel();
loginPanel.add(loginNameAndPasswordPanel,gbb);
gbb.gridx = 0;
gbb.gridy = 2;
loginNameAndPasswordPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(0,0,0,0);
JLabel loginNameLab = new JLabel("Нэр : ");
gbc.gridx = 0;
gbc.gridy = 0;
loginNameAndPasswordPanel.add(loginNameLab, gbc);
JLabel loginPassLab = new JLabel("Нууц үг : ");
gbc.gridx = 0;
gbc.gridy = 1;
loginNameAndPasswordPanel.add(loginPassLab, gbc);
loginNameFld.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 0;
loginNameAndPasswordPanel.add(loginNameFld, gbc);
loginPassFld.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 1;
loginNameAndPasswordPanel.add(loginPassFld, gbc);
statusFld.setEditable(false);
loginNameAndPasswordPanel.add(statusFld, gbc);
statusFld.setHorizontalAlignment(JTextField.CENTER);
JPanel buttonsPanel = new JPanel();
loginPanel.add(buttonsPanel,gbb);
gbb.gridx = 0;
gbb.gridy = 3;
buttonsPanel.setLayout(new GridBagLayout());
GridBagConstraints gba = new GridBagConstraints();
gba.anchor = GridBagConstraints.LINE_END;
gba.insets = new Insets(2, 2, 2, 2);
JButton loginBtn = new JButton("Нэвтрэх");
gba.gridx = 0;
gba.gridy = 0;
buttonsPanel.add(loginBtn, gba);
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
String name = loginNameFld.getText();
String pass = loginPassFld.getText();
if(event.getSource() == loginBtn){
if (name.equals(userName) && pass.equals(password)) {
initMainFrame();
loginFrame.dispose();
JOptionPane.showMessageDialog(null, "Системд нэвтэрлээ. Өнөөдөр " + showDate, " ", JOptionPane.INFORMATION_MESSAGE);
} else {
statusFld.setText("Нэр эсвэл нууц үг буруу байна.");
}
}
}
});
JButton closeBtn = new JButton(" Хаах ");
gba.gridx = 1;
gba.gridy = 0;
buttonsPanel.add(closeBtn, gba);
add(loginPanel);
closeBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
//Main method
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initLoginFrame();
}
});
}
}
public class MainFrame extends JFrame {
//Initialzie mainFrame
public static void initMainFrame() {
JFrame mainFrame = new MainFrame();
mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
mainFrame.setMinimumSize(new Dimension(800, 600));
mainFrame.setLocationRelativeTo(null);
}
some, i think unimportant statements are not shown for the sake of brevity
I believe you confused "loginWindow" with "loginFrame". You try to use
loginFrame.dispose();
but your content is on loginWindow, not loginFrame.
I was able to get it to dispose the username window doing the following.
static JFrame loginWindow; <--- create as class variable, not local.
//loginFrame.add(loginPanel); <--- doesn't appear that this is actually used
if(event.getSource() == loginBtn){
if (name.equals(userName) && pass.equals(password)) {
MainFrame.initMainFrame();
//loginFrame.dispose(); <--- again, not used
loginWindow.dispose(); <--- want to dispose
JOptionPane.showMessageDialog(null, "Системд нэвтэрлээ. Өнөөдөр " , " ", JOptionPane.INFORMATION_MESSAGE);
} else {
statusFld.setText("Нэр эсвэл нууц үг буруу байна.");
}
}
You must also change this:
JFrame loginWindow = new LoggingWindow();
to:
loginWindow = new LoggingWindow();
You can always dispatch the "close" event to the JFrame object:
loginFrame.dispatchEvent(new WindowEvent(loginFrame, WindowEvent.WINDOW_CLOSING));
I definitely confused with loginFrame was indeed useless. I created a class variable: static JFrame loginWindow; but it results NullPointerException.
My school project is to create a purchasing system for that I create a JPanel array to list out all the products information and also allow user to input something for every item. And I dont know how to get all the values from jtextfields by clicking one button. The actionPerformed() method always requires a final variable which is quite troublesome for me.
private JButton payBtn;
public void shoppingCartTab(Customer userIn){
contentPanel.removeAll();
bottomPanel.removeAll();
final Customer USER = userIn;
ArrayList<Product> pArray = new ArrayList<Product>();
pArray = loadCartFile.loadCartFile(userIn);
JLabel tabLabel = new JLabel("Shopping Cart");
JPanel cartItems = new JPanel();
cartItems.setLayout(new BoxLayout(cartItems, BoxLayout.Y_AXIS));
final JPanel CONSTANT_CART = cartItems;
JScrollPane scroller = new JScrollPane(cartItems);
if(pArray != null){
JPanel item[] = new JPanel[pArray.size()];
for(int i = 0; i< pArray.size(); i++){
item[i] = new JPanel();
final JPanel JPANEL_TO_DEL = item[i];
item[i].setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.weightx = 0.3;
item[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel icon_small = new JLabel(new ImageIcon("Icons\\" + pArray.get(i).getID() + "_small.jpg"));
JLabel itemID = new JLabel(pArray.get(i).getID());
final String CONSTANT_ID = pArray.get(i).getID();
JLabel itemName = new JLabel(pArray.get(i).getName());
JLabel itemPrice = new JLabel("$" + pArray.get(i).getPrice());
JPanel setQuantity = new JPanel();
JButton plusBtn = new JButton("+");plusBtn.setPreferredSize(new Dimension(45,30));
final JTextField QUANTITY = new JTextField("0");QUANTITY.setColumns(3);
QUANTITY.setPreferredSize(new Dimension(45,30));QUANTITY.setHorizontalAlignment(JTextField.CENTER);
JButton minusBtn = new JButton("-");minusBtn.setPreferredSize(new Dimension(45,30));
plusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())<100)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())+1));
}
});
minusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())>0)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())-1));
}
});
setQuantity.add(plusBtn);
setQuantity.add(QUANTITY);
setQuantity.add(minusBtn);
JButton delBtn = new JButton("Delete");
delBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure to remove this item from your cart?", "Confirm", JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
CONSTANT_CART.remove(JPANEL_TO_DEL);
revalidate();
repaint();
ShoppingCart.removeItem(USER, CONSTANT_ID);
}
}
});
gBC.gridx = 0;
gBC.gridy = 0;
item[i].add(icon_small,gBC);
gBC.gridx = 1;
gBC.gridy = 0;
item[i].add(itemID,gBC);
gBC.gridx = 2;
gBC.gridy = 0;
item[i].add(itemName,gBC);
gBC.gridx = 3;
gBC.gridy = 0;
item[i].add(itemPrice,gBC);
gBC.gridx = 4;
gBC.gridy = 0;
item[i].add(setQuantity,gBC);
gBC.gridx = 5;
gBC.gridy = 0;
item[i].add(delBtn,gBC);
cartItems.add(item[i]);
}
contentPanel.add(tabLabel);
contentPanel.add(scroller);
payBtn = new JButton("Pay");
bottomPanel.add(payBtn); payBtn.addActionListener(this);
}else{
JLabel emptyMsg = new JLabel("Your cart is empty!");
contentPanel.add(emptyMsg);
}
revalidate();
repaint();
}
One solution would be to create a type which extends JPanel, and exposes a public property, which when called returns the value stored in the JTextField. Something like:
public class TextFieldPanel extends JPanel {
private JTextField myTextField;
public TextFieldPanel()
{
//layout init code here
}
public String getText()
{
return myTextField.getText();
}
}
Then just use this class instead of a regular JPanel. Then when your button is clicked, iterate over each of the objects in your collection, and call getText() on them to get your values.
import java.awt.*;
import javax.swing.*;
public class Class4 {
public static final long serialVersionUID = 1L;
public void mainMethod(int event){
JFrame f = new JFrame("Love Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,200);
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
if(event == 0){
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
p.setBounds(150, 0, 500, 75);
p.setPreferredSize(new Dimension(150,75));
JTextField boy = new JTextField();
boy.setMaximumSize(new Dimension(200,40));
JTextField girl = new JTextField();
girl.setMaximumSize(new Dimension(200,40));
p.add(boy);
p.add(girl);
gbc.insets = new Insets(-90,310,0,0);
gbc.gridx = 0;
gbc.gridy = 0;
f.add(p,gbc);
JPanel p3 = new JPanel(new BorderLayout());
p3.setBounds(0, 0, 150, 75);
p3.setPreferredSize(new Dimension(150,75));
Class5 c5o = new Class5();
c5o.setPreferredSize(new Dimension(150,75));
p3.add(c5o);
gbc.insets = new Insets(0,0,90,330);
gbc.gridx = 0;
gbc.gridy = 0;
f.add(p3,gbc);
JPanel p2 = new JPanel(new FlowLayout());
Class7 c7o = new Class7();
p2.add(c7o);
p2.setPreferredSize(new Dimension(300,40));
gbc.insets = new Insets(0,0,-20,0);
gbc.gridx = 0;
gbc.gridy = 0;
f.add(p2,gbc);
f.setVisible(true);
//1st
JOptionPane.showMessageDialog(null,f.isVisible());
}
if(event == 5){
JPanel p4 = new JPanel(new BorderLayout());
p4.setBounds(0,140,500,55);
Class2 c2o = new Class2();
Dimension d2 = new Dimension(500,55);
c2o.setPreferredSize(d2);
p4.setPreferredSize(d2);
p4.add(c2o);
gbc.insets = new Insets(0,0,-130,0);
gbc.gridx = 0;
gbc.gridy = 0;
f.add(p4,gbc);
f.invalidate();
f.validate();
f.repaint();
//2nd
JOptionPane.showMessageDialog(null,f.isVisible());
}
}
}
The revalidate and repaint doesn't work. I have an layout manager, so I suspect the problem is with the if statements. The 1st time I test the visibility of f, it returned true. The second time I tested the same thing, it returned false. Why doesn't my revalidate and repaint work? How I need to do to get it to work?
There are some issues with this code, but the major one is the scope of your JFrame reference f.
Assumed that you are calling the method somehow like in this main sample:
public static void main(String[] args) {
Class4 c = new Class4();
c.mainMethod(0);
c.mainMethod(5);
}
Then, your code is creating a second JFrame during the second call.
Move the JFrame creation into the constructor and make f a member variable:
public class Class4 {
private JFrame f;
public Class4() {
f = new JFrame("Love Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,200);
f.setLayout(new GridBagLayout());
}
// ...
}
You can then modify the JFrame in subsequent calls of the mainMethod().
Some additional notes:
Avoid reusing GridBagConstraints. Create them through the constructor. This makes the code much more robust.
You do not need to get the contentPane from the JFrame anymore (as suggested in an other answer). As of Java 1.5, the add() methods of JFrame directly delegate to the content pane.
There is no need to do invalidate() or repaint() when adding components to the JFrame. add() already invalidates the component hierarchy. However, you need to call validate() when the component has already been shown (as in your case). See java.awt.Container.add() for more information.
if(event == 5){
JPanel p4 = new JPanel(new BorderLayout());
p4.setBounds(0,140,500,55);
Class2 c2o = new Class2();
Dimension d2 = new Dimension(500,55);
c2o.setPreferredSize(d2);
p4.setPreferredSize(d2);
p4.add(c2o);
gbc.insets = new Insets(0,0,-130,0);
gbc.gridx = 0;
gbc.gridy = 0;
f.add(p4,gbc);
f.invalidate();
f.validate();
f.repaint();
//2nd
JOptionPane.showMessageDialog(null,f.isVisible());
}
The frame f it isn't visible(missing the f.setVisible(true); ), so not need to be revalidated and repainted in this case, it will not be visible for user.
Also use a logger or a breakpoint to test f.isVisible() because that will block the ui.
I'm having trouble seeing exactly what you're looking for. An SSCCE would really help. Is this what you're looking for?
import java.awt.*;
import javax.swing.*;
class Canv extends JComponent {
GridBagConstraints gbc;
public Canv (int event) {
gbc = new GridBagConstraints();
switch(event)
{
case 0:
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
this.setBounds(150, 0, 500, 75);
this.setPreferredSize(new Dimension(150,75));
JTextField boy = new JTextField();
boy.setMaximumSize(new Dimension(200,40));
JTextField girl = new JTextField();
girl.setMaximumSize(new Dimension(200,40));
this.add(boy);
this.add(girl);
gbc.insets = new Insets(-90,310,0,0);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(this,gbc);
JPanel p3 = new JPanel(new BorderLayout());
p3.setBounds(0, 0, 150, 75);
p3.setPreferredSize(new Dimension(150,75));
//Class5 c5o = new Class5();
//c5o.setPreferredSize(new Dimension(150,75));
//p3.add(c5o);
gbc.insets = new Insets(0,0,90,330);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(p3,gbc);
JPanel p2 = new JPanel(new FlowLayout());
//Class7 c7o = new Class7();
//p2.add(c7o);
p2.setPreferredSize(new Dimension(300,40));
gbc.insets = new Insets(0,0,-20,0);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(p2,gbc);
break;
case 5:
JPanel p4 = new JPanel(new BorderLayout());
p4.setBounds(0,140,500,55);
//Class2 c2o = new Class2();
Dimension d2 = new Dimension(500,55);
//c2o.setPreferredSize(d2);
p4.setPreferredSize(d2);
//p4.add(c2o);
gbc.insets = new Insets(0,0,-130,0);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(p4,gbc);
//this.invalidate();
this.validate();
this.repaint();
JOptionPane.showMessageDialog(null,this.isVisible());
break;
default:
break;
}
}
public void paintComponent(){
}
}
public class Class4 {
static int event;
static JFrame frame;
static Canv canvas;
public static void main(String[] args)
{
frame = new JFrame("Love Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,200);
frame.setLayout(new GridBagLayout());
//event = Integer.parseInt(args[0]);
event = 5;
canvas = new Canv(event);
frame.add(canvas);
frame.setVisible(true);
}
}
Running the above code would return true in the dialog box. In order to change between events, just add another method in Class4 to reset Canv, by calling its constructor with a different event number.