CardLayout Manager Questions/Confusion - java

I'm currently working on a program which I've asked questions involving previously.
I've made a good amount of progress since then, and now I'm ready to begin on the infoPanel portion of the client program. I've read through the documentation and other questions, but I'm a still a bit confused. How do I setup the panel to, y'know, work? How do I link it with the JList(If that's even possible to use a JList instead of a combo box), and then how do I establish which selection references which card?
Thank you so much for any assistance!
Source:
import javax.swing.*;
import java.util.*;
import java.awt.*;
public class ClientApp extends JFrame
{
public static void main(String[] args)
{
new ClientApp();
}
public ClientApp()
{
this.setSize(320,380);
this.setTitle("Honeydukes Candy Order");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
JPanel infoPanel = new JPanel(new CardLayout());
JPanel invntryPanel = new JPanel();
String[] candy = {"Acid Pops", "Bat's Blood Soup",
"Bertie Bott's Every Flavour Beans",
"Blood-flavoured Lollipops",
"Cauldron Cakes", "Charm Choc",
"Chocoballs", "Chocolate Cauldrons",
"Chocolate Frogs", "Chocolate Skeletons",
"Chocolate Wands", "Choco-Loco", "Cockroach Clusters",
"Nougat", "Crystallised Pineapple",
"Drooble's Best Blowing Gum", "Exploding Bonbons",
"Toffees", "Fizzing Whizzbees",
"Fudge Flies", "Ice Mice",
"Jelly Slugs", "Liquourice Wands",
"Pepper Imps", "Peppermint Toads",
"Pink Coconut Ice", "Pixie Puffs",
"Pumpkin Fizz", "Salt Water Taffy",
"Shock-o-Choc", "Skeletal Sweets",
"Splindle's Lick'O'Rish Spiders",
"Sugar Quills", "Sugared Butterfly Wings",
"Toothflossing Stringmints", "Tooth-Splintering Strongmints",
"Treacle Fudge", "Chocolates", "Wizochoc"};
JList candyList = new JList(candy);
candyList.setVisibleRowCount(18);
candyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane(candyList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
invntryPanel.add(scroll);
JPanel startCard = new JPanel();
JPanel acidPopsCard = new JPanel();
JPanel batsBloodSoupCard = new JPanel();
JPanel bertieBottsCard = new JPanel();
JPanel bloodPopsCard = new JPanel();
JPanel cauldronCakesCard = new JPanel();
JPanel charmChocCard = new JPanel();
JPanel chocoballsCard = new JPanel();
JPanel chocCauldronsCard = new JPanel();
JPanel chocFrogsCard = new JPanel();
JPanel chocSkeleCard = new JPanel();
JPanel chocWands = new JPanel();
JPanel chocolocoCard = new JPanel();
JPanel roachClustersCard = new JPanel();
JPanel nougatCard = new JPanel();
JPanel crystalPineappleCard = new JPanel();
JPanel droobleGumCard = new JPanel();
JPanel explodeBonbonsCard = new JPanel();
JPanel toffeesCard = new JPanel();
JPanel fizzWhizCard = new JPanel();
JPanel fudgeFliesCard = new JPanel();
JPanel iceMiceCard = new JPanel();
JPanel jellySlugsCard = new JPanel();
JPanel liquorWandsCard = new JPanel();
JPanel pepImpsCard = new JPanel();
JPanel pinkCocoIceCard = new JPanel();
JPanel pixiePuffsCard = new JPanel();
JPanel pumpkFizzCard = new JPanel();
JPanel saltTaffeyCard = new JPanel();
JPanel shockChocCard = new JPanel();
JPanel skeleSweetsCard = new JPanel();
JPanel spindleSpidersCard = new JPanel();
JPanel sugarQuillsCard = new JPanel();
JPanel sugarWingsCard = new JPanel();
JPanel flossMintsCard = new JPanel();
JPanel splintMintsCard = new JPanel();
JPanel treacleFudgeCard = new JPanel();
JPanel chocolatesCard = new JPanel();
JPanel wizochocCard = new JPanel();
infoPanel.add(startCard);
infoPanel.add(acidPopsCard);
infoPanel.add(batsBloodSoupCard);
infoPanel.add(bertieBottsCard);
infoPanel.add(bloodPopsCard);
infoPanel.add(cauldronCakesCard);
infoPanel.add(charmChocCard);
infoPanel.add(chocoballsCard);
infoPanel.add(chocCauldronsCard);
infoPanel.add(chocFrogsCard);
infoPanel.add(chocSkeleCard);
infoPanel.add(chocWands);
infoPanel.add(chocolocoCard);
infoPanel.add(roachClustersCard);
infoPanel.add(nougatCard);
infoPanel.add(crystalPineappleCard);
infoPanel.add(droobleGumCard);
infoPanel.add(explodeBonbonsCard);
infoPanel.add(toffeesCard);
infoPanel.add(fizzWhizCard);
infoPanel.add(fudgeFliesCard);
infoPanel.add(iceMiceCard);
infoPanel.add(jellySlugsCard);
infoPanel.add(liquorWandsCard);
infoPanel.add(pepImpsCard);
infoPanel.add(pinkCocoIceCard);
infoPanel.add(pixiePuffsCard);
infoPanel.add(pumpkFizzCard);
infoPanel.add(saltTaffeyCard);
infoPanel.add(shockChocCard);
infoPanel.add(skeleSweetsCard);
infoPanel.add(spindleSpidersCard);
infoPanel.add(sugarQuillsCard);
infoPanel.add(sugarWingsCard);
infoPanel.add(flossMintsCard);
infoPanel.add(splintMintsCard);
infoPanel.add(treacleFudgeCard);
infoPanel.add(chocolatesCard);
infoPanel.add(wizochocCard);
this.add(invntryPanel, BorderLayout.WEST);
this.add(infoPanel, BorderLayout.EAST);
this.setVisible(true);
}
}

I would add a ListSelectionListener to the JList, and inside of that listener change the card displayed by the CardLayout.
You really need to read the tutorial on how to use CardLayout first though as there you'd see that your add method is wrong. Consider using the Strings held by the JList as the constant that you'd use when adding components to the CardLayout-using panel.

Related

Java GUI Fill Empty spaces

I have the following Java GUI for my project. For some reason, the middle and right panels have been put below leaving empty spaces - marked in red. Is there a way to pull the panels up to fill the spaces.
These empty spaces does not look good. I have tried to check all code but cannot pinpoint where to correct.
Thanks in advance.
public static JPanel main= new JPanel(),
left= new JPanel(),middle= new JPanel(),right = new JPanel();
Container c = getContentPane();
c.setLayout(new FlowLayout()) ;
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.add(new JLabel("Enter word/SQL: "), "North");
pane.add(tf, "Center"); //enter keyword
JPanel second = new JPanel();
second.setLayout(new GridLayout(8, 1));
second.add(messageIDText);
//This is the start of adding panels
//create a left side panal and add the sub panels to it
JPanel left = new JPanel();
JPanel middle = new JPanel();
JPanel center = new JPanel();
JTextArea output = new JTextArea("", 60, 60);
JPanel sixth = new JPanel();
JPanel seventh = new JPanel();
JPanel eigth = new JPanel(new GridLayout(8,1));
JPanel labels7 = new JPanel(new GridLayout(5,1));
JPanel controls7 = new JPanel(new GridLayout(5,1));
JPanel tenth = new JPanel();
sixth.setLayout(new BorderLayout(5,5));
JPanel fourth = new JPanel();
fourth.add(firstButton);
sixth.add(labels, BorderLayout.WEST);
sixth.add(controls, BorderLayout.CENTER);
sixth.add(controlsButtons, BorderLayout.EAST);
labels.add(new JLabel("Proposal:"));
controls.add(proposalNumberText);
controlsButtons.add(freeQueryButton);
//add border
pane.setBorder(BorderFactory.createCompoundBorder(new
EmptyBorder(10,10,10,10), BorderFactory.createEtchedBorder()));
fourth.setBorder(BorderFactory.createCompoundBorder(new
EmptyBorder(10,10,10,10), BorderFactory.createEtchedBorder()));
//-------LEFT SIDE -- PARAMETERS
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
JLabel headerLabel,blank;
headerLabel = new JLabel("Navigate Records", JLabel.LEFT);
Font f = headerLabel.getFont();
headerLabel.setFont(f.deriveFont(f.getStyle() ^ Font.BOLD)); // bold
left.add(headerLabel, BorderLayout.PAGE_END);
left.add(fourth, BorderLayout.PAGE_END);
main.add(left);
//---------MIDDLE PART - Messages - tabbed pane
JTabbedPane jtp = new JTabbedPane();
getContentPane().add(jtp);
//jtp.setSize(jtp.getPreferredSize());
JPanel jpA = new JPanel(),jpB = new JPanel(),
jpC = new JPanel(),jpD = new JPanel();
JScrollPane scrollPane2 = new JScrollPane(),jp = new
JScrollPane(activeTSText), jp2 = new JScrollPane(analyseWordsText),
jp3 = new JScrollPane(markedMessageText);
JLabel labelA = new JLabel();
labelA.setText("");
jpA.add(labelA);
jpA.add(jp);
jtp.addTab("Message", jpA);
middle.add(jtp);
main.add(middle);
//----------RIGHT PART - .. //paramters and results
JPanel jj = new JPanel();
jj.setLayout(new BoxLayout(jj, BoxLayout.PAGE_AXIS));
stateJTable.setRowHeight(20); //add JTable
JScrollPane js3 =new JScrollPane(stateJTable);
js3.setVisible(true);
//JTabbedPane jtp2 = new JTabbedPane();
//JPanel StateSubstatesTabOnLeft = new JPanel(),
StateSubstates_PostProcessedTabOnLeft = new JPanel();
JPanel firstleftTabinRightSideOfFrame = new JPanel(),
secondLeftTabinRightSideOfFrame = new
JPanel(),rightTabInRightSideOfFrame = new JPanel();
jj.add(js3);
//downbelow, the state jtable is added to the panel here through the
//scrollpane which contains the jtable
right.add(jj) ; //stateJTable);// add table in panel using add() method
main.add(right);
proposalNumberText.requestFocusInWindow();
I have solved the problem by using Borderlayout and assigning the main panel to it.
The assigning the WEST, CENTER and EAST regions to it.
I have added the code below in the code above at places where the main panel is being added to.
Thank you for the advice to start debugging by using MRE approach.
BorderLayout layout = new BorderLayout();
main.setLayout(layout);
main.add(left,BorderLayout.WEST);
main.add(middle,BorderLayout.CENTER);
main.add(right,BorderLayout.EAST);

How to make method return a panel?

I am making a Java application with tabbed pane, I want some panes to have the same panel layout and structure, I don't want to clutter my code by writing the same code over and over again, so I created a method that returns a JPanel with a structure I want the pane to have.
I am initialising new variables and taking them to the method . My problem is that after I create a panel I can not do anything else in it because it doesn't show up. I can not add labels etc, etc (although if I add the label in the method it does show).
My question is it possible to somehow change the code I've written to make it possible to change it after the panel is returned?
JPanel panel2 = panel2(); // this code bit is in the constructor
JPanel mainPanel = new JPanel(); //Variables needed to create a panel
JPanel LeftPanel = new JPanel();
JPanel RightPanel = new JPanel();
JSplitPane splitPaneH = new JSplitPane();
JPanel panelTop = new JPanel();
JPanel panelBottom = new JPanel();
private JPanel panel2() {
JPanel newPanel = new JPanel();
CreateAPanel(newPanel, LeftPanel,RightPanel,splitPaneH, panelTop,panelBottom);
JLabel label = new JLabel ("lalala");
LeftPanel.add(label,BorderLayout.CENTER);
return newPanel;
}
private JPanel CreateAPanel(JPanel mainPanel, JPanel LeftPanel,JPanel RightPanel, JSplitPane splitPaneH, JPanel panelTop, JPanel panelBottom){
mainPanel.setPreferredSize(new Dimension(1100, 630));
mainPanel.setLayout(new BorderLayout());
LeftPanel = new JPanel();
RightPanel = new JPanel();
splitPaneH = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
panelTop = new JPanel();
panelBottom = new JPanel();
splitPaneH.setTopComponent(panelTop);
splitPaneH.setBottomComponent(panelBottom);
splitPaneH.setDividerLocation(300);
splitPaneH.setPreferredSize(new Dimension(800,630));
mainPanel.add(LeftPanel, BorderLayout.WEST);
mainPanel.add(RightPanel,BorderLayout.EAST);
LeftPanel.setBackground(Color.RED);
LeftPanel.setPreferredSize(new Dimension (300,630));
RightPanel.add(splitPaneH);
return mainPanel;
}
you do not use your return value...
your method CreateAPanel(...) creates the desired panel but you just don't use it
you should adjust your method panel2() in like this:
private JPanel panel2()
{
//JPanel newPanel = new JPanel(); don't create a new panel!
//CreateAPanel(newPanel, LeftPanel,RightPanel,splitPaneH, panelTop,panelBottom);
//instead do this:
JPanel newPanel = CreateAPanel(newPanel, LeftPanel,RightPanel,splitPaneH, panelTop,panelBottom);
JLabel label = new JLabel ("lalala");
LeftPanel.add(label,BorderLayout.CENTER);
return newPanel;
}
It's totally possible to add components to the Panel object afterwards. The only mistake that you have made is that "inside the method body you create new JPanel instances to replace with original param references" so when the method returns there is no effect on the original objects. I suggest doing something different as this:
private JPanel[] CreateAPanel(JPanel mainPanel)
{
mainPanel.setPreferredSize(new Dimension(1100, 630));
mainPanel.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JSplitPane splitPaneH = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
JPanel panelTop = new JPanel();
JPanel panelBottom = new JPanel();
splitPaneH.setTopComponent(panelTop);
splitPaneH.setBottomComponent(panelBottom);
splitPaneH.setDividerLocation(300);
splitPaneH.setPreferredSize(new Dimension(800,630));
mainPanel.add(leftPanel, BorderLayout.WEST);
mainPanel.add(rightPanel,BorderLayout.EAST);
leftPanel.setBackground(Color.RED);
leftPanel.setPreferredSize(new Dimension (300,630));
rightPanel.add(splitPaneH);
return new JPanel[]{mainPanel, leftPanel, rightPanel, panelTop, panelBottom};
}
If you want to change or add some more components inside result JPanel you get you can set names to all your components when you create them:
JPanel newPanel = new JPanel();
newPanel .setName("leftPanel");
resultPanel.add(newPanel, BorderLayout.WEST);
Then when you get resultPanel you can get it's components:
Component[] componentList = resultPanel.getContentPane().getComponents();
JPanel leftPanel = null;
for (Component component: componentList) {
if (Objects.equals(component.getName(), "leftPanel")) {
leftPanel = (JPanel) component;
}
}
if (leftPanel != null) {
// do something
}

Add Jpanel to a Jscrollbar

I'm trying to add a Jpanel to a JscrollBAr but when i run java it's not working. It's a RadioButton with a question. Can you help me please ?
this is my class jpanel :
public class yesnoPanel extends JPanel {
private JPanel quest;
private JPanel answ;
public yesnoPanel(String q){
JPanel pan = new JPanel();
JRadioButton yes = new JRadioButton("yes");
JRadioButton no = new JRadioButton("no");
ButtonGroup bg = new ButtonGroup();
JTextArea question = new JTextArea(1,20);
question.setText(q);
JPanel pan2 = new JPanel();
pan2.add(question);
bg.add(yes);
bg.add(no);
pan.add(yes);
pan.add(no);
this.quest=pan2;
this.answ=pan;
}
I can show them when i use JFrame but not with Jscrollbar
This is my main with the jscrollbar :
public static void main(String[] args) {
JFrame fram = new JFrame();
yesnoPanel question = new yesnoPanel("are you ok");
JPanel q = question.getQuestion();
JPanel a = question.getAnsw();
JPanel all = new JPanel();
all.add(q);
all.add(a);
yesnoPanel question2 = new yesnoPanel("sure ?");
JPanel q2 = question2.getQuestion();
q2.setSize(200,500);
JPanel a2 = question2.getAnsw();
JPanel all2 = new JPanel();
all2.add(q2,BorderLayout.WEST);
all2.add(a2);
JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(100,100));
scroll.setViewportView(all);
scroll.setVisible(true);
}
thanks to all
Replace your last few lines in main method with this to make it work.
JPanel master = new JPanel();
master.add(all);
master.add(all2);
JScrollPane scroll = new JScrollPane(master);
scroll.setPreferredSize(new Dimension(100,100));
scroll.setViewportView(all);
scroll.setVisible(true);
fram.add(scroll);
fram.pack();
fram.setVisible(true);
fram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

BoxLayout Left Alignment

I'm trying to left align the class and neutral buttons so they are in line with the left most card button. For some reason, setAlignmentX only shifts the buttons half way. Here is the code. Is there away to align the buttons?
private String[] listEntries = {"a","a","a","a","a"};
private JButton remove = new JButton("Remove");
private JList list;
private JButton b1 = new JButton("Class");
private JButton b2 = new JButton("Neutral");
private JPanel page = new JPanel(new CardLayout());
private DefaultListModel listModel = new DefaultListModel();
public Main () {
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel,BoxLayout.PAGE_AXIS));
leftPanel.setLayout(new BoxLayout(leftPanel,BoxLayout.PAGE_AXIS));
rightPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
leftPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel title = new JLabel("Deck Constructor", SwingConstants.CENTER);
title.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
//Set up Deck List
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(-1);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(150, 80));
JLabel listTitle = new JLabel("List");
listTitle.setLabelFor(list);
listScroller.setAlignmentX(LEFT_ALIGNMENT);
rightPanel.add(listTitle);
rightPanel.add(listScroller);
rightPanel.add(remove);
//Set up Card Selection
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
b1.setActionCommand("Class");
b2.setActionCommand("Neutral");
b1.addActionListener(this);
b2.addActionListener(this);
buttonPanel.add(b1);
buttonPanel.add(b2);
JPanel classCards = new JPanel(new GridLayout(2,3, 10, 10));
JButton card1 = new JButton("Card 1");
card1.addActionListener(this);
card1.setActionCommand("addCard");
JButton card2 = new JButton("Card 2");
JButton card3 = new JButton("Card 3");
JButton card4 = new JButton("Card 4");
JButton card5 = new JButton("Card 5");
JButton card6 = new JButton("Card 6");
classCards.add(card1);
classCards.add(card2);
classCards.add(card3);
classCards.add(card4);
classCards.add(card5);
classCards.add(card6);
JPanel neutral = new JPanel();
neutral.setBackground(Color.BLUE);
page.add(classCards, "Class");
page.add(neutral, "Neutral");
leftPanel.add(buttonPanel);
leftPanel.add(page);
setPreferredSize(new Dimension(640,640/12*9));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(leftPanel,BorderLayout.CENTER);
getContentPane().add(rightPanel,BorderLayout.EAST);
getContentPane().add(title,BorderLayout.NORTH);
pack();
setVisible(true);
}
It is not perfect solution, but you can use for example:
If you want to keep buttons default size:
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING,1,2));
and delete:
buttonPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
If you want to fill buttonPanel with buttons:
JPanel buttonPanel = new JPanel(new GridLayout(1,2,2,2));
buttonPanel.setBorder(new EmptyBorder(2,1,2,1));
In (FlowLayout.LEADING,1,2) and in EmptyBorder(2,1,2,1))the 1,2 values are added to match buttonPanel and classCard hgap and vgap.

Not all components showing

When I run this program, the window blocks out the buttons in panel2 when I use setSize to determine window size.
In addition, if I use frame.pack() instead of setSize(), all components are on one horizontal line but I'm trying to get them so that panel1 components are on one line and panel2 components are on a line below them.
Could someone explain in detail the answers to both of these problems?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Exercise16_4 extends JFrame{
// FlowLayout components of top portion of calculator
private JLabel jlbNum1 = new JLabel("Number 1");
private JTextField jtfNum1 = new JTextField(4);
private JLabel jlNum2 = new JLabel("Number 2");
private JTextField jtfNum2 = new JTextField(4);
private JLabel jlbResult = new JLabel("Result");
private JTextField jtfResult = new JTextField(8);
// FlowLayout Components of bottom portion of calculator
private JButton jbtAdd = new JButton("Add");
private JButton jbtSubtract = new JButton("Subtract");
private JButton jbtMultiply = new JButton("Multiply");
private JButton jbtDivide = new JButton("Divide");
public Exercise16_4(){
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
panel1.add(jlbNum1);
panel1.add(jtfNum1);
panel1.add(jlNum2);
panel1.add(jtfNum2);
panel1.add(jlbResult);
panel1.add(jtfResult);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 10));
panel1.add(jbtAdd);
panel1.add(jbtSubtract);
panel1.add(jbtMultiply);
panel1.add(jbtDivide);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
}
public static void main(String[] args){
Exercise16_4 frame = new Exercise16_4();
frame.setTitle("Caculator");
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setResizable(false);
frame.setVisible(true);
}
}
You're problem is likely a typographical error in that you're adding all components to panel1 and none to panel2:
// you create panel2 just fine
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 10));
// but you don't use it! Change below to panel2.
panel1.add(jbtAdd);
panel1.add(jbtSubtract);
panel1.add(jbtMultiply);
panel1.add(jbtDivide);
Add the buttons to panel2, and then call pack() before setVisible(true). Do not set the size of the GUI.

Categories