Cardlayout With Jbutton Not Switching - java

Hello I am fairly new to java programming and I am currently trying to work on a small game with a GUI, Right now I am stuck at an issue where I can only use a normal button with a card layout, unfortunately I want to use my own icon with the button and to do this I need to use a JButton. but for some reason when i use a JButton it does not get switched with the panels. I'm just wondering what I am doing wrong. I am programming as an applet with a IDE called Ready To Program.
{
CardLayout PanelLayout = new CardLayout ();
JPanel AppPanel = new JPanel (); //Main App Panel using cardlayout
JPanel StartPanel = new JPanel (); //Start Menu Panel
JPanel GamePanel = new JPanel (); //Running Game Panel
JButton StartBtn = new JButton ();
public void init ()
{
StartBtn.setIcon(new ImageIcon ("StartIcon.png"));
StartBtn.setBorder(BorderFactory.createEmptyBorder());
StartBtn.setContentAreaFilled(true);
StartPanel.add (StartBtn);
AppPanel.setLayout (PanelLayout);
AppPanel.add (StartPanel, "1");
AppPanel.add (GamePanel, "2");
PanelLayout.show (AppPanel, "1");
setLayout (new BorderLayout ());
add ("Center", AppPanel);
}
public boolean action (Event e, Object o)
{
if (e.target == StartBtn)
{
PanelLayout.show (AppPanel, "2");
}
return true;
}
}

Frist of all variable names should NOT start with an upper case character. I have never seen a tutorial or answer in any forum that uses an upper case character, so don't make up your own conventions. Learn by example.
I can only use a normal button with a card layout, unfortunately I want to use my own icon with the button and to do this I need to use a JButton.
A JButton is a normal button. What other kind of button are you referring to? It doesn't matter whether the button has text or Icon or both, it is still a button.
The button in your code doesn't work because you didn't add and ActionListener to the button.
Read the section from the Swing tutorial on How to Use Button for more information and examples. The tutorial also has a section on How to Write ActionListeners.
Your code has an action(...) method. I don't know if that is generated by the IDE or not, but basically the code in that method would be the code in your ActionListener.
add ("Center", AppPanel);
That is not the proper form of the method to add a component to a panel. First all don't use hardcoded literal strings, use the variables provided by the API:
add (appPanel, BorderLayout.CENTER);

Related

How Do I Make Sure Only One JRadioButton Is Selected In Java?

I have three JRadioButtons added to a JPanel. However, when I select one, I can select another one and the previous one selected stays selected. How can I make sure that only one is selected at a time?
My JPanel class, which is added by my main JFrame:
public class MainPanel extends JPanel {
private static JRadioButton addHouse, addRoad, calculateDist;
static {
addHouse = new JRadioButton("Add House");
addRoad = new JRadioButton("Add Road");
calculateDist = new JRadioButton("Calculate Distance");
}
MainPanel() {
setBackground(Color.WHITE);
addHouse.setBounds(50, 50, 100, 50);
addRoad.setBounds(50, 150, 100, 50);
addHouse.setBounds(50, 250, 100, 50);
addHouse.setBackground(Color.WHITE);
addRoad.setBackground(Color.WHITE);
calculateDist.setBackground(Color.WHITE);
add(addHouse);
add(addRoad);
add(calculateDist);
}
}
As you didn't share the complete code i can't tell how to do it in your case but in general
It can be done like that
ButtonGroup buttonGroup = new ButtonGroup() // create a button group , buttons in a button group knows how to behave together
JRadioButton radioButton1 = new JRadioButton("R1"); // create your buttons
JRadioButton radioButton2 = new JRadioButton("R2"); // as many you want
buttonGroup.add(radioButton1); // make them part of group
buttonGroup.add(radioButton2);
myJFrame.setLayout(new FlowLayout()); // or any layout you want
myJFrame.add(radioButton1); // add buttons to jframe
myJFrame.add(radioButton1);
when buttons were added to JFrame (or any other container) they were part of a group , so group handles the communications between them, now you can check only one at a time,
try commenting buttonGroup.add(); you will loose that behaveiour .
Same thing can be achieved manually , it that case you will track all other radio buttons
at every selection to check if others are already check and then uncheck them which is tedious so better use ButtonGroup class of swing
You can add the JRadioButtons in a ButtonGroup instance first. Here is a simple example:
// configure buttons bounds, background etc.
ButtonGroup buttonGroup= new ButtonGroup();
buttonGroup.add(addHouse);
buttonGroup.add(addRoad);
buttonGroup.add(calculateDist);
// add the buttons to the panel too.

How can i refresh a JDialog Image Correctly?

