I use Eclipse Window Builder. When I click the button, something will be written on the screen. But since my prints are long, I want to use a scroll pane.
public class uyg2 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
uyg2 frame = new uyg2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public uyg2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(32, 29, 89, 23);
contentPane.add(btnNewButton);
JTextArea textArea = new JTextArea();
textArea.setBounds(10, 63, 233, 173);
contentPane.add(textArea);
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(249, 10, 173, 118);
contentPane.add(scrollPane);
}
So, based on...
public class uyg1 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
uyg1 frame = new uyg1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public uyg1() {
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);
JTextArea textArea = new JTextArea("Test");
textArea.setSize(400, 400);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scroll);
frame.setVisible(true);
}
}
textArea.setSize(400, 400); is irrelevant as the layout manager will deal with it. You can provide sizing hints via the JTextArea(String, int, int) constructer, but remember, this is the number of characters in width/height, not pixels.
The following are giving you issues...
frame.getContentPane().add(scroll);
frame.setVisible(true);
because frame is undefined. Since the class extends from JFrame, they are pointless, it should just be
getContentPane().add(scroll);
setVisible(true);
but, I'd add...
pack();
setLocationRelativeTo(null);
before it, as it will give you a generally better experience
You need to add the TextArea to the ScrollPane. Don't add the textarea tho the contentpane.
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");
}
});
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...
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.
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.