JFrame build panel is not working - java

I have tried everything possible to fix this error. Every time I compile the program, the error
KiloConverter.java:25: error: cannot find symbol
How to resolve this error?
import javax.swing.*; // Needed for swing classes
public class KiloConverter extends JFrame
{
private JPanel panel;
private JLabel messageLabel;
private JTextField kiloTextField;
private JButton calcButton;
private final int WINDOW_WIDTH = 310;
private final int WINDOW_HEIGHT = 100;
//constructor
public KiloConverter()
{
setTitle("Kilometer Converter");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//bulid the panel and add it to the frame
buildPanel();
//Add the panel to the frame's content page
add(panel);
setVisible(true);
}
//the bulid panel method adds a label, a text field,
//and a button to a panel
private void bulidPanel()
{
//Create a label to display instructions.
messageLabel = new JLabel("Enter a distance " + "in kilometers");
//Create a text field 10 characters wide.
kiloTextField = new JTextField(10);
//create a button with the caption CALCULATE
calcButton = new JButton("Calculate");
//create a JPanel object and let the panel field reference it
panel = new JPanel();
//Add the label, text fieldm and button components to the panel
panel.add(messageLabel);
panel.add(kiloTextField);
panel.add(calcButton);
}
public static void main (String[] args)
{
new KiloConverter();
}
}

The source code seen, incorrectly spells 'build' as 'bulid' in two comments and one method name. Correcting the spelling in the method name should fix the problem, but change all three instances.

Related

Refer to an individual JTextField when they're in different tabs

I have three JTextFields, when the buy button is pressed the associated listener should retrieve the text from the text fields and use it to update the table.
The issue is that when I press the buy button it tries to use the data in the JTextFields in David's tab as opposed to the one I'm currently on. If I made another tab named "Jack" it would then try to be using jacks. The code to create the text boxes is as follows:
JLabel label2 = new JLabel("Name Of Share:");
tabPanel.add(label2);
textFieldName = new JTextField("", 15);
textFieldName.setColumns(10);
textFieldName.setToolTipText("Enter Number of shares here");
tabPanel.add(textFieldName);
The listener for the buy button:
int quantity = 0;
if (e.getActionCommand().equals("Buy")) {
String name = view.getTextFieldName().getText();
String ticker = view.getTextFieldTicker().getText().toUpperCase();
try{
quantity = Integer.parseInt(view.getTextFieldNumber().getText());
}catch(NumberFormatException er){
}
view.buy(ticker, name, quantity);
}
Everything works fine if I only have one tab but once I introduce more that's when the issues start.
Can anyone suggest a way to fix this so I can get data from the text boxes of only the tab I am on?
I should have mentioned view is of type MainGUI a Class I have created, which is used for building the GUI which has the fields:
public class MainGUI extends JFrame implements Observer {
private JTabbedPane tabbedPane;
private JTable table;
private JTextField textFieldTicker;
private JTextField textFieldName;
private JTextField textFieldNumber;
private DefaultTableModel model;
private PortfolioManager pm;
private JLabel tValue;
to create a Tab the code used is:
JPanel topPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel labelPanel = new JPanel();
JSplitPane splitPanelbtm = new JSplitPane(JSplitPane.VERTICAL_SPLIT, labelPanel, buttonPanel);
JSplitPane splitPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, splitPanelbtm){
private final int location = 500;
{setDividerLocation(location);}
#Override
public int getDividerLocation(){
return location;
}
#Override
public int getLastDividerLocation(){
return location;
}
};
splitPanel.setEnabled( false );
splitPanel.setDividerSize(0);
splitPanelbtm.setEnabled( false );
splitPanelbtm.setDividerSize(0);
splitPanelbtm.setBorder(null);
splitPanel.setBorder(null);
tabbedPane.add(tabName, splitPanel);
tabbedPane.setName(tabName);
this.add(tabbedPane);
this.setVisible(true);
createLabelsButtons(topPanel);
createTable(topPanel);
tValue = new JLabel("Total Value for " + tabbedPane.getName() + " is: $ ");
labelPanel.add(tValue);
createTabButtons(buttonPanel);

Clear a JPanel from a JFrame