i am coding a program using SWing in java, but this is my problem, when i press a button, I want that every time I press a button, I update a new image in the same position as the previous one, I try to do it in the action listener of the code, but the image is not updated and the one that was At the beginning, can someone help me in this? Thank you very much.
public MainWindow() {
initComponents();
setIconImage(Icono);
this.setLocationRelativeTo(null);
this.setResizable(false);
Imagen fondo=new Imagen();
this.add(fondo, BorderLayout.CENTER);
this.pack();
PracticeMode = new javax.swing.JDialog();
}
private void StartPracticeActionPerformed(java.awt.event.ActionEvent evt) {
ButtonsSelected(1);
StartGame Practice=new StartGame(OpcComboBox, numUnity, numTrys,
opcNotas, false);
PracticeBF.dispose();
PracticeMode.setIconImage(Icono);
PracticeMode.setBounds(460, 600, 460, 538);
PracticeMode.setVisible(true);
CirculodeQuintasBW BW=new CirculodeQuintasBW();
PracticeMode.add(BW, BorderLayout.CENTER);
PracticeMode.pack();
PracticeMode.setLocationRelativeTo(null);
PracticeMode.setResizable(false);
}
This is the Image that i want to refresh, it supossed to be another Image before of that, but each time i tried to refresh it doesnt work...
PracticeMode it supossed to be a JDialog, anybody can help me?.
private void D2ActionPerformed(java.awt.event.ActionEvent evt) {
CirculodeQuintasD D=new CirculodeQuintasD();
PracticeMode.add(D, BorderLayout.CENTER);
PracticeMode.validate();
PracticeMode.repaint();
PracticeMode.pack();
}
First of all variable names and method names should NOT start with an upper case character. Learn by example from reading your text book or tutorial and then follow the Java conventions and don't make up your own!
when i press a button, I want that every time I press a button, I update a new image in the same position as the previous one,
Add an JLabel containing an ImageIcon to your panel.
When you want to change the image you just use:
label.setIcon( new ImageIcon(...) );
For example read the section from the Swing tutorial on How to Use Combo Boxes. It does exactly what your want. It uses an ActionListener to change the image of a label. The only different is that the ActionEvent is generated by clicking on an item in the combobox instead of clicking on a button.

populating JTabbed Pane with JScroll panes according to user selection

We have a project for university which is a program to hold handouts and feedback for courseworks done.
What we've thought of is breaking the whole thing down into smaller pieces, for example:
You have a coursework which requires to write a program and a report on results etc.
So the user will create a new coursework by selecting the "code" and "report" options, since that's what is required. And then we need to create the respective tabs in the program so the user can input what is needed.
I have created all necessary forms and windows, It's just I'm not sure how to move on forward.
a) where should I put my code? should I have it on the "create" event?
b) how do I do this whole custom population thing?
Obviously, I'm not asking for the entire thing in code. I'm not even sure what to read and what to search for.
Following are some screenshots of the ui to help explain what I mean.
New project window
How the main window should be after creating a new projet. Notice the various tabs.
A form for report feedback
On your "Create" button click check for the checkbox.isSelected() and use the method below as:
if(reportCheckbox.isSelected()){
addonScreen(new reportFrame(),"Report Submission");
addonScreen(new reportFeedbackFrame(),"Report Feedback");
}
Use a desktop pane as a container...add your tabbed pane to it
public static JTabbedPane tabbedPane = new JTabbedPane();
jDesktopPane1.add(tabbedPane);
Use this method to add tabs to the layout at runtime
public static void addOnScreen(JInternalFrame inFrame, String title) {
//border for the internal frame
javax.swing.plaf.InternalFrameUI ifu = inFrame.getUI();
((javax.swing.plaf.basic.BasicInternalFrameUI) ifu).setNorthPane(null);
Border b1 = new LineBorder(new Color(114, 139, 173), 3, true) {
};
tabbedPane.setBounds(0, 0, jDesktopPane1.getWidth(), jDesktopPane1.getHeight());
inFrame.setLocation(0, 0);
inFrame.setSize(jDesktopPane1.getWidth(), jDesktopPane1.getHeight());
inFrame.setBorder(b1);
JPanel jp = new JPanel();
jp.setLayout(new GridLayout());
jp.setOpaque(true);
jp.add(inFrame);
tabbedPane.addTab(title, jp);
tabbedPane.setSelectedComponent(jp);
inFrame.requestFocusInWindow();
inFrame.setVisible(true);
tabbedPane.setVisible(true);
}

Add panel to a panel

