Can't call custom JPanel class methods in main frame class - java

tl;dr
I just started learning java and swing and I have this problem where inside the main class if I try to call any custom method defined in my custom class which extends JPanel, i get an error which says "cannot find symbol", it's as if that method isn't even declared.
I tripled checked the custom class object looks properly initiated and the method is set as public. Any idea why this happens?
At first I was using Intellij Idea but it's gui designer was so frustrating to use that i thought it was the IDE's fault but even after switching to NetBeans and rewriting code from scratch I get the same error.
I wanted to write a class called Drawing which extends JPanel that could draw my custom Circuit class objects. Basically what i wanted to do for the app is that selecting New from the File menu would create and draw that Circuit object. For that I wanted that pressing the New button would call setCircuit() method defined in the Drawing class which initializes the circuit and then the paintComponent() would draw the circuit.
Code below:
import circuit.*;
import java.awt.Graphics;
public class Drawing extends javax.swing.JPanel {
private Circuit circuit = null;
public Drawing(){
}
public void setCircuit(Circuit circuit) {
this.circuit = circuit;
}
#Override
public void paintComponent(Graphics graphics){
super.paintComponent(graphics);
if(circuit == null){
graphics.drawString("Create a new circuit.", 10, 20);
} else{
// draws the circuit
}
}
}
import circuit.*;
public class GUI extends javax.swing.JFrame {
private Circuit circuit = null;
public GUI() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
drawing = new Drawing();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
newMenuItem = new javax.swing.JMenuItem();
exitMentuItem = new javax.swing.JMenuItem();
exitMenu = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("My app");
setName("mainFrame"); // NOI18N
javax.swing.GroupLayout drawingLayout = new javax.swing.GroupLayout(drawing);
drawing.setLayout(drawingLayout);
drawingLayout.setHorizontalGroup(
drawingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
drawingLayout.setVerticalGroup(
drawingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
fileMenu.setText("File");
newMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
newMenuItem.setText("New");
newMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newMenuItemActionPerformed(evt);
}
});
fileMenu.add(newMenuItem);
exitMentuItem.setText("Exit");
exitMentuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMentuItemActionPerformed(evt);
}
});
fileMenu.add(exitMentuItem);
menuBar.add(fileMenu);
exitMenu.setText("Edit");
menuBar.add(exitMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawing, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawing, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void newMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
circuit = new Circuit();
drawing.setCircuit(circuit); // this is where I get the error:
/*
cannot find symbol
symbol: setCircuit(Circuit)
location: variable drawing of type JPanel
*/
}
private void exitMentuItemActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
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(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.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 GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel drawing;
private javax.swing.JMenuItem exitMentuItem;
private javax.swing.JMenu exitMenu;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem newMenuItem;
// End of variables declaration
}

Related

Check state and Uncheck state of JCheckBox MenuItem ActinListner

I have WordWrap checkBox MenuItem.By default it is unchecked(false) state.When I run the program and click on New menuitem and write some text after I click on WordWrap menuItem,The WordWrap state in not changed for first two times.I want to change the state(checked) for first time only.I had tried that but not working.
Here is code:
public class CheckBoxMenuItem extends javax.swing.JFrame {
int i=0;
JTextArea textArea;
JScrollPane scrollpane;
public CheckBoxMenuItem() {
initComponents();
WordWrap.setSelected(false);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Create = new javax.swing.JMenuItem();
WordWrap = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
Create.setText("Create");
Create.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CreateActionPerformed(evt);
}
});
jMenu1.add(Create);
WordWrap.setSelected(true);
WordWrap.setText("WordWrap");
WordWrap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WordWrapActionPerformed(evt);
}
});
jMenu1.add(WordWrap);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void CreateActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
internalFrame.setAutoscrolls(true);
textArea=new JTextArea();
textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
scrollpane=new JScrollPane(textArea);
internalFrame.add(scrollpane);
tabbedPane.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
}
private void WordWrapActionPerformed(java.awt.event.ActionEvent evt) {
WordWrap.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
AbstractButton button = (AbstractButton) ie.getItem();
if(button.isSelected()){
textArea.setLineWrap(true);
scrollpane.validate();
}
else
{
textArea.setLineWrap(false);
scrollpane.validate();
}
}
});
}
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(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new CheckBoxMenuItem().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Create;
private javax.swing.JCheckBoxMenuItem WordWrap;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration
}
In your WordWrapActionPerformed method, you're doing nothing but adding an ItemListener to do, this won't do much...
Instead, you should simply carry out the requirements of the event, for example...
private void WordWrapActionPerformed(java.awt.event.ActionEvent evt) {
AbstractButton button = (AbstractButton) evt.getSource();
if (button.isSelected()) {
textArea.setLineWrap(true);
} else {
textArea.setLineWrap(false);
}
textArea.revalidate();
}
Either that or change the listener on the menu item in the GUI properties to use a ItemListener instead of an ActionListener
You'll probably also want to become farmiluar with Code Conventions for the Java Programming Language, it will make your code eaiser to read for others ;)

