Using CardLayout in Java - java

I'm currently trying to make a game with a menu.
Menu looks like this.
http://puu.sh/xGoC
Ideally, when I push a button, it will bring me to the game.
The game looks like this.
http://puu.sh/xGoV
I currently initialize a JFrame() in my main class which runs either the menu class or the game class (Both of which are JPanels).
How would I go about using CardLayout to make it so that I can initialize the game menu and when I click a button, change the panel to the game panel?

I've got some sample code for you, it's not perfect, but it should work. Basically, you want to use the NEXT or PREVIOUS calls on the layout manager.
As there's only two panels, I just use the NEXT call to cycle through them. It's probably the best if you read the Swing documentation though, this works, but you might have other requirements as well.
import java.awt.CardLayout;
public class CardLayoutUsage extends javax.swing.JFrame {
public CardLayoutUsage() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
containerPanel = new javax.swing.JPanel();
menuPanel = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
gamePanel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
containerPanel.setLayout(new java.awt.CardLayout());
menuPanel.setBackground(new java.awt.Color(153, 255, 255));
jButton2.setText("Go to Game");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout menuPanelLayout = new javax.swing.GroupLayout(menuPanel);
menuPanel.setLayout(menuPanelLayout);
menuPanelLayout.setHorizontalGroup(
menuPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, menuPanelLayout.createSequentialGroup()
.addContainerGap(135, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(149, 149, 149))
);
menuPanelLayout.setVerticalGroup(
menuPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, menuPanelLayout.createSequentialGroup()
.addContainerGap(141, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(134, 134, 134))
);
containerPanel.add(menuPanel, "card2");
gamePanel.setBackground(new java.awt.Color(255, 255, 204));
jButton1.setText("Go to Menu");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout gamePanelLayout = new javax.swing.GroupLayout(gamePanel);
gamePanel.setLayout(gamePanelLayout);
gamePanelLayout.setHorizontalGroup(
gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, gamePanelLayout.createSequentialGroup()
.addContainerGap(138, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(147, 147, 147))
);
gamePanelLayout.setVerticalGroup(
gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, gamePanelLayout.createSequentialGroup()
.addContainerGap(152, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(123, 123, 123))
);
containerPanel.add(gamePanel, "card3");
getContentPane().add(containerPanel, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout)(containerPanel.getLayout());
cl.next(containerPanel);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout cl = (CardLayout)(containerPanel.getLayout());
cl.next(containerPanel);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CardLayoutUsage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CardLayoutUsage().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel containerPanel;
private javax.swing.JPanel gamePanel;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel menuPanel;
// End of variables declaration
}

Don't use CardLayout for that.
Instead, remove the menu panel from the frame's content pane and add the game panel.
Remember to validate() the frame as well. Something like this:
public static final int VIEW_MENU = 0;
public static final int VIEW_GAME = 1;
private static Container content;
...
content = frame.getContentPane();
public static void setView(int view){
if(view == VIEW_MENU){
content.remove(menuPanel);
content.add(gamePanel);
} else {
content.remove(gamePanel);
content.add(menuPanel);
}
frame.validate();
}
In the program that I'm currently working on I have a class called ViewManager that creates static instances of each view and adds them to an array with indices that correspond to the constant fields. I also have fields to keep track of previous views for breadcrumbs / going back. It might be a case of re-inventing the wheel, but it allows you to control everything about it. And it's efficient.

Related

How to use autogenerated netbeans JFrame forms?

I want to develop a mini game and I struggle creating a Menu for this app. The Menu consists of 3 buttons (exit, rules, play) and I want to let the netbeans JFrame form designer to take care of it (you know, I just place the buttons, assign them functionality and style and the IDE creates the class code for me).
Now, the problem is that I do not know how to implement this code. It says that "This method is called from within the constructor to initialize the form.", so I guessed that I just had to do:
public Menu() {
create_and_show_menu();
}
private void create_and_show_menu() {
JFrame f = new JFrame("Menu");
new Sterge();
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
... but it didn't work out. Please tell me how to use that freakin' JFrame form, cause I haven't found anything online about that.
The auto-generated class code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author stoic
*/
public class Sterge extends javax.swing.JFrame {
/**
* Creates new form Sterge
*/
public Sterge() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton1MousePressed(evt);
}
});
jButton2.setText("jButton1");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton2MousePressed(evt);
}
});
jButton3.setText("jButton1");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton3MousePressed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(138, 138, 138)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap(189, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jButton1)
.addGap(42, 42, 42)
.addComponent(jButton2)
.addGap(46, 46, 46)
.addComponent(jButton3)
.addContainerGap(73, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jButton2MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jButton3MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Sterge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Sterge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Sterge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Sterge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Sterge().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
// End of variables declaration
}
The initcomponents() method initializes all of the Java swing components objects that your Front-End GUI uses, using the NetBeans GUI Builder. I see you are already using NetBeans GUI Builder and the IDE generated the code while you are designing,
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton1MousePressed(evt);
}
});
jButton2.setText("jButton1");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton2MousePressed(evt);
}
});
jButton3.setText("jButton1");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton3MousePressed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(138, 138, 138)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap(189, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jButton1)
.addGap(42, 42, 42)
.addComponent(jButton2)
.addGap(46, 46, 46)
.addComponent(jButton3)
.addContainerGap(73, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
So that is how the NetBeans IDE helping you to develop applications without typing more codes but with designing. Pretty easy huh :)
These swing components are automatically generated inside the above method whenever you make changes to the design of your GUI using the GUI builder.
You should not change any aspect of the above code within this method as this method is inextricably linked to the Front-End NetBeans GUI builder. If you change the code your Front-End also will be changed. But if you wish to change the code that is up to you to take care of it.
The initComponents(); method is called inside the constructor by default by NetBeans. And it is by default private. Running this initComponents(); method inside the Constructor will display the Front-End as soon as the application starts.
public Sterge() {
initComponents();
}
But you can call the initComponents(); method wherever you like (constructor or inside other methods). For Java, it is just like any other method.
When I come to your menu question, I don't see any JMenuBar and JMenuItems are used. If you need them you can read about how to use Menus from here. But I see there are 3 JButtons as you said there are three buttons in Menu. So I assume these are the 3 buttons that you are saying about.
Look at the following codes in your class.
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jButton2MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jButton3MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
Suppose you need to print Hello World! in the console after you click the jButton1. Here is the place where you write the code. Inside the following method.
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
System.out.println("Hello World!");
}
Once you click the above button MouseEvent will be triggered and you will see the Hello World! text on the console. According to your details, there are 3 buttons for 3 functions (exit, rules, play). Writing the code is up to you. :)
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
// Code for exit the game writes here
}
private void jButton2MousePressed(java.awt.event.MouseEvent evt) {
// Code for show rules writes here
}
private void jButton3MousePressed(java.awt.event.MouseEvent evt) {
// Code for play the game writes here
}
If you look more carefully at the NetBeans-generated code, you will see that inside initComponents(); method there is this code,
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton3MousePressed(evt);
}
});
NetBeans use this structure to prevent edits on the standard code that could lead to incorrect event handling, allowing you at the same time to write the code you need to be executed when that event happens.
As you have used MouseListener I suggest don't use a MouseListener. A JButton is designed to be used with an ActionListener.
public void jButton3ActionPerformed(ActionEvent e) {
// Your code here
}
The generated code ActionListener by the NetBeans GUI Builder will be,
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
So I will stop writing from here as I can't cover all the points within this. The following links provide a very good quick start guide to the essentials of NetBeans GUI builder.
Introduction to GUI Building
Designing a Swing GUI in NetBeans
Hope this helps you. Happy Coding!

Change JFrame(without layout) to JPanel

I have to change my program's GUI implemented in Swing. Now I have many charts in seperate windows and I want to change it so they all display in only one. The constraction of the orginal version was that
JFrame had a JPanel field. JFrame had no set layout.
private void initComponents() {// GEN-BEGIN:initComponents
getContentPane().setLayout(null);
setTitle("Wykres");
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
resizedWindow(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width - MIN_WIDTH) / 2, (screenSize.height - MIN_HEIGHT) / 2, MIN_WIDTH, MIN_HEIGHT);
}
JPanel was declared as follows:
BorderLayout borderLayout = new BorderLayout();
borderLayout.setHgap(0);
borderLayout.setVgap(0);
drawPanel = new JDrawPanel();
drawPanel.setLayout(borderLayout);
drawPanel.setComponentOrientation(ComponentOrientation.UNKNOWN);
setContentPane(drawPanel);
If I remove inheritance by JFrame and add inheritance by JPanel, the method paintComponent is not called. I think the reason is bad layout settings. However program calculates the distances from the edges, and I don't want to change it. How can I easily edit this program?
I also generated new GUI in NETBEANS
public class ViewPanel extends javax.swing.JFrame {
public ViewPanel() {
// initComponents();
}
public ViewPanel(JPanel histo, JPanel dystrybu, JPanel time){
initComponents(histo, dystrybu, time);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents(JPanel histo, JPanel dystrybu, JPanel time) {
MainTabs = new javax.swing.JTabbedPane();
jHistoTab = histo;
jDystybuTab = dystrybu;
jTimeTab = time;
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("zaleznosc czasowa");
MainTabs.setToolTipText("");
MainTabs.addTab("histogram", jHistoTab);
MainTabs.addTab("dystrybuanta", jDystybuTab);
MainTabs.addTab("zalenosc czasowa", jTimeTab);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(MainTabs, javax.swing.GroupLayout.DEFAULT_SIZE, 712, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(MainTabs, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
.addContainerGap())
);
MainTabs.getAccessibleContext().setAccessibleName("");
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ViewPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ViewPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ViewPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ViewPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ViewPanel().setVisible(true);
AppSMO.main(null);
}
});
}
public void setHistoTab(JPanel panel){
jHistoTab=panel;
}
// Variables declaration - do not modify
private javax.swing.JTabbedPane MainTabs;
private JPanel jDystybuTab;
private JPanel jHistoTab;
private JPanel jTimeTab;
// End of variables declaration
}
Set a BorderLayout to the contentpane. Add your panel to the contentPane.
That will give it center constraint so it will adapt to the size of the window.
In the panel you are then free to add any components you need. I recommend that you don't use null layout anywhere.
Avoid absolute positioning.

How to create a JMenuBar with Glossy Colors?

I created a small Swing based application. For that I created a menu bar using JMenuBar class. But I want to apply glossy color for that menu bar.
In particular, I'm look at the effects seen here: a gradient color in the fifth example and an animation in the seventh.
My Code:
public class MenuBar extends javax.swing.JFrame {
/**
* Creates new form MenuBar
*/
public MenuBar() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MenuBar().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration
}
While your question is very broad, several points are worth mentioning:
As suggested here, support for CSS in Swing is limited; JavaFX may be an alternative.
In Swing, the appearance of a JMenuItem is controlled by its UI delegate, typically derived from BasicButtonUI; an example of applying a gradient is seen here.
Alternatively, add instances of JButton to a JToolBar, illustrated here; use the rollover property to change the button's icon as desired.
Create animated icons using a Swing Timer, as shown here.

How to Customize the JMenuBar with HTML code [duplicate]

I created a small Swing based application. For that I created a menu bar using JMenuBar class. But I want to apply glossy color for that menu bar.
In particular, I'm look at the effects seen here: a gradient color in the fifth example and an animation in the seventh.
My Code:
public class MenuBar extends javax.swing.JFrame {
/**
* Creates new form MenuBar
*/
public MenuBar() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MenuBar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MenuBar().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration
}
While your question is very broad, several points are worth mentioning:
As suggested here, support for CSS in Swing is limited; JavaFX may be an alternative.
In Swing, the appearance of a JMenuItem is controlled by its UI delegate, typically derived from BasicButtonUI; an example of applying a gradient is seen here.
Alternatively, add instances of JButton to a JToolBar, illustrated here; use the rollover property to change the button's icon as desired.
Create animated icons using a Swing Timer, as shown here.

How to update an image in a Java GUI

I have a GUI with several buttons and I'm using NetBeans GUI Builder to do.
At the click of one of these I would like for it to open another frame containing a picture.
So I associate a listener (actionPerformed) the button and when clicked it opens actually post the new frame.
In the new frame I waxed a JLabel and then I associate the image of the label. I saw that to do that NetBeans generates this code:
label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/tree.png")));
My problem is that the picture is overwritten several times during the execution of the program is not changed yet in the frame.
That is, in the new frame is always displayed an old version of the image.
How can I do so that the image is always up to date?
Thank you very much
The Code:
package View;
import Controller.Util;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class AlberoIpotesi extends javax.swing.JFrame {
/** Creates new form AlberoIpotesi */
public AlberoIpotesi() {
initComponents();
remove(label);
revalidate();
repaint();
Decifra.sessioneDec.toString(".../src/img/tree");
revalidate();
repaint();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
scroll = new javax.swing.JScrollPane();
label = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Albero delle ipotesi");
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("Albero delle ipotesi");
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/tree.png"))); // NOI18N
label.setVerticalAlignment(javax.swing.SwingConstants.TOP);
scroll.setViewportView(label);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addContainerGap(29, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(25, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void start() {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AlberoIpotesi().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
public static javax.swing.JLabel label;
public static javax.swing.JScrollPane scroll;
// End of variables declaration
}
I'd seperate the creation of the icon and the setIcon on the JLabel, like so:
ImageIcon icon = new ImageIcon("path/to/picture.png");
label.setIcon(icon);
That way you can change the icon's image later and update the label
icon = new ImageIcon("path/to/new_picture.png"); // Changes the icon
label.setIcon(icon); // Updates the label's icon
So basically what I understand is that you have a button which creates a new instance object of the frame you wish to display right? Then you have an image stored in a particular location of your project where you will recall the object to display the updated image as you say?
I am unaware of how you choose to launch your frame. But what I can suggest is that you make use of a parametrized constructor to change your image each time(if required) the frame is called.
https://www.dropbox.com/s/mpqvy9hgsvsgq9t/PeanutsAndPretzels.zip
I am not sure of the terms and conditions of stackoverflow and external project files. But I compiled something which may or may not help you. Give it a bash to get an idea perhaps.

Categories