I'm working on an assignment for class where we need to create a JComboBox and each option opens a new window where you can do whatever you want on those new windows. Please keep in mind I'm very new to GUI and new to Java in general, in case my questions are dumb.
I have a question and an issue...
My question:
When the user selects "The Matrix" option a new window pops up with a quote and two buttons. Right now I have two JPanels (panel and panel2) panel adds the quote to the NORTH position and then panel2 adds the two buttons to the CENTER position both using BorderLayout. My question is am I doing this correctly...Could I use just panel to add the quote and the buttons or is it necessary to create separate panels for separate items being added to the JFrame? When I had them both added to the same panel the quote was not on the window when I ran the program.
panel.add(matrixQuote);
newFrame.add(panel, BorderLayout.NORTH);
That's how I had it when it wasn't showing up ^^^
I GOT THE ISSUE WITH CLEARING THE JFRAME FIXED
I am trying to add an ActionListener to the bluePill button and instead of opening another new window I thought I could clear everything from the existing window when the button is pressed and then display something new on said window. The only info I could find on this is how I have it in the actionPerformed method below. I'll post a snippet of what I'm talking about directly below and then all my code below that just in case.
All my code...
public class MultiForm extends JFrame{
private JComboBox menu;
private JButton bluePill;
private JButton redPill;
private JLabel matrixQuote;
private int matrixSelection;
private JFrame newFrame;
private JPanel panel;
private JPanel panel2;
private static String[] fileName = {"", "The Matrix", "Another Option"};
public MultiForm() {
super("Multi Form Program");
setLayout(new FlowLayout());
menu = new JComboBox(fileName);
add(menu);
TheHandler handler = new TheHandler();
menu.addItemListener(handler);
}
public void matrixPanel() {
TheHandler handler = new TheHandler();
//Create a new window when "The Matrix" is clicked in the JCB
newFrame = new JFrame();
panel = new JPanel();
panel2 = new JPanel();
newFrame.setLayout(new FlowLayout());
newFrame.setSize(500, 300);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
matrixQuote = new JLabel("<html>After this, there is no turning back. "
+ "<br>You take the blue pill—the story ends, you wake up "
+ "<br>in your bed and believe whatever you want to believe."
+ "<br>You take the red pill—you stay in Wonderland, and I show"
+ "<br>you how deep the rabbit hole goes. Remember: all I'm "
+ "<br>offering is the truth. Nothing more.</html>");
panel2.add(matrixQuote);
newFrame.add(panel2, BorderLayout.NORTH);
//Blue pill button and picture.
Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
bluePill = new JButton("Blue Pill", bp);
panel2.add(bluePill);
bluePill.addActionListener(handler);
//Red pill button and picture
Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
redPill = new JButton("Red Pill", rp);
panel2.add(redPill);
newFrame.add(panel2, BorderLayout.CENTER);
newFrame.setVisible(true);
}
private class TheHandler implements ItemListener, ActionListener{
public void itemStateChanged(ItemEvent IE) {
//listen for an item to be selected.
if(IE.getStateChange() == ItemEvent.SELECTED) {
Object selection = menu.getSelectedItem();
if("The Matrix".equals(selection)) {
matrixPanel();
}
else if("Another Option".equals(selection)) {
}
}
}
public void actionPerformed(ActionEvent AE) {
if(AE.getSource() == bluePill) {
newFrame.remove(panel);
newFrame.remove(panel2);
newFrame.repaint();
}
}
}
//MAIN
public static void main(String[] args) {
MultiForm go = new MultiForm();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400, 200);
go.setVisible(true);
}
}
Use a Card Layout. You can swap panels as required.
The tutorial has a working example.
You can use:
jpanel.removeAll();
Either to delete a certain JComponent by using the JComponent itself like:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
frame.remove(panel);
panel.getGraphics().clearRect(0, 0, panel.getWidth(), panel.getHeight());

Java GUI BorderLayout application 4 buttons Left, right, up and down each move location

I have been breaking my head for days over a project I have to do in my Java beginner class about GUI BorderLayout Jbutton and I really hope some one here can help me out to understand it or shed some light. My task is to create a BorderLayout window with 4 button left right up and down
Each button moves the window/ Borderlayout 20 pixel left or right or up or down.
I have already created a code with the buttons but I do not to know how to make the buttons move and above all I must not allow the Window to move out/ disappear from the desktop. Please be patient with me I am totally fresh student.
Here is my code so far:
import java.awt.*;
import javax.swing.*;
public class WindowBorder extends JFrame {
private static final long serialVersionUID = 1L;
private int x, y; //the coordinates for moving in the screen
public WindowBorder (String titel){
super (titel);
//create the buttons and the layout and add the buttons
JButton right = new JButton ("Right");
JButton left = new JButton ("Left");
JButton up = new JButton ("Up");
JButton down = new JButton ("Down");
//JButton center = new JButton ("Default"); hide the middle button
setLayout (new BorderLayout (75,75));
add(BorderLayout.EAST,right);
add(BorderLayout.WEST,left);
add(BorderLayout.NORTH,up);
add(BorderLayout.SOUTH,down);
//add(BorderLayout.CENTER,default); hide the middle button
//I must create the inner class with the constructors for the task project for school
class WindowBorderInner implements ActionListener {
#Override
public void actionPerformed (ActionEvent e){
if(e.getActionCommand().equals("right"))
//this is the part that I am lost :(
}
}
//configuration the size and the location of the Border layout
setSize (400,400);
setLocationByPlatform (true);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String [] arg){ //the test method
new WindowBorder("Move Window");
}
}
I'm on my mobile so I can't(won't) type out much code, but I copied this out of another thread
jFrame.setLocation(jFrame.getX() + 5, jFrame.getY());
You can manually set the location of the JFrame in this way when the action listener is called.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screenSize.width); int y = (screenSize.height);
class ListenerInnerClass implements ActionListener {
#Override
public void actionPerformed (ActionEvent e){
if (e.getActionCommand ().equals("Right"))
Toolkit.getDefaultToolkit().getScreenSize();
setLocation (+20,y);
}
}
public MoveBorderDemo (String titel){
super (titel);
//create the buttons and the layout and add the buttons
JButton Right = new JButton ("Right");
JButton Left = new JButton ("Left");
JButton Up = new JButton ("Up");
JButton Down = new JButton ("Down");
Right.addActionListener(new ListenerInnerClass());
setLayout (new BorderLayout (75,75));
add(BorderLayout.EAST,Right);
add(BorderLayout.WEST,Left);
add(BorderLayout.NORTH,Up);
add(BorderLayout.SOUTH,Down);
//configuration the size and the location of the Border layout
setSize (400,400);
//Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(200,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String [] arg){ //the test method
new MoveBorderDemo ("Move Window");
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
System.out.println("Screen width = " + d.width);
System.out.println("Screen height = " + d.height);
}
}

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.

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