How to change the Background color of JMenuBar and JToolBar?

I want to change the background color of JMenuBar and JToolBar. For that I had tried but not working. I had followed the solutions given by some websites. But, those are also not working correctly.
Here is my code:
import java.awt.Color;
public class JFrameDemo extends javax.swing.JFrame {
public JFrameDemo() {
Color b=new Color(0,150,255);
initComponents();
menuBar.setForeground(Color.GREEN);
toolbar.setBackground(b);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
toolbar = new javax.swing.JToolBar();
close = new javax.swing.JButton();
open = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
jMenu3 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
toolbar.setRollover(true);
close.setText("close");
close.setFocusable(false);
close.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
close.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
toolbar.add(close);
open.setText("open");
open.setFocusable(false);
open.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
open.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
toolbar.add(open);
menuBar.setBackground(new java.awt.Color(51, 51, 255));
jMenu3.setText("File");
menuBar.add(jMenu3);
jMenu4.setText("Edit");
menuBar.add(jMenu4);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(toolbar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(toolbar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 306, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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(JFrameDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrameDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrameDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrameDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
// ImageIcon img = new ImageIcon("C:\\Icons\book-edit-icon.png");
JFrameDemo fdemo=new JFrameDemo();
fdemo.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton close;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar menuBar;
private javax.swing.JButton open;
private javax.swing.JToolBar toolbar;
// End of variables declaration
}
Did you try to setOpaque(true) on your JMenuBar ?
You can also do this :
menuBar.setUI ( new BasicMenuBarUI (){
public void paint ( Graphics g, JComponent c ){
g.setColor ( YOUR_COLOR_HERE );
g.fillRect ( 0, 0, c.getWidth (), c.getHeight () );
}
} );
Or in general :
UIManager.put ( "MenuBarUI", YOUR_SPECIFIC_UI_HERE );
I assume you mean it dosen't set the color.
I don't know if is a glich in swing, but I have always been told to do it this way:
public class BackgroundMenuBar extends JMenuBar
{
Color bgColor=Color.WHITE;
public void setColor(Color color)
{
bgColor=color;
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(bgColor);
g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
}
}
Then you use the new Class instend of a JMenuBar, and set color with setColor.
Example take from: SO: Change background and text color of JMenubar and...

Closing JInternalFrame with JTabbedPane

I want to close the JInternalFrame.I am developing A MenuItem as Crete,whenever click on open it is opening an JInternalFrame,but it's not closing.
Please help me.
Here is my code
import javax.swing.JInternalFrame;
import javax.swing.JTextArea;
public class CloseWindow extends javax.swing.JFrame {
JTextArea tx;
int i=1;
public CloseWindow() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Crete = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
Crete.setText("Create");
Crete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CreteActionPerformed(evt);
}
});
jMenu1.add(Crete);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void CreteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JInternalFrame internalFrame = new JInternalFrame();
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
i++;
internalFrame.setSize(700, 700);
tx = new JTextArea();
internalFrame.add(tx);
tPane.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
}
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(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CloseWindow.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 CloseWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Crete;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tPane;
// End of variables declaration
}
Add the following:
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
tPane.remove(internalFrame);
}
});
But don't forget to make internalFrame variable to be final.

How to add a JInternalFrame to JFrame?

I have my JFrame, and I want to attach to a button an ActionListener that triggers the JInternalFrame.
I do:
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
AboutFrame about = new AboutFrame(); //jInternalFrame
this.add(about);
}
But it doesn't bring it to front. What did I miss?
You probable want to use a JDesktopPane, then set the content pane of your frame to the desktop pane
JDesktopPane desktop = new JDesktopPane(); //a specialized layered pane
createFrame(); //create first "window"
setContentPane(desktop);
Then you can do something like this
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt)
{
AboutFrame about = new AboutFrame(); <--- JInternalFrame
about.setVisible(true); //necessary as of 1.3 <--- set it visible
desktop.add(about); <--- add to desktop
try {
about.setSelected(true); <--- set it selected
} catch (java.beans.PropertyVetoException e) {}
}
See How to Us Internal Frames
UDATE
Run this example, I made on NetBeans GUI Builder also. It works fine, without the behavior yout're talking about.
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jDesktopPane1 = new javax.swing.JDesktopPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1);
jDesktopPane1.setLayout(jDesktopPane1Layout);
jDesktopPane1Layout.setHorizontalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 376, Short.MAX_VALUE)
);
jDesktopPane1Layout.setVerticalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 302, Short.MAX_VALUE)
);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("About");
jMenuItem1.setText("About");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem1);
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)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jDesktopPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
AboutFrame about = new AboutFrame();
about.setVisible(true);
jDesktopPane1.add(about);
try {
about.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String args[]) {
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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration
}
AboutFrame.java
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
public class AboutFrame extends JInternalFrame{
public AboutFrame() {
add(new Panel());
pack();
}
private class Panel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("About Screen", 100, 100);
}
public Dimension getPreferredSize(){
return new Dimension(300, 300);
}
}
}
Steps I took
Opened a new JFrame form
Dragged a JDesktopPane to the main frame and expanded it the size of the frame
Dragged a JMenuBar to the top of the frame
Dragged a JMenuItem to the JMenuBar
Added an event listener to the JMenuItem
Added the action code that i provided for you earlier. That's all I did, and it works fine.
EDIT
A different apprach would be instead of using an JInternalFrame for this. Use a modal JDialog. You can create it the same way you did the JInternalFrame , and show it the same way. This will guarantee you don't get this result. :)