i'm building a Java program. The core of this program is visualized in a JFrame with a JMenuBar and various JMenuItem and JMenu. The point is that I added a centralPanel to all the frame,but if I add something to the centralPanel it shows only if i resize the main frame, reducing it or enlarging it!
Here's the code:
This is the constructor:
public UserFrame(Sistema system)
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize.width, screenSize.height);
storicoPanel = new JPanel();
carrelloPanel = new JPanel();
carrelloFrame = new JFrame();
pane = new JScrollPane(storicoArea);
close = new JButton("Chiudi");
this.sistema = system;
menu = new JMenuBar();
this.setJMenuBar(menu);
centralPanel = new JPanel();
add(centralPanel);
Here i added the centralPanel, and here, in an ActionListener, i try to add something to it, but it doesnt' work:
public ActionListener createVisualizzaStorico(final ArrayList<Acquisto> array)
{
class Visualize implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
storicoPanel.removeAll();
for(Acquisto a : array)
{
Articolo temp = a.getArticolo();
if(temp instanceof Vacanza)
storicoPanel.add(new VacanzaPanel((Vacanza)temp));
else if(temp instanceof BeneDiConsumo)
storicoPanel.add(new BeneDiConsumoPanel((BeneDiConsumo)temp));
else if(temp instanceof Cena)
storicoPanel.add(new CenaPanel((Cena)temp));
else
storicoPanel.add(new PrestazioniOperaPanel((PrestazioneOpera)temp));
}
centralPanel.add(storicoPanel);
centralPanel.repaint();
Could you please help me? Thanks!
Use a CardLayout instead of trying to add and remove component/panels. It's much cleaner and you don't have to worry about the things that may go wrong, like what you're facing here.
See this example to see how easy and cleaner it is. Also see How to Use CardLayout tutorial
Side Notes
A component can only have one parent container. Though I don't think this is causing a problem for you. It's good to know. First I see you trying to add storicoPanel to a JScrollPane, JScrollPane that you never add to the centerPanel. Then you later add the storicoPanel to the centerPanel. The JScrollPane will no longer be the parent after this.
I'm not sure what you're using this carrelloFrame = new JFrame(); for, but you're class is already a JFrame, why create another?
Just FYI, when adding components dynamically, you need to revalidate() and repaint(). Though, in your situation, I am totally against the adding and removing of components, because this looks like a perfect case for a CardLayout.
Try these..
centralPanel.updateUI(); // or
SwingUtilities.updateComponentTreeUI(getRootPane());
Execute your frame code in SwingUtilities.invokeLater()
Instead of repaint() call updateUI() or
SwingUtilities.updateComponentTreeUI(getRootPane()) to update the
user interface.

Add & remove JTextField at runtime in Java(Swings) program

how to add and remove components(JButons , JTextField etc) at runtime in a Swing program (Java ) , without using NetBeans ? which Layout should I use ?
I want the user to enter Username & Password and , when he clicks on Submit button , the new screen with new components(JButtons , JTextField etc) should appear , I am unable to achieve the transition at runtime.
You want to use two different panels to achieve this result. It's not a good idea to use the same panel and remove all of the first components and add all of the second ones.
Make a LoginPanel class which lays out the username and password fields, labels, and submit button. Then, when the submit button is pressed, after the login is authenticated, hide the login panel and display a new panel with the layout you want for the next screen.
This sort of approach makes it much easier to maintain the two panels, and clearly separates their layouts and functionality from each other.
You can center this new frame over the existing panel using this code:
public static void centerFrameOverComponent(JFrame frame, JComponent component) {
Window parent = SwingUtilities.getWindowAncestor(component);
Rectangle frameRect = frame.getBounds();
Rectangle parentRect = parent.getBounds();
int x = (int) (parentRect.getCenterX() - frameRect.getWidth() / 2);
int y = (int) (parentRect.getCenterY() - frameRect.getHeight() / 2);
frame.setLocation(x, y);
}
Another approach is to call setVisible(false) on the specific component when you wish to hide it.
In cases where I have wanted to add/remove an entire sub panel, I have used the following:
panel.remove(subPanel);
panel.revalidate();
panel.repaint();
You want to call the last two methods whenever you add/remove components.
One approach would be to use CardLayout. Your login button handler would check the credentials and use show() to reveal the second pane.
Addendum: For security, consider using JPasswordField for the password; for convenience, consdier setLocationRelativeTo() for positioning the frame.
you could create a new class for exsample MyFrame thath extends JFrame, that rapresetns your new windows, in the constructor of that class you have to add at the contentpanel your all contolr....
in this way you can add a jbutton to your JFrame.
class MyFrame extends JFrame{
private JButton jb= new JButton("hello");
public MyFrame(){
setSize(new Dimension(300,180)); //set the MyFrame size
getContentPane().add(jb); //add your Component at ContentPane
}
}
after the login you could show your new frame in this way:
new MyFrame().setVisible(true);

Categories

Resources