Neither setContentPane() nor getContentPane().add() works - java

I can provide all of my code if that would aid in the problem, but I believe since this only affects one class really, it can be solved here, to simplify the issue.
I have a solitaire project (mind the package/class name, it was trial and error and I didn't delete the old projects) that refuses to accept the GameArea class I have, which extends JPanel. The GameArea works fine in its own separate instance where the tester class runs with only the JPanel on the JFrame. That tester class uses setContentPane(newGame) to add it to the JFrame.
In the class below, neither getContentPane().add(newGame) nor setContentPane(newGame) successfully adds the game to the frame. This class sets up a main menu, with two buttons. The first one takes it into the Start New Game screen, and then the button which is supposed to start the game will either:
1) show only a green screen if getContentPane().add(newGame) is used
2) show a pressed Start New Game, and then freeze on the Start New Game screen if setContentPane(newGame) is used. This is frustrating because getContentPane().removeAll() is called before this...However, using the menu, I can return to the main menu and still run in that infinite loop of freeze and fix.
I suspect because I don't know enough about swing classes yet that I'm missing something. Any help is greatly appreciated, since I need to have this done in 2 days.
package guitestersolitairenew;
/**
*
* #author Josh
* #version 1.00 2015/3/28
*/
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import static javax.swing.Action.MNEMONIC_KEY;
import static javax.swing.Action.SHORT_DESCRIPTION;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.GroupLayout;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class GUITesterSolitaireNew extends JFrame
{
public GUITesterSolitaireNew()
{
initComponents();
setMainMenu();
}
private void initComponents()
{
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(80, 135, 40));
setTitle("Klondike Solitaire");
getContentPane().setBackground(new java.awt.Color(85,130,40));
setSize(1200,700);
setLocationRelativeTo(null);
setResizable(false);
JMenuBar menubar = new JMenuBar();
menubar.add(new JMenu("File"));
class MainMenu extends AbstractAction
{
public MainMenu(String text, ImageIcon icon, String desc, Integer mnemonic)
{
super(text,icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e)
{
setMainMenu();
}
}
menubar.getMenu(0).add(new JMenuItem(new MainMenu("Main Menu", null, "Return to the main menu.", KeyEvent.VK_M)));
class NewGame extends AbstractAction
{
public NewGame(String text, ImageIcon icon, String desc, Integer mnemonic)
{
super(text,icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e)
{
newGame(e);
}
}
menubar.getMenu(0).add(new JMenuItem(new NewGame("New Game", null, "Start a new game.", KeyEvent.VK_N)));
class RestartGame extends AbstractAction
{
public RestartGame(String text, ImageIcon icon, String desc, Integer mnemonic)
{
super(text,icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e)
{
//Fix to restart game.
}
}
menubar.getMenu(0)
.add(new JMenuItem(new RestartGame("Restart Game", null, "Restart the current game.", KeyEvent.VK_R)));
class LoadGame extends AbstractAction
{
public LoadGame(String text, ImageIcon icon, String desc, Integer mnemonic)
{
super(text,icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e)
{
//Fix to load game.
}
}
menubar.getMenu(0).add(new JMenuItem(new LoadGame("Load Game", null, "Load a saved game.", KeyEvent.VK_L)));
class SaveGame extends AbstractAction
{
public SaveGame(String text, ImageIcon icon, String desc, Integer mnemonic)
{
super(text,icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e)
{
//Fix to save game
}
}
menubar.getMenu(0).add(new JMenuItem(new SaveGame("Save Game", null, "Create a save file.", KeyEvent.VK_S)));
class ExitAction extends AbstractAction
{
public ExitAction (String text, ImageIcon icon, String desc, Integer mnemonic)
{
super(text, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
menubar.getMenu(0).add(new JMenuItem(new ExitAction("Exit", null, "Exit from the program.", KeyEvent.VK_E)));
menubar.add(new JMenu("Help"));
class Rules extends AbstractAction
{
public Rules (String text, ImageIcon icon, String desc, Integer mnemonic)
{
super(text, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e)
{
JFrame rules = new JFrame("Klondike Solitaire Rules");
rules.setSize(400,430);
rules.setLocationRelativeTo(null);
rules.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JTextArea jta = new JTextArea();
jta.setEditable(false);
Component add = rules.add(jta);
JScrollPane jsp = new JScrollPane();
jsp.setViewportView(jta);
rules.getContentPane().add(jsp, java.awt.BorderLayout.CENTER);
jta.setCaretPosition(jta.getText().length());
jta.append("Klondike Solitaire Rules:\n\n");
jta.setCaretPosition(jta.getText().length());
jta.append("The game starts with a standard 52 card deck.\n");
jta.setCaretPosition(jta.getText().length());
jta.append("The cards are first dealt into 7 'tableaus' where the cards\n");
jta.setCaretPosition(jta.getText().length());
jta.append("are all turned face down and one card laid onto each tableau.\n");
jta.setCaretPosition(jta.getText().length());
jta.append("The left one is turned up, and the process is repeated for the\n");
jta.setCaretPosition(jta.getText().length());
jta.append("2nd to 7th tableaus. The 2nd card in the 2nd tableau is turned up.\n");
jta.setCaretPosition(jta.getText().length());
jta.append("Each tableau receives as many cards as the column position. The\n");
jta.setCaretPosition(jta.getText().length());
jta.append("last card in each tableau will be face up. The deck is placed\n");
jta.setCaretPosition(jta.getText().length());
jta.append("off to the side.\n\n");
jta.setCaretPosition(jta.getText().length());
jta.append("The cards are drawn one at a time from deck. Valid moves are: \n");
jta.setCaretPosition(jta.getText().length());
jta.append("-Move card from deck to tableau\n");
jta.setCaretPosition(jta.getText().length());
jta.append("-Move card from deck to foundation <stacks by suit>\n");
jta.setCaretPosition(jta.getText().length());
jta.append("-Click deck again for another card.\n");
jta.setCaretPosition(jta.getText().length());
jta.append("The deck is cycled if cards are remaining. The cards, after\n");
jta.setCaretPosition(jta.getText().length());
jta.append("being face up, will sort in descent of value and opposing\n");
jta.setCaretPosition(jta.getText().length());
jta.append("face color: i.e. a black 6 can only go on top of a red 7.\n\n");
jta.setCaretPosition(jta.getText().length());
jta.append("The player wins by moving all cards from the deck and tableaus\n");
jta.setCaretPosition(jta.getText().length());
jta.append("to the 4 foundations. The foundations sort by suit in ascending\n");
jta.setCaretPosition(jta.getText().length());
jta.append("order of value, starting with the ace. All aces are low.");
rules.setResizable(false);
rules.setVisible(true);
}
}
menubar.getMenu(1)
.add(new JMenuItem(new Rules("Rules", null, "Show a popup aid for the rules of the game.", KeyEvent.VK_R)));
class Info extends AbstractAction
{
public Info (String text, ImageIcon icon, String desc, Integer mnemonic)
{
super(text, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e)
{
JFrame info = new JFrame("Development Info");
info.setSize(450,225);
info.setLocationRelativeTo(null); //sends it to center of screen
info.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); //does not close application, but actually kills the window when closed
JTextArea jta = new JTextArea();
jta.setEditable(false); //The user can't type on the text box.
Component add = info.add(jta); //abstraction that adds the component jta to window info
JScrollPane jsp = new JScrollPane();
jsp.setViewportView(jta); //puts the text area in the scroll pane
info.getContentPane().add(jsp, java.awt.BorderLayout.CENTER); //centers the text area and scroll pane to be the main subject of the frame
jta.setCaretPosition(jta.getText().length()); //sets the cursor to the end of the text typed so far
//edited out
info.setResizable(false);
info.setVisible(true);
}
}
menubar.getMenu(1)
.add(new JMenuItem(new Info("Info", null, "Information about Klondike Solitaire.", KeyEvent.VK_I)));
setJMenuBar(menubar);
}
private void newGame(java.awt.event.ActionEvent evt)
{
getContentPane().removeAll();
getContentPane().repaint();
setBackground(new java.awt.Color(80, 135, 40));
JLabel jLabel1 = new JLabel();
JButton jButton1 = new JButton();
jLabel1.setBackground(new java.awt.Color(80, 135, 40));
jLabel1.setFont(new java.awt.Font("Kunstler Script", 1, 120)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Klondike Solitaire");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setMaximumSize(new java.awt.Dimension(800, 100));
jLabel1.setMinimumSize(new java.awt.Dimension(800, 100));
jLabel1.setPreferredSize(new java.awt.Dimension(800, 100));
jLabel1.setRequestFocusEnabled(true);
jButton1.setText("Start New Game");
jButton1.setFont(new java.awt.Font("Times New Roman", 1, 20));
jButton1.setMaximumSize(new java.awt.Dimension(200, 50));
jButton1.setMinimumSize(new java.awt.Dimension(200, 50));
jButton1.setPreferredSize(new java.awt.Dimension(200, 50));
jButton1.addActionListener(new java.awt.event.ActionListener()
{
#Override
public void actionPerformed(java.awt.event.ActionEvent evt)
{
startNewGame();
}
});
JLabel replay = new JLabel("Replay game from seed:");
replay.setBackground(new java.awt.Color(80,135,40));
replay.setFont(new java.awt.Font("Times New Roman", 1, 20));
replay.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
replay.setVerticalAlignment(javax.swing.SwingConstants.CENTER);
replay.setMaximumSize(new java.awt.Dimension(220, 50));
replay.setMinimumSize(new java.awt.Dimension(220, 50));
replay.setPreferredSize(new java.awt.Dimension(220, 50));
JTextField getSeed = new JTextField();
getSeed.setCaretPosition(getSeed.getText().length());
getSeed.setFont(new java.awt.Font("Times New Roman", 1, 18));
getSeed.setMaximumSize(new java.awt.Dimension(150, 24));
getSeed.setMinimumSize(new java.awt.Dimension(150, 24));
getSeed.setPreferredSize(new java.awt.Dimension(150, 24));
JButton startSeed = new JButton("Start Game");
startSeed.setFont(new java.awt.Font("Times New Roman", 1, 20));
startSeed.setMaximumSize(new java.awt.Dimension(130, 30));
startSeed.setMinimumSize(new java.awt.Dimension(130, 30));
startSeed.setPreferredSize(new java.awt.Dimension(130, 30));
startSeed.addActionListener(new java.awt.event.ActionListener()
{
#Override
public void actionPerformed(java.awt.event.ActionEvent evt)
{
startNewGame(Integer.parseInt(getSeed.getText()));
}
});
JButton back = new JButton("Back to Main Menu");
back.setFont(new java.awt.Font("Times New Roman", 1, 20));
back.setMaximumSize(new java.awt.Dimension(200, 50));
back.setMinimumSize(new java.awt.Dimension(200, 50));
back.setPreferredSize(new java.awt.Dimension(200, 50));
back.addActionListener(new java.awt.event.ActionListener()
{
#Override
public void actionPerformed(java.awt.event.ActionEvent evt)
{
setMainMenu();
}
});
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addGap(200, 200, 200)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER, false)
.addComponent(back, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(replay, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(getSeed, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(startSeed, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jButton1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(200, 200, 200)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(90, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(150, 150, 150)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(jButton1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(replay, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(getSeed, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(startSeed, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(180, 180, 180)
.addComponent(back, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
);
}
private void startNewGame()
{
getContentPane().removeAll();
getContentPane().repaint();
newGame.newGame();
Container pane = getContentPane();
pane.add(newGame);
setContentPane(pane);
getContentPane().revalidate();
getContentPane().repaint();
}
public void startNewGame(int seed)
{
getContentPane().removeAll();
getContentPane().repaint();
newGame.newGame();
add(newGame);
}
private void setMainMenu()
{
getContentPane().removeAll();
getContentPane().repaint();
setBackground(new java.awt.Color(80, 135, 40));
JLabel jLabel1 = new javax.swing.JLabel();
JButton jButton1 = new javax.swing.JButton();
JButton jButton2 = new javax.swing.JButton();
jLabel1.setBackground(new java.awt.Color(80, 135, 40));
jLabel1.setFont(new java.awt.Font("Kunstler Script", 1, 120)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Klondike Solitaire");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setMaximumSize(new java.awt.Dimension(800, 100));
jLabel1.setMinimumSize(new java.awt.Dimension(800, 100));
jLabel1.setPreferredSize(new java.awt.Dimension(800, 100));
jLabel1.setRequestFocusEnabled(true);
jButton1.setText("New Game");
jButton1.setFont(new java.awt.Font("Times New Roman", 1, 20));
jButton1.setMaximumSize(new java.awt.Dimension(200, 50));
jButton1.setMinimumSize(new java.awt.Dimension(200, 50));
jButton1.setPreferredSize(new java.awt.Dimension(200, 50));
jButton1.addActionListener(new java.awt.event.ActionListener()
{
#Override
public void actionPerformed(java.awt.event.ActionEvent evt)
{
newGame(evt);
}
});
jButton2.setText("Load Game");
jButton2.setFont(new java.awt.Font("Times New Roman", 1, 20));
jButton2.setMaximumSize(new java.awt.Dimension(200, 50));
jButton2.setMinimumSize(new java.awt.Dimension(200, 50));
jButton2.setPreferredSize(new java.awt.Dimension(200, 50));
GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addGap(200, 200, 200)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER, false)
.addComponent(jButton2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(200, 200, 200)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(90, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(150, 150, 150)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(jButton1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(5, 5, 5)
.addComponent(jButton2)
.addContainerGap(120, Short.MAX_VALUE))
);
}
/**
* #param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
System.out.println("Main.main(): 492");
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(GUITesterSolitaireNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new GUITesterSolitaireNew().setVisible(true);
}
});
}
private javax.swing.JInternalFrame jInternalFrame1;
private GameArea newGame = new GameArea();
}

Don't use setContentPane to switch views, use a CardLayout, that's what it's designed for. See How to Use CardLayout for more details
Also, there's little point to doing this...
setContentPane(pane);
getContentPane().revalidate();
getContentPane().repaint();
In this instance, it's not the contentPane that needs to be revalidated, it's the contentPanes parent...

Related

Counter reset not working in Java

In my program it has two JButton with name Start and Reset to 0 and one JTextField and one JLabel. When I click to Start JButton number of times its show the result in JTextField.
If count number is equal to 1 it show message Start in JLabel and when count is greater than 1 it show the Reset to 0 in JLabel. But the problem is when I click on Reset to 0 JButton it reset to 1 but it not showing message Reset to 0 in JLabel?
Program is here:
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import com.alee.laf.rootpane.WebFrame;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class Search {
private WebFrame frame;
private JTextField textField;
private JButton btnResetTo;
private JButton btnNewButton;
private int count;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Search window = new Search();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Search() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new WebFrame();
frame.setBounds(100, 100, 296, 374);
frame.setDefaultCloseOperation(WebFrame.EXIT_ON_CLOSE);
btnNewButton = new JButton("Start");
btnNewButton.addMouseListener(new MouseAdapter() {
private int Qnty;
#Override
public void mouseClicked(MouseEvent e) {
count=e.getClickCount();
textField.setText(Integer.toString(count));
Qnty=Qnty+count;
if(Qnty==1)
lblNewLabel.setText("Start");
else if(Qnty>1)
{
lblNewLabel.setText("Reset");
}
}
});
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.BOLD, 40));
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setColumns(10);
btnResetTo = new JButton("Reset to 0");
btnResetTo.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
count=e.getClickCount();
count=0;
}
});
lblNewLabel = new JLabel("");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(lblNewLabel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
.addComponent(btnResetTo, GroupLayout.PREFERRED_SIZE, 136, GroupLayout.PREFERRED_SIZE))
.addComponent(textField, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(25)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(btnResetTo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnNewButton, GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)
.addGap(31)
.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)
.addGap(73))
);
frame.getContentPane().setLayout(groupLayout);
}
}
Use a ActionListener instead of MouseListener on your buttons - buttons can be trigged in more ways then just clicking on them. See How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details
When reset is called, you actually need to change the components, like you did with btnNew - the variables aren't magically linked to the components
Maybe like
btnResetTo = new JButton("Reset to 0");
btnResetTo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count = 0;
textField.setText(Integer.toString(count));
lblNewLabel.setText("Start");
}
});

Position JPanel on JFrame

I have a problem with JPanel location. I started the creating a small game... I created 2 panels in design (on a JFrame). All worked good and the panels were on the correct places. In my game I have to use 2 graphic tables so I use 2 panels and I add every one of them panel set layout (new Grid Layout(10,10)).
After that I run the project to see how it works and I discover my panels in other places and with another size. I found the way that helps my to change back the size but I cannot found the way to change back the location or a way to give my own location...
I tried to add pictures that can show you what I see but the site blocked the pictures...
The code is:
public class GameFrame extends javax.swing.JFrame {
int [][]p1;
int [][]p1Attac;
int [][]p2;
int [][]p2Attac;
static int size=10;
int player;
JPanel [][]b1;
JPanel [][]b2;
int w=1100,h=900;
/**
* Creates new form GameFrame
* #param player1
* #param player2
*/
public GameFrame(int [][]player1, int [][]player2) {
initComponents();
// setSize(w, h);
setVisible(true);
// size=10;
p1=new int[size][size];
p1Attac=new int[size][size];
p2=new int[size][size];
p2Attac=new int[size][size];
b1=new JPanel[size][size];
b2=new JPanel[size][size];
init(player1, player2);
leftBoard.setBackground(Color.red);
rightBoard.setBackground(Color.blue);
GridLayout gl=new GridLayout(size, size);
leftBoard.setLayout(gl);
rightBoard.setLayout(gl);
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
b1[i][j]=new JPanel();
b1[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
b1[i][j].setBackground(Color.red);
b2[i][j]=new JPanel();
b2[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
b2[i][j].setBackground(Color.blue);
leftBoard.add(b1[i][j]);
rightBoard.add(b2[i][j]);
}
}
leftBoard.setPreferredSize(new Dimension(w/2-50, h/2));
rightBoard.setPreferredSize(new Dimension(w/2-50, h/2));
// leftBoard.setIgnoreRepaint(true);
// leftBoard.setLocation(0, h/5);
}
public void init(int [][]player1,int [][]player2){
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
p1[i][j]=player1[i][j];
p2[i][j]=player2[i][j];
p1Attac[i][j]=0;
p2Attac[i][j]=0;
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
leftBoard = new javax.swing.JPanel();
rightBoard = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout leftBoardLayout = new javax.swing.GroupLayout(leftBoard);
leftBoard.setLayout(leftBoardLayout);
leftBoardLayout.setHorizontalGroup(
leftBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 523, Short.MAX_VALUE)
);
leftBoardLayout.setVerticalGroup(
leftBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 498, Short.MAX_VALUE)
);
javax.swing.GroupLayout rightBoardLayout = new javax.swing.GroupLayout(rightBoard);
rightBoard.setLayout(rightBoardLayout);
rightBoardLayout.setHorizontalGroup(
rightBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 547, Short.MAX_VALUE)
);
rightBoardLayout.setVerticalGroup(
rightBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 498, Short.MAX_VALUE)
);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel1.setText("Enemy Attacs:");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel2.setText("Your Attacs:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(leftBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(118, 118, 118)
.addComponent(rightBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(193, 193, 193)
.addComponent(jLabel2)))
.addContainerGap(43, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(leftBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rightBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(65, 65, 65))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*int [][]p1=new int[size][size];
int [][]p2=new int[size][size];
for(int i=0;i<size;i++)
for(int j=0;j<size;j++){
p1[i][j]=0;
p2[i][j]=0;
}
p1[0][0]=p1[1][0]=p1[2][0]=p1[3][0]=4;
p1[0][3]=p1[1][3]=p1[2][3]=3;
p1[5][3]=p1[6][3]=p1[7][3]=3;
p1[0][3]=p1[1][3]=2;*/
int [][]p1={
{4,4,4,4,0,1,0,0,0,0},
{0,0,0,0,0,0,0,1,0,0},
{3,3,3,0,3,0,0,0,0,0},
{0,0,0,0,3,0,0,0,0,0},
{2,2,0,0,3,0,0,1,0,0},
{0,0,0,0,0,1,0,0,0,0},
{0,0,0,0,0,0,0,2,2,0},
{0,0,0,5,0,0,0,0,0,0},
{0,0,0,0,0,0,5,0,2,2},
{0,0,0,0,0,0,0,0,0,0}
};
int [][]p2={
{0,1,0,0,1,0,0,2,2,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,1,0,1,0,2,2,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,5,0,0,3,0,0,2,0,0},
{0,0,0,0,3,0,0,2,0,0},
{0,0,0,0,3,0,0,0,0,0},
{0,0,0,0,0,0,4,4,4,4},
{0,3,3,3,0,0,0,0,0,0},
{0,0,0,0,0,0,5,0,0,0}
};
new GameFrame(p1, p2);
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new GameFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel leftBoard;
private javax.swing.JPanel rightBoard;
// End of variables declaration
}
Thanks to #AndrewThompson for giving important ideas for this problem (GridLayout, Titled Borders). I've waited about 30 minutes to see if he'd post his own answer. He didn't, so I decided to post my own - I hope no-one is mad at me.
Don't use Grouplayout for this, IMO it just makes things complicated and user-unfriendly (at least in this case). Instead you can achieve everything with simple GridLayouts. (with much less code, resizeable) I've created an example that shows you how:
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class GameFrame {
JPanel[][] arrayL = new JPanel[10][10];
JPanel[][] arrayR = new JPanel[10][10];
public GameFrame() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new GridLayout(1, 2));
JPanel left = new JPanel(new GridLayout(10, 10, 1, 1));
left.setBorder(BorderFactory.createTitledBorder(new EmptyBorder(0, 0,
0, 0), "Enemy"));
((TitledBorder) left.getBorder()).setTitleFont(new Font("Arial", Font.BOLD, 20));
addCells(left, arrayL, Color.RED);
JPanel right = new JPanel(new GridLayout(10, 10, 1, 1));
right.setBorder(BorderFactory.createTitledBorder(new EmptyBorder(0, 0,
0, 0), "You"));
((TitledBorder) right.getBorder()).setTitleFont(new Font("Arial", Font.BOLD, 20));
addCells(right, arrayR, Color.BLUE);
JPanel leftPanel = new JPanel();
leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
leftPanel.setLayout(new GridLayout(1, 1));
leftPanel.add(left);
JPanel rightPanel = new JPanel();
rightPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
rightPanel.setLayout(new GridLayout(1, 1));
rightPanel.add(right);
frame.getContentPane().add(leftPanel);
frame.getContentPane().add(rightPanel);
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void addCells(JPanel panel, JPanel[][] array, Color color) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
JPanel p = new JPanel();
p.setBackground(color);
p.setBorder(BorderFactory.createLineBorder(Color.BLACK));
array[j][i] = p;
panel.add(p);
}
}
}
public static void main(String[] args) {
new GameFrame();
}
}
One issue is that the initComponents() generated by the Netbeans GUI builder has layout which is being messed up by the code run later in the constructor.
The way to fix this is using the Customize Code .. right-click menu option in the designer. Putting your code there will allow you to keep the outer design set by the Gui Builder and add internal custom components. After that you can comment out all the code in the constructor.

JFrames load blank

I'm trying to make a program that uses Swing for the GUI, but the form that opens up when I run the code below is blank. I'm still able to get information regarding the objects that aren't seen, however (tested with getting btnLogin.getText()). Am I missing something, or am I doing something wrong?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class loginForm extends JFrame implements ActionListener{
public static void main(String[] args){
new loginForm();
}
public loginForm() {
System.out.println("Starting...");
pack();
initComponents();
System.out.println("Opened");
this.setVisible(true);
}
private void initComponents() {
loginForm = new JFrame();
lblUserID = new JLabel();
existingUserIDTextField = new JTextField();
lblPassword = new JLabel();
existingUserPasswordField = new JPasswordField();
btnLogin = new JButton();
btnLogin.addActionListener(this);
lblWelcome = new JLabel();
//======== loginForm ========
{
loginForm.setResizable(false);
loginForm.setTitle("Library Reservation System");
Container loginFormContentPane = loginForm.getContentPane();
//---- lblUserID ----
lblUserID.setText("User ID:");
lblUserID.setFont(new Font("Tahoma", Font.PLAIN, 16));
//---- lblPassword ----
lblPassword.setText("Password:");
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 16));
//---- btnLogin ----
btnLogin.setText("Login");
//---- lblWelcome ----
lblWelcome.setText("Welcome to our Library Reservation System");
lblWelcome.setFont(new Font("Tahoma", Font.PLAIN, 16));
GroupLayout loginFormContentPaneLayout = new GroupLayout(loginFormContentPane);
loginFormContentPane.setLayout(loginFormContentPaneLayout);
loginFormContentPaneLayout.setHorizontalGroup(
loginFormContentPaneLayout.createParallelGroup()
.addGroup(loginFormContentPaneLayout.createSequentialGroup()
.addGroup(loginFormContentPaneLayout.createParallelGroup()
.addGroup(loginFormContentPaneLayout.createSequentialGroup()
.addGap(199, 199, 199)
.addComponent(btnLogin, GroupLayout.PREFERRED_SIZE, 145, GroupLayout.PREFERRED_SIZE))
.addGroup(loginFormContentPaneLayout.createSequentialGroup()
.addGap(72, 72, 72)
.addGroup(loginFormContentPaneLayout.createParallelGroup()
.addComponent(lblUserID, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)
.addComponent(lblPassword))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(loginFormContentPaneLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(existingUserIDTextField, GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
.addComponent(existingUserPasswordField, GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)))
.addGroup(GroupLayout.Alignment.TRAILING, loginFormContentPaneLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblWelcome, GroupLayout.PREFERRED_SIZE, 318, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(118, Short.MAX_VALUE))
);
loginFormContentPaneLayout.setVerticalGroup(
loginFormContentPaneLayout.createParallelGroup()
.addGroup(loginFormContentPaneLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblWelcome, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
.addGap(11, 11, 11)
.addGroup(loginFormContentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblUserID)
.addComponent(existingUserIDTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(loginFormContentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblPassword)
.addComponent(existingUserPasswordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(btnLogin)
.addContainerGap(12, Short.MAX_VALUE))
);
loginForm.pack();
loginForm.setLocationRelativeTo(loginForm.getOwner());
}
}
private JFrame loginForm;
private JLabel lblUserID;
private JTextField existingUserIDTextField;
private JLabel lblPassword;
private JPasswordField existingUserPasswordField;
private JButton btnLogin;
private JLabel lblWelcome;
}
The frame containing the controls is never displayed.
loginForm.setVisible(true);
Instead of having an outer redundant frame class you could do
public class LoginFormApp extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
LoginFormApp loginFormApp = new LoginFormApp();
loginFormApp.initComponents();
}
});
.....
}
where initComponents makes the loginForm visible as previously stated.

Adding a Set of JTextFields to a Panel at Runtime, Different Layout Manager

I am trying to make a set of two JTextfields (side by side) appear inside of a panel when a button is clicked. The problem is that something like Flowlayout will make my textfields move all over the place (they line up in a single row or column), and Gridlayout makes the textfields far too big. I have investigated Springlayout and Grouplayout, but these layouts don't seem to have a straightforward way to add a component at runtime (plus the code is really messy looking to me, as seen in the example below).
This is an example of what I am trying to achieve with the layout...run the code and pay attention to how the JTextfields react when you resize the window (the add set of fields button doesn't work, because I am unsure of how to add components to the panel with the Grouplayout in place):
GoodLayout.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
public class GoodLayout extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GoodLayout frame = new GoodLayout();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GoodLayout() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 383, 328);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JButton buttonAddFields = new JButton("+ Add Set of Fields +");
buttonAddFields.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Add a set of fields to the panel");
}
});
contentPane.add(buttonAddFields, BorderLayout.SOUTH);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
textField = new JTextField();
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setColumns(10);
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField_1, GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE))
.addGroup(gl_panel.createSequentialGroup()
.addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField_3, GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE))
.addGroup(gl_panel.createSequentialGroup()
.addComponent(textField_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField_5, GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE)))
.addContainerGap())
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(textField_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(287, Short.MAX_VALUE))
);
panel.setLayout(gl_panel);
}
}
The important bit in the code above is the actionPerformed method...I would really like to find a simple solution that looks good (GUI layout-wise) when the button is clicked and a pair of textfields appear. Maybe there is a better layout for this? I used the Eclipse plugin WindowBuilder to build the code above, and I have tried all of the different layout options that seemed reasonable to try.
Any ideas or tricks about how to better tackle this problem are appreciated
Thanks, Dan
Do not discard the GroupLayout manager -- it is a very capable layout manager
and is one of the few managers that does things properly.
However, it is not suited for dynamic layout constructions due to the
way the layout is built. We would have to completely redo our layout and
do ad hoc calculations.
For this, we can easily use MigLayout. MigLayout is a third-party layout
manager that also does things properly. It is easy to use and very powerful.
package com.zetcode;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class GoodLayout2 extends JFrame {
private JPanel pnl;
public GoodLayout2() {
initUI();
setTitle("MigLayout solution");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void initUI() {
JButton addBtn = new JButton("Add");
addBtn.addActionListener(new AddAction());
pnl = new JPanel(new MigLayout("ins dialog, wrap 2"));
pnl.add(addBtn, "span 2, center");
pnl.add(new JTextField(10));
pnl.add(new JTextField(10), "pushx, growx");
pnl.add(new JTextField(10));
pnl.add(new JTextField(10), "pushx, growx");
pnl.add(new JTextField(10));
pnl.add(new JTextField(10), "pushx, growx");
add(pnl);
pack();
}
private class AddAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
pnl.add(new JTextField(10));
pnl.add(new JTextField(10), "pushx, growx");
pnl.doLayout();
pnl.repaint();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GoodLayout2 ex = new GoodLayout2();
ex.setVisible(true);
}
});
}
}
I have placed the button to the north part of the window, since the code
is then slightly less complicated.

Cannot add JScrollPane to JTextArea in GroupLayout

Here is the code for what I tried but the scroll pane is not showing up and am using Group-layout.
import java.awt.BorderLayout;
public class JScrollPanel extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JScrollPanel frame = new JScrollPanel();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JScrollPanel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
**final JTextArea textArea = new JTextArea();
JScrollPane scrollpanedreapta = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
contentPane.add(scrollpanedreapta, null);**
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(31)
.addComponent(textArea, GroupLayout.PREFERRED_SIZE, 339, GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(31)
.addComponent(textArea, GroupLayout.PREFERRED_SIZE, 172, GroupLayout.PREFERRED_SIZE)
.addContainerGap(49, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
}
When I launch the code, it works fine and when I overflow the Text-area, both scroll-panes are not showing up. Any Help Guys.
You should add the JScrollPane to your layout groups instead of JTextArea, i.e. replace
.addComponent(textArea, ...)
with
.addComponent(scrollpanedreapta, ...)
two times.

Categories

Resources