Having trouble moving a jButton

I'm trying to use Matisse in NetBeans to create a simple game...like Myst. I just want it to display a Frame that has things like a text field and buttons/inventory on the right. I can do that. Then I created a Jpanel that displays on the Frame. I've input some pictures and created a set of cards to make visible and invisible when needed. Each card/scene needs to have buttons that will be different for each scene. Basically I want to make transparent buttons for the user to press that do things (i.e. move to next picture/scene, find a key, etc...). I can create different buttons in each picture, but I can't seem to move them anywhere. I have a suspicion it's due to Matisse, but I don't know.
Here is some of the code, I'm sure it's crude as it's my first implementation of anything in Java. At the very bottom in the Scene to display I've added a button, that displays. I pretty much know now that the setBounds won't work due to the way position works...how would I then place it somewhere. Right now it just displays at the top mid of the picture.
SceneFrame:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import scene.SecondPanel;
import scene.FirstPanel;
import scene.Scene;
import javax.swing.JButton;
public class SceneFrame extends javax.swing.JFrame {
private FirstPanel sceneP;
private SecondPanel sceneSP;
/**
* Creates new form SceneFrame
*/
public SceneFrame() {
initComponents();
addCards();
}
public void addCards() {
sceneP = new FirstPanel();
SceneManager.add("SecondPanel", sceneP);
sceneSP = new SecondPanel();
SceneManager.add("FirstPanel", sceneSP);
sceneP.setVisible(false);
}
/**
* 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() {
SceneManager = new scene.ScenePanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout SceneManagerLayout = new javax.swing.GroupLayout(SceneManager);
SceneManager.setLayout(SceneManagerLayout);
SceneManagerLayout.setHorizontalGroup(
SceneManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 517, Short.MAX_VALUE)
);
SceneManagerLayout.setVerticalGroup(
SceneManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 421, Short.MAX_VALUE)
);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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()
.addComponent(SceneManager, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(139, 139, 139)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(SceneManager, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 97, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
sceneP.setVisible(false);
//SceneManager.showScene("SecondPanel");
sceneSP.setVisible(true);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
sceneSP.setVisible(false);
//SceneManager.showScene("FirstPanel");
sceneP.setVisible(true);
}
/**
* #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(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SceneFrame.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 SceneFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel SceneManager;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
// End of variables declaration
}
Scene:
package scene;
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.Image;
import javax.swing.ImageIcon;
public abstract class Scene extends JPanel {
public Image image;
private String sceneName;
public Scene(String cn) {
setName(cn);
this.setSize(600, 600);
this.setBackground(Color.WHITE);
}
public String getCardName() {
return sceneName;
}
public abstract void addControlButtons();
// public abstract void implementControlButtons();
}
A Panel to display:
/**
* Creates a new ForestScene Object.
*/
public SecondPanel() {
super("SecondPanel");
JButton Button2 = new JButton("SwagCity");
try {
image = (new ImageIcon(getClass().getResource("/resources/ForestPath.jpg"))).getImage();
} catch (Exception e) {/*How to handle?*/
}
this.addControlButtons();
}
#Override
public void addControlButtons(){
JButton bButton = new JButton("bButton");
//bButton.setBounds(200, 300, 500, 600); //How to display where I want?
bButton.setAlignmentX(1000);
this.add(bButton);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Graphics2D g2 = (Graphics2D) g;
if (image != null) {
boolean val = g.drawImage(image, 0, 0, 800, 600, this);
} else {
System.out.println("Image not found");
}
}
}
You need to add JFrame.frame.setLayout(null) so that you can adjust your fields(button,textfields) on to the frame.I too had a similar problem
I've figured out that it must be the layoutManager confusing something. If i set: this.setLayout(null); I can then set the bounds of the button and it displays where and how I want. I apologize if the question did not have enough information, but I did not know myself anymore than I told you. If anyone has anything to add about what I did, I'll be glad to select that as my answer.

Categories

Resources