Add JTextField to JToolBar - java

I'm trying to add JTextField to JToolBar and it works, but it is too long. I need it to take only 3 letters.
Here is the screenshot of it now...
I tried following methods,
JTextField field = new JextField(3); // thought this limits to three characters.
And I tried,
field.setColumns(3); // this didn't work either.

The default layout of a tool-bar respects the maximum size set for a text field.
import java.awt.*;
import javax.swing.*;
public class TextFieldInToolBar {
TextFieldInToolBar() {
JPanel p = new JPanel(new BorderLayout());
JToolBar tb = new JToolBar();
p.add(tb, BorderLayout.PAGE_START);
Icon disk = (Icon)UIManager.get("FileView.floppyDriveIcon");
Icon pc = (Icon)UIManager.get("FileView.computerIcon");
tb.add(new JButton(disk));
JTextField tf = new JTextField(3);
tf.setMaximumSize(tf.getPreferredSize());
tb.add(tf);
tb.addSeparator();
tb.add(new JButton(pc));
p.setPreferredSize(new Dimension(250,50));
JOptionPane.showMessageDialog(null, p);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TextFieldInToolBar();
}
});
}
}

JToolBar is container as JFrame, JDialog or JWindow, you can laying this container by using the proper LayoutManager
this issue should be the same by using JMenuBar as container for JComponents (alternative)

Related

Add Object to JPanel after button click

I have created a JScrollPane with a JPanel inside it and I want to add JPanel/JLabel/Other objects after pressing the button. For example after three button presses I want to get something like this:
I tried myJPane.add(testLabel) with testlabel.setBounds()but no result, I don't want to use GridLayout because of the unchangeable sizes. I would like it if the added objects had different sizes - adjusted to the text content.
What should I use for it and how?
Thanks in advance.
Best regards,
Tom.
Here is a JPanel inside a JScrollPane that adds JLabels to it when pressing the button:
public class Example extends JFrame {
public Example() {
JPanel boxPanel = new JPanel();
boxPanel.setLayout(new BoxLayout(boxPanel, BoxLayout.PAGE_AXIS));
JTextField textField = new JTextField(20);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel label = new JLabel(textField.getText());
label.setOpaque(true);
label.setBackground(Color.RED);
boxPanel.add(label);
boxPanel.add(Box.createRigidArea(new Dimension(0,5)));
textField.setText("");
boxPanel.revalidate();
// pack();
}
});
JPanel southPanel = new JPanel();
southPanel.add(textField);
southPanel.add(sendButton);
add(new JScrollPane(boxPanel));
add(southPanel, BorderLayout.PAGE_END);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Example();
}
}
The BoxLayout will stack the labels on top of each other.
Notes:
setOpaque(true) must be called on label for it to honor the background color.
Box.createRigidArea is used for creating gaps. Use it as you wish.
The call to revalidate() is imperative in order to display the new components immediately.
Calling pack() (on the JFrame) will resize it each time to fit all the new components. I just put it there for demonstration since the initial frame size is too small to display the initial components added.
I will use a BoxLayout, creating a vertical box, and after each button action, it will add a new JPanel to this box.
Example:
public class YourChat extends JPanel{
private JScrollPane sc;
private Box bv;
public YourChat(){
bv = Box.createVerticalBox();
sc = new JScrollPane(bv);
//your functions (panel creation, addition of listeners, etc)
add(sc);
}
//panel customized to have red backgroud
private class MyPanel extends JPanel(){
private JLabel label=new JLabel();
public MyPanel(String text){
setBackgroundColor(Color.red);
add(label);
}
}
//inside the action listener
public void actionPerformed(ActionEvent e) {
sc.add(new MyPanel(textField.getText()));
textField.setText("");
}
}
For extra information check on:
[https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html]
See also the example
[http://www.java2s.com/Code/Java/Swing-JFC/VerticalandhorizontalBoxLayouts.htm]
Use BoxLayout if you want only add vertically, otherwise you can use FlowLayout for both directions.

Changing layout of a JPanel sent to JOptionPane with the pane still running

Trying to change the look of a JOptionPane while its open, depending on which radiobutton the user clicks. What am I doing wrong? It works perfect if I for example add a button and move a JLabel from side to side of the window.
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import static javax.swing.JOptionPane.*;
public class ChangePanel extends JFrame{
private JButton click = new JButton("CLICK ME!");
ChangePanel(){
add(click, BorderLayout.SOUTH);
click.addActionListener(new ButtonListen());
setVisible(true);
setSize(300,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public class ButtonListen implements ActionListener{
public void actionPerformed(ActionEvent e){
PopUpPanel pop = new PopUpPanel();
showConfirmDialog(ChangePanel.this, pop, "Changeable", OK_CANCEL_OPTION);
}
}
//Send this as Parameter to the ConfirmDialog
public class PopUpPanel extends JPanel implements ActionListener{
JRadioButton jewelry = new JRadioButton("Jewelry");
JRadioButton shares = new JRadioButton("Shares");
JRadioButton machine = new JRadioButton("Machine");
PopUpPanel(){
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
JPanel north = new JPanel();
bg.add(jewelry);
jewelry.addActionListener(this);
bg.add(shares);
shares.addActionListener(this);
bg.add(machine);
machine.addActionListener(this);
north.add(jewelry);
north.add(shares);
north.add(machine);
add(north);
}
//Listener for RadioButtons
public void actionPerformed(ActionEvent e){
JTextField info1Txt = new JTextField(12);
JTextField info2Txt = new JTextField(12);
JTextField info3Txt = new JTextField(3);;
JRadioButton b = (JRadioButton)e.getSource();
if(b.getText().equals("Jewelry")){
//Dummy test text
System.out.println("Jewelry");
JPanel info1 = new JPanel();
info1.add(new JLabel("info1:"));
info1.add(info1Txt);
add(info1);
JPanel info2 = new JPanel();
info2.add(new JLabel("info2:"));
info2.add(info2Txt);
add(info2);
JPanel info3 = new JPanel();
info3.add(new JLabel("info3:"));
info3.add(info3Txt);
add(info3);
validate();
repaint();
}else if(b.getText().equals("Shares")){
//Dummy test text
System.out.println("Shares");
}else
//Dummy test text
System.out.println("Machine");
}
}
public static void main(String[] args){
new ChangePanel();
}
}
As you are working with BoxLayout, you should provide size hints to the PopUpPanel panel, which you haven't given.
When a BoxLayout lays out components from top to bottom, it tries to size each component at the component's preferred height. If the vertical space of the layout does not match the sum of the preferred heights, then BoxLayout tries to resize the components to fill the space. The components either grow or shrink to fill the space, with BoxLayout honoring the minimum and maximum sizes of each of the components.
check out the official tutorial page discussion: BoxLayout Feature
Call revalidate() and repaint() on the container after removing or adding components to it. So if you change the following lines:
validate();
repaint();
to:
revalidate();
repaint();
The content should appear. Though, it will not fit the original size of the JOptionPane. You can override PopUpPanel.getPreferredSize() to return desired size so that JOptionPane is packed properly, ie:
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
You can also use JDialog instead of JOptionPane.
Also, consider using CardLayout instead of swapping components manually. Check How to Use CardLayout for examples.
Why not just use setPreferredSize(new Dimension(300, 300)) in PopUpPanel constructor? Works fine for me. Good eye on revalidate and repaint.

How to set the width of a JTextField at runtime?

Can someone please help me how to set the width of a JTextField at runtime? I want my text field to be resized on runtime. It will ask the user for the length, then the input will change the width of the text field.
if(selectedComponent instanceof javax.swing.JTextField){
javax.swing.JTextField txtField = (javax.swing.JTextField) selectedComponent;
//txtField.setColumns(numInput); //tried this but it doesn't work
//txtField.setPreferredSize(new Dimension(numInput, txtField.getHeight())); //also this
//txtField.setBounds(txtField.getX(), txtField.getY(), numInput, txtField.getHeight());
//and this
txtField.revalidate();
}
I am using null layout for this, since I'm on edit mode.
You simply need to use jTextFieldObject.setColumns(int columnSize). This will let you increase it's size at runtime. The reason why you couldn't do it at your end is the null Layout. That is one of the main reasons why the use of null Layout/Absolute Positioning is discouraged. Here is a small example for trying your hands on :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextFieldExample
{
private JFrame frame;
private JPanel contentPane;
private JTextField tfield;
private JButton button;
private int size = 10;
private ActionListener action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String input = JOptionPane.showInputDialog(
frame, "Please Enter Columns : "
, String.valueOf(++size));
tfield.setColumns(Integer.parseInt(input));
contentPane.revalidate();
contentPane.repaint();
}
};
private void createAndDisplayGUI()
{
frame = new JFrame("JTextField Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
tfield = new JTextField();
tfield.setColumns(size);
JButton button = new JButton("INC Size");
button.addActionListener(action);
contentPane.add(tfield);
contentPane.add(button);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JTextFieldExample().createAndDisplayGUI();
}
});
}
}
For absolute positioning you need to call setSize() on the JTextField in order to attain the result, though you should always keep in mind the reason why this approach is discouraged, as given in the Java Doc's first paragraph:
Although it is possible to do without a layout manager, you should use a layout manager if at all possible. A layout manager makes it easier to adjust to look-and-feel-dependent component appearances, to different font sizes, to a container's changing size, and to different locales. Layout managers also can be reused easily by other containers, as well as other programs.
I got the text field to resize just by using setBounds. Check out the following example:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Resize extends JFrame{
public JTextField jtf = new JTextField();
public Resize(){
//frame settings
setTitle("Resizable JTextField");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setSize(new Dimension(600,400));
setResizable(false);
//init and add text field to the frame
add(jtf);
jtf.setBounds(20,50,200,200);
//button to change text field size
JButton b = new JButton("Moar.");
add(b);
b.setBounds(20,20,b.getPreferredSize().width,b.getPreferredSize().height);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
jtf.setBounds(20,50,jtf.getSize().width+10,jtf.getSize().height); //THIS IS WHERE THE RESIZING HAPPENS
}
});
setVisible(true);
}
public static void main(String[] args){
Resize inst = new Resize();
}
}
"Fun" little run-it-yourself solution:
public static void main(String[] args) {
JFrame frame = new JFrame();
JTextField jTextField = new JTextField("Alice");
JPanel panel = new JPanel();
JButton grow = new JButton("DRINK ME");
JButton shrink = new JButton("EAT ME");
panel.add(jTextField);
panel.add(grow);
panel.add(shrink);
frame.add(panel);
frame.setVisible(true);
frame.pack();
grow.addActionListener(l -> resize(frame, jTextField, 2));
shrink.addActionListener(l -> resize(frame, jTextField, 0.5f));
}
private static void resize(JFrame frame, Component toResize, float factor) {
System.out.println(toResize.getPreferredSize());
toResize.setPreferredSize(new Dimension((int)(toResize.getPreferredSize().width * factor),
(int)(toResize.getPreferredSize().height * factor)));
toResize.setFont(toResize.getFont().deriveFont(toResize.getFont().getSize() * factor));
frame.pack();
}
Attention: Please note that the consumption of too much cake can kill you.

Java Swing: How can I implement a login screen before showing a JFrame?

I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).

Java CardLayout Main Menu Problem

Ok so im working on this game in java called 8 bit chimera. Im working on the main menu right now but when im using the card layout the window wont open for some reason. Here is some code.
import javax.swing.*;
import java.awt.*;
public class MainScreen extends JFrame{
String Title = "MainMenu";
MainMenuComp MMC = new MainMenuComp();
BreedingGround BGR = new BreedingGround();
public MainScreen() {
setTitle("8-bit Chimera "+Title);
setSize(800,600);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(MMC);
add(BGR);
}
public static void main(String[] args){
new MainScreen();
}
}
that was the Main window
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainMenuComp extends JPanel implements ActionListener{
BreedingGround BGR = new BreedingGround();
ImageData ID = new ImageData();
Image TitleBg;
Image Title;
CardLayout CL;
JButton Play;
public MainMenuComp() {
setLayout(new GridBagLayout());
GridBagConstraints GBC = new GridBagConstraints();
ImageIcon TitleData = new ImageIcon(ID.TitleSource);
ImageIcon TitleBackGroundData = new ImageIcon(ID.TitleBackGroundSource);
ImageIcon PlayData = new ImageIcon(ID.PlaySource);
TitleBg = TitleBackGroundData.getImage();
Title = TitleData.getImage();
Play = new JButton();
Play.setIcon(PlayData);
add(Play,GBC);
add(BGR,"Breed");
}
public void actionPerformed(ActionEvent AE){
if(AE.getSource() == Play){
CL.show(this, "Breed");
}
}
public void paintComponent(Graphics g){
g.drawImage(TitleBg,0,0,800,600,this);
g.drawImage(Title,250,80,280,140,this);
}
}
this was the card layout
import javax.swing.*;
import java.awt.*;
public class BreedingGround extends JPanel{
ImageData ID = new ImageData();
Image Swamp;
CardLayout CL;
public BreedingGround(){
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
ImageIcon SwampData = new ImageIcon(ID.SwampSource);
Swamp = SwampData.getImage();
}
public void paintComponent(Graphics g){
g.drawImage(Swamp,0,0,800,600,this);
}
}
and that was what i wanted the CardLayout to open. The problem is that when i try to run it the window wont run and this keeps showing in the compiler.
--------------------Configuration: 8-bit Chimera - JDK version 1.6.0_26 - --------------------
Exception in thread "main" java.lang.IllegalArgumentException: cannot add to layout: constraints must be a GridBagConstraint
at java.awt.GridBagLayout.addLayoutComponent(GridBagLayout.java:685)
at java.awt.Container.addImpl(Container.java:1074)
at java.awt.Container.add(Container.java:927)
at MainMenuComp.<init>(MainMenuComp.java:26)
at MainScreen.<init>(MainScreen.java:7)
at MainScreen.main(MainScreen.java:23)
Process completed.
All i really want to know is what this is saying.
I don't see where you ever set the layout of a container to be CardLayout, and if you don't set the layout to this, you can't magically use it. If you haven't yet gone through the CardLayout tutorial, consider doing so as it's all explained there.
Edit 1
Comment from Alexander Kim:
when i added the cardbagLayout it wont load the image and the button size filled the whole screen. I also took away the grids
You need to nest your JPanels in order to nest layouts. Use a single JPanel as the CardLayout container whose single function it is is to display other JPanels (the "cards"). These other JPanels will use whatever layouts that are necessary to properly display the components that they hold such as your JButton or "grids" (whatever they are). And even these JPanels may hold other JPanels that use other layouts.
Again, please read the layout tutorials as it's all described well there. You will not regret doing this.
Edit 2
Here's a very simple example that uses a CardLayout. The component displayed by the CardLayout using JPanel (called the cardContainer) is changed depending on which item is selected in a combobox.
Here's the CardLayout and the JPanel that uses it:
private CardLayout cardLayout = new CardLayout();
// *** JPanel to hold the "cards" and to use the CardLayout:
private JPanel cardContainer = new JPanel(cardLayout);
And here's how I add a component to the cardlayout-using JPanel:
JPanel redPanel = new JPanel();
//...
String red = "Red Panel";
cardContainer.add(redPanel, red); // add the JPanel to the container with the String
I also add the String to a JComboBox so I can use this combo box later to tell the CardLayout to display this JPanel (redPanel) if the user selects the item "Red" in this same JComboBox:
cardCombo.addItem(red); // also add the String to the JComboBox
Here's the ActionListener in the JComboBox that lets me change the item displayed in the cardlayout using JPanel:
cardCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String item = cardCombo.getSelectedItem().toString();
// *** if combo box changes it tells the CardLayout to
// *** swap views based on the item selected in the combo box:
cardLayout.show(cardContainer, item);
}
});
And here's the whole shebang:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleCardLayoutDemo {
private CardLayout cardLayout = new CardLayout();
// *** JPanel to hold the "cards" and to use the CardLayout:
private JPanel cardContainer = new JPanel(cardLayout);
private JComboBox cardCombo = new JComboBox();
private JPanel comboPanel = new JPanel();;
public SimpleCardLayoutDemo() {
JPanel greenPanel = new JPanel(new BorderLayout());
greenPanel.setBackground(Color.green);
greenPanel.add(new JScrollPane(new JTextArea(10, 25)), BorderLayout.CENTER);
greenPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
greenPanel.add(new JButton("Bottom Button"), BorderLayout.PAGE_END);
String green = "Green Panel";
cardContainer.add(greenPanel, green);
cardCombo.addItem(green);
JPanel redPanel = new JPanel();
redPanel.setBackground(Color.red);
redPanel.add(new JButton("Foo"));
redPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
String red = "Red Panel";
cardContainer.add(redPanel, red);
cardCombo.addItem(red);
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.blue);
JLabel label = new JLabel("Blue Panel", SwingConstants.CENTER);
label.setForeground(Color.white);
label.setFont(label.getFont().deriveFont(Font.BOLD, 32f));
bluePanel.add(label);
String blue = "Blue Panel";
cardContainer.add(bluePanel, blue);
cardCombo.addItem(blue);
comboPanel.add(cardCombo);
cardCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String item = cardCombo.getSelectedItem().toString();
// *** if combo box changes it tells the CardLayout to
// *** swap views based on the item selected in the combo box:
cardLayout.show(cardContainer, item);
}
});
}
public JPanel getCardContainerPanel() {
return cardContainer;
}
public Component getComboPanel() {
return comboPanel ;
}
private static void createAndShowUI() {
SimpleCardLayoutDemo simplecardDemo = new SimpleCardLayoutDemo();
JFrame frame = new JFrame("Simple CardLayout Demo");
frame.getContentPane().add(simplecardDemo.getCardContainerPanel(), BorderLayout.CENTER);
frame.getContentPane().add(simplecardDemo.getComboPanel(), BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// to run Swing in a thread-safe way
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Your problem is with add(BGR,"Breed");. The layout of MainMenuComp is a GridBagLayout, so the constraint must be a GridBagConstraint, not a String (you have "Breed" as the constraint).

Categories

Resources