Adding 2 JPanels, different classes
Hi,
I have 3 different classes in 3 files:
public class Trainer {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.getContentPane().add(t);
f.pack();
}...plus...
public class Test extends JPanel {
public int testing(int n) {
return 0;
}...and...
public class Game extends Test implements MouseListener, MouseMotionListener {
Game() {
setPreferredSize(new Dimension(800, 600));
addMouseListener(this);
addMouseMotionListener(this);
(...)I would like to add 2 JPanels side by side to the class "Game". I am not allowed to modify "Test" and "Trainer". Class "Trainer" incorporates the main-method.
How could I do this?
Thanks for your help!
Thanks for your replies, they were really helpful :)
My last question to this topic: I would like to set a background-color for my 2 JPanels - however, the color isn't applied:
Game() {
setPreferredSize(new Dimension(800, 600));
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
JPanel actionPanel = new JPanel() { public void paint(Graphics g) {
actionPanel_paint(g);
actionPanel.addMouseListener(this);
actionPanel.addMouseMotionListener(this);
actionPanel.setBackground(new java.awt.Color(153, 204, 255));
JPanel statusPanel = new JPanel() { public void paint(Graphics g) {
statusPanel_paint(g);
statusPanel.setBackground(new java.awt.Color(204, 255, 204));
add(actionPanel);
add(statusPanel);
public void actionPanel_paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Ellipse2D.Double testCircle_action = new Ellipse2D.Double(100, 100, 20, 20);
g2.setColor(Color.RED);
g2.draw(testCircle_action);
g2.fill(testCircle_action);
public void statusPanel_paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Ellipse2D.Double testCircle_status = new Ellipse2D.Double(100, 100, 20, 20);
g2.setColor(Color.BLACK);
g2.draw(testCircle_status);
g2.fill(testCircle_status);
}
Similar Messages
-
Updating JPanel with buttons from a different class
I have a JPanel in a class that has a gridlayout with buttons in it for a game board. And my problem is that when I want to update a button using setIcon() the button doesn't change in the GUI because the buttons are in a different class. The JPanel is in a Client class and the buttons are in a GamePlugin class. I've tried a bunch of different things but none of them worked or it was way too slow. I'm sure theres an easy way to do it that I'm not seeing. Any suggestions? Heres part of my code for updating the GUI.
private JPanel boardPanel = new JPanel();
Container cP = getContentPane();
cP.add(boardPanel, BorderLayout.WEST);
boardPanel.setPreferredSize(new Dimension(400, 400));
boardPanel.setLayout(new GridLayout(8, 8));
cP.add(optionsPanel, BorderLayout.CENTER);
* Gets the board panel from the selected plugin.
public void drawGameBoard(GamePlugin plugin) {
board = (OthelloPlugin)plugin;
boardPanel = board.getBoardPanel();
for (int i = 0; i < GamePlugin.BOARD_SIZE; i++)
for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
board.boardButtons[i][j].setActionCommand("" + i + "" + j);
board.boardButtons[i][j].addActionListener(this);
* This method takes a GameBoard and uses it to update this class' data
* and GUI representation of the board.
public void updateBoard(GamePlugin updatedBoard) {
board = (OthelloPlugin)updatedBoard;
for (int i = 0; i < GamePlugin.BOARD_SIZE; i++) {
for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
int cell = board.getCell(i,j);
if (cell == OthelloPlugin.PLAYER1){
board.boardButtons[i][j].setIcon(black);
else if (cell == OthelloPlugin.PLAYER2)
board.boardButtons[i][j].setIcon(white);
else
board.boardButtons[i][j].setText("");
}txp200:
I agree that a call to validate() , possibly repaint(), should fix your problem. In the class with the panel that the buttons are on, i would create a static repaint method that call panel.repaint(). You can then call that method in your other class. Just make sure u only use methods to change the properties of the button, never make a make a new one, as then you will lose the association with the panel. Hope this helps.
-- Brady E -
Java interfaces and containers in different classes
Hi in trying to create an interface in Java that will be the basis for other classes to populate areas on in in certain panels.
So for example I have a default size for a screen and some default buttons that should appear on it. These are all setup in a class called ScriptyUI. Within ScriptyUI I want to set up several rows where each row will be populated with the container of a different class. So for instance another class called NetworkAreaUI will create all the buttons and boxes needed for the NetworkUI class along with the actionListeners for each of the buttons. I therefore want to add this into one of the rows of the ScriptyUI class.
Each time I try and call the networkAreaUI class from within the ScriptyUI class I get an error stating that a container is expected and not a window.
Any Ideas?
I have placed everything within the ScriptyUI class and it works, however this class soon becomes so large it is quite unmanageble.
What I am also trying is something similar to these code snippets:
I want to add this.............:
public class NetworkAreaUI extends JFrame implements Runnable, ActionListener
private JPanel networkPanel;
private JTextField netPath;
private JButton remove;
private JButton add;
private JLabel netDrives;
private JComboBox driveList;
private int driveCount = 0;
private Thread adds;
private Thread lists;
private Thread removes;
protected NetworkDrive myNetworkDrive;
public NetworkAreaUI()
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
networkPanel = new JPanel();
networkPanel.setLayout(new GridLayout(3,4));
netDrives = new JLabel("Type Network Drive Location");
networkPanel.add(netDrives);
remove = new JButton("Remove");
networkPanel.add(remove);
netPath = new JTextField("\\\\Server\\Share\\Name",20);
networkPanel.add(netPath);
add = new JButton("add");
networkPanel.add(add);
driveList = new JComboBox();
networkPanel.add(driveList);
networkPanel.setVisible(false);
cp.add(networkPanel);
//Adds action listeners
//Adds MenuSelection to the menu's
remove.addActionListener(this);
add.addActionListener(this);
driveList.addActionListener(this);(then there is code for the action listeners )........into this.....
public class ScriptyUI extends JFrame// implements ActionListener, Runnable
private final int FRAME_WIDTH = 600;
private final int FRAME_HEIGHT = 540;
private JPanel rows;
private JPanel row1;
private JPanel row2;
private JPanel row3;
private JPanel row4;
private JPanel button;
private JPanel outputArea;
private JTextArea message;
private JPanel selection;
private JButton vbs;
private JButton bat;
/* private JPanel networkPanel;
private JTextField netPath;
private JButton remove;
private JButton add;
private JLabel netDrives;
private JComboBox driveList;
private int driveCount = 0;
private JMenuBar menu;
private JMenu fileMenu;
private JMenu helpMenu;
private JMenuItem restartMenu;
private JMenuItem quitMenu;
private JMenuItem show;
protected NetworkDrive myNetworkDrive;
protected NetworkAreaUI myNetGui;
private JButton back;
private JButton next;
private JTextArea output;
private JScrollPane jsp;
private JButton save;
private JFileChooser fc;
private String fileType;
// private Thread thread;
/* private Thread adds;
private Thread lists;
private Thread removes;
private Thread nextOne;
private Thread saveIt;*/
// private Thread;
public ScriptyUI(String title)
super(title);
myNetworkDrive = new NetworkDrive();
myNetworkDrive.reset();
// myNetGui = new NetworkAreaUI();
setUpGui();
public void setUpGui()
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
//Setup Menu Bar
menu = new JMenuBar();
setJMenuBar(menu);
fileMenu = new JMenu("File");
helpMenu = new JMenu("Help");
restartMenu = new JMenuItem("Start Over");
quitMenu = new JMenuItem("Quit game");
show = new JMenuItem("Show Drives");
//Construct Menu Bar
menu.add(fileMenu);
menu.add(helpMenu);
fileMenu.add(restartMenu);
fileMenu.add(quitMenu);
fileMenu.add(show);
rows = new JPanel();
rows.setLayout(new GridLayout(6,1));
//Create Message area and populate with Text.
row1 = new JPanel();
message = new JTextArea("Select which format you " +
"would like the Script to be in. Visual Basic" +
"Script or Batch Script", 3, 30);
row1.add(message);
rows.add(row1);
//setup the selection screen
row2 = new JPanel();
selection = new JPanel();
selection.setLayout(new BorderLayout());
//sets the buttons on the selection screen
vbs = new JButton("Visual Basic Scripts");
selection.add(vbs, BorderLayout.NORTH);
bat = new JButton("Batch Scripts");
selection.add(bat, BorderLayout.SOUTH);
row2.add(selection, BorderLayout.CENTER);
rows.add(row2);
row3 = new JPanel();
myNetGui = new NetworkAreaUI();
row3.add(myNetGui);
rows.add(row3);
cp.add(rows, BorderLayout.CENTER);Any help or guidance will be greatly appreciated,Encephalopathic wrote:
good
Thanks :)
Are you sure that you want to use a Container and not a JPanel or JComponent? This is Swing after all.Hi i set up the method as below which seemed to work:
public Container setup()
networkPanel = new JPanel();
networkPanel.setLayout(new GridLayout(5,2));
netDrives = new JLabel("Type Network Drive Location:");
networkPanel.add(netDrives);
typeName = new JLabel("Type Drive Letter:");
networkPanel.add(typeName);
netPath = new JTextField("\\\\Server\\Share\\Name",20);
networkPanel.add(netPath);
nameDrive = new JTextField("X",1);
networkPanel.add(nameDrive);
add = new JButton("add");
networkPanel.add(add);
remove = new JButton("Remove");
networkPanel.add(remove);
driveList = new JComboBox();
networkPanel.add(driveList);
driveNames = new JComboBox();
networkPanel.add(driveNames);
//Adds action listeners
//Adds MenuSelection to the menu's
remove.addActionListener(this);
add.addActionListener(this);
driveList.addActionListener(this);
//return the content panel
return networkPanel;
}it is set up in the header to return container
public Container setup()
.but i actually return networkPanel which is setup as a JPanel.
So have now changed it to read:
public JPanel setup()
.I think that should be a little better? is it?
Thanks for the heads up.
Ian -
How do I access a gui component in a different class?
I have a jpanel (mainwindow) in a japplet. mainwindow loads and displays a jpanel form (content1). How do I code a button on conent1 so that mainwindow loads and displays a different jpanel form(content2)? mainwindow, content1, and content2 are all in different classes/packages. Thanks in advance!
Let your JPanel content1 forward its ActionEvents to its parent. For instance, you could define your content1 as follows:
public class Content1 extends JPanel
private ArrayList<ActionListener> actionListeners;
private JButton myButton;
public Content1()
actionListeners = new ArrayList<ActionListener>();
myButton = new JButton("Test");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
forwardAction(e);
public void addActionListener(ActionListener listener) {
actionListeners.add(listener);
protected void forwardAction(ActionEvent e) {
for (ActionListener l: actionListeners) {
l.actionPerformed(e);
}Then you could let your mainWindow listen to content1:
// in your main windows' code:
Content1 content1 = new Content1();
content1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
swapPane(e); // create a method swapPane in your mainwindow that handles the switch to content2.
}); -
Two equal objects, but different classes?
When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
The source codes of the program bind_ref.java are listed as below:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
import java.lang.*;
import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
public class bind_ref {
public static void main( String[] args ) {
// Set up environment for creating the initial context
Hashtable env = new Hashtable();
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
env.put( Context.PROVIDER_URL, "file:/daniel/" );
Context ctx = null;
File f = null;
Fruit fruit1 = null, fruit2 = null;
byte [] b = new byte[10];
try {
ctx = new InitialContext( env );
Hashtable the_env = ctx.getEnvironment();
Object [] keys = the_env.keySet().toArray();
int key_sz = keys.length;
fruit1 = new Fruit( "Orange" );
SubReference ref1 = fruit1.getReference();
ctx.rebind( "reference", fruit1 );
fruit2 = ( Fruit )ctx.lookup( "reference" );
System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
} catch( Exception ne ) {
System.err.println( "Exception: " + ne.toString() );
System.exit( -1 );
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
All the outputs are shown as below:
=======================================================
Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
--------- (i)subref.hashCode() = (-1759114666)
SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
--------- (i)subref.hashCode() = (-1759114666)
FruitFactory: obj's class = (class javax.naming.Reference)
FruitFactory: obj's hashCode = -1759114666
FruitFactory: obj = (Reference Class Name: Fruit
Type: fruit
Content: Orange
FruitFactory: ( obj instanceof SubReference ) = false
FruitFactory: subref_class_name = (Fruit)
Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
ref1's class = (class SubReference)
fruit2.myRef's class = (class javax.naming.Reference)
( ref1 instanceof SubReference ) = true
( fruit2.myRef instanceof SubReference ) = false
ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
ref1.equals( fruit2.myRef ) = true
========================================================
I hightlight the critical codes and outputs related to the strangeness with bold texts.
Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?It can also depend on how you implement the equals method.
class Cat {
String name;
Cat(String n) {
name = n;
class Dog {
String name;
Dog(String n) {
name = n;
public boolean equals(Object o) {
return name.equals(o.name);
public static void main(String[] args) {
Dog d = new Dog("Fred");
Cat c = new Cat("Fred");
System.out.println(d.equals(c));
} -
Can't call or execute of different class files in a main program
Hi, I got a main program which can call 3 different classes. The main program have an implicit-choice List as a starting menu. If one of the file is selected, the files will call out and display it. However, i managed to call the 1st 2 files, and the 3rd files can't display anything after selected.
I enclosed my code as below:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Catalogues extends Form implements CommandListener {
private Displayable parent;
private Display display;
private List Cata;
private Boots bo;
private Higheels hHeels;
private Sandals sand;
private Slippers sp;
private Command backCommand = new Command("Back", Command.BACK, 1);
private Command viewCommand = new Command("View", Command.SCREEN, 1);
private String[] options = {"Boots", "High Heels","Sandals", "Slippers"};
public Catalogues(Display d, Displayable p) {
super("Welcome to Footwear World");
Cata = new List("Select Option", List.IMPLICIT, options, null);
display = d;
parent = p;
addCommand(backCommand);
addCommand(viewCommand);
setCommandListener(this);
public void commandAction(Command c, Displayable d) {
if(d==parent && c==List.SELECT_COMMAND){
switch(parent.getSelectedIndex()){
case 0:
if(bo==null){
bo = new Boots(display,parent);
display.setCurrent(bo);
break;
case 1:
if(hHeels==null){
hHeels = new Higheels(display,parent);
display.setCurrent(hHeels);
break;
case 2:
if(sand==null){
sand = new Sandals(display,parent);
display.setCurrent(sand);
break;
case 3:
if(sp==null){
sp = new Slippers(display,parent);
display.setCurrent(sp);
break;
default:
else if (c==backCommand) {
display.setCurrent(parent);
}If the 3rd option is selected, i'll display above mentioned layout which contain a list to select too.
After build this project on WToolkit. It shown an error message which is as below:
Project settings saved
Building "SelectCustest"
C:\WTK22\apps\SelectCustest\src\Catalogues.java:29: cannot resolve symbol
symbol : method getSelectedIndex ()
location: class javax.microedition.lcdui.Displayable
switch(parent.getSelectedIndex()){
^
1 error
com.sun.kvem.ktools.ExecutionException
Build failed
May i know what is problem am i facing now? And how to solve it.
Thanks.Thanks to all for your thoughts and replies. I liked the xargs suggestion, so I tried that first. I would have (may still) try the stdin suggestion, followed by writing the grep output to a file.
xargs does work, in a way I didn't expect it to, but that could be due to my inexperience with the workings of the shell.
here's a line from my test script
cat file | grep foo | xargs java com.company.test.TEchoArghere's the contents of 'file'
123foo
abc
qafoozv
qaz
wsx
qwefoort
zxcfooh
sdfghhere's the output from the test class, which just echos any arguments
::number of args: 4
::args[0] 123foo
::args[1] qafoozv
::args[2] qwefoort
::args[3] zxcfoohso xargs appends all the values from grep into an argument list and call the java class once.
when I took xargs out of the script, nothing was passed to the class:
::number of args: 0this was really interesting and something to keep in my back pocket for future use.
Thanks again to all.
Tom -
How to use the different class for each screen as well as function.
Hi Experts,
How to use the different class for each screen as well as function.
With BestRegards,
M.Thippa Reddy.Hi ThippaReddy,
see this sample code
Public Class ClsMenInBlack
#Region "Declarations"
'Class objects
'UI and Di objects
Dim objForm As SAPbouiCOM.Form
'Variables
Dim strQuery As String
#End Region
#Region "Methods"
Private Function GeRate() As Double
Return Double
End Function
#End Region
Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
If pVal.BeforeAction = True Then
If pVal.MenuUID = "ENV_Menu_MIB" Then
End If
Else ' Before Action False
End If
End Sub
#End Region
End Class
End Class
Rgds
Micheal
Vasu Anna Regional Feeling a???? Just Kidding
Edited by: micheal willis on Jul 27, 2009 5:49 PM
Edited by: micheal willis on Jul 27, 2009 5:50 PM -
Problem in importing two different classes with same name...
I have to import two different classes in my program with the same name....
import org.apache.lucene.document.Document;
import org.w3c.dom.Document;
// I AM USING THE DOCUMENT FROM W3C PACKAGE HERE....
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource( new StringReader( tempString ) );
d = builder.parse( is );
NodeList images = d.getElementsByTagName("img");
int length = images.getLength();
for(int i = 0;i<length;i++)
Node image = images.item(i);
String tempAltText = image.getAttributes().getNamedItem("alt").getNodeValue();
altText = altText.concat(" ").concat(tempAltText);
}and the error i am getting is
[javac] C:\Documents and Settings\sumit-i\WolframWorkspaces\Base\WolframNutch\src\java\com\wolfram\nutch\indexer\InfoCenterFilter.java:20: org.apache.lucene.document.Document is already defined in a single-type import
[javac] import org.w3c.dom.Document;
[javac] ^
[javac] C:\Documents and Settings\sumit-i\WolframWorkspaces\Base\WolframNutch\src\java\com\wolfram\nutch\indexer\InfoCenterFilter.java:132: incompatible types
[javac] found : org.w3c.dom.Document
[javac] required: org.apache.lucene.document.Document
[javac] d = builder.parse( is );
[javac] ^
[javac] C:\Documents and Settings\sumit-i\WolframWorkspaces\Base\WolframNutch\src\java\com\wolfram\nutch\indexer\InfoCenterFilter.java:133: cannot find symbol
[javac] symbol : method getElementsByTagName(java.lang.String)
[javac] location: class org.apache.lucene.document.Document
[javac] NodeList images = d.getElementsByTagName("img");
[javac] ^
[javac] Note: Some input files use unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
[javac] 3 errorsany idea ..how to resolve it
Edited by: ping.sumit on Jul 16, 2008 3:39 PM
Edited by: ping.sumit on Jul 16, 2008 3:40 PMnow i changed the code to
import org.apache.lucene.document.Document;
import org.w3c.dom.Document;
org.w3c.dom.Document d = null;
try{
System.out.println("in author");
URL url = new java.net.URL(urlString);
java.net.URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((in.readLine()) != null)
//tempString = tempString.concat(in.readLine());
String temp = in.readLine();
tempString = tempString + " " + temp;
System.out.println("the string in author" + tempString);
in.close();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource( new StringReader( tempString ) );
d = builder.parse( is );
NodeList images = d.getElementsByTagName("img");and their is only one error i am getting ...and that is
[javac] C:\Documents and Settings\sumit-i\WolframWorkspaces\Base\WolframNutch\src\java\com\wolfram\nutch\indexer\InfoCenterFilter.java:20: org.apache.lucene.document.Document is already defined in a single-type import
[javac] import org.w3c.dom.Document;
[javac] ^
[javac] Note: Some input files use unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
[javac] 1 error -
Cycle Counting is not fetching All Items in Different Classes
Hi All,
My client has performed cycle counting. Ideally system has to fetech all the items in different classes. But in cycle counting listing report only able to fetch few items.
Please let me know are we missing something ?
And please let me know the significance of "Assign Items". How to put the same.
Regards,
John
Edited by: 911765 on Mar 14, 2012 4:36 AM1) CC won't fetch all items in all classes.
It will look at only those items that are present in the assign items screen.
It will only consider those items which have cycle count enabled flag set to Yes in item master
It will only consider those items that have a non-zero frequency for the ABC class of the item.
It will only print those items that have some onhand if you run the CC to ignore zero onhand items.
2) You can either manually add items to a CC in the assign items window.
OR
You can reinitialize or update the CC (by going to the 3rd tab on CC screen)
Make sure that you have run ABC compilation so each item has a ABC class. You should also specify the frequency for each ABC class.
Sandeep Gandhi -
Invoke a method in one class from a different class
I am working on a much larger project, but to keep this simple, I wrote out a little test that would convey the over all theory of the program.
What I am doing is starting out with a 2 JFrames and a Class. When the program is launched, the first JFrame opens. In this JFrame is a label and a button. When the button is clicked, the second JFrame opens. This JFrame has a textField and a button. The user puts the text in the textField and presses the button. When the button is pushed, I want the text that was just put in the textField, to be displayed in the first JFrame's label. I am trying to invoke a method in the first JFrame from the second, but nothing happens. I have also tried making the Class extend from JFrame1 and invoke it from there, but no luck. So, how do I invoke a method in a class from a different class?
JFrame1 (I omitted the layout part. I made this in Netbeans so its pretty long)
public class NewJFrame1 extends javax.swing.JFrame {
private NewClass1 nC = new NewClass1();
/** Creates new form NewJFrame1 */
public NewJFrame1() {
initComponents();
jLabel1.setText("Chuck");
public void setLabels()
jLabel1.setText(nC.getName());
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
NewJFrame2 j2 = new NewJFrame2();
j2.setVisible(true);The class
public class NewClass1 {
public static String name;
public NewClass1()
public NewClass1(String n)
name = n;
public String getName()
return name;
public void setName(String n)
name = n;
}The second jFrame
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
NewClass1 nC = new NewClass1();
NewJFrame1 nF = new NewJFrame1();
nC.setName(jTextField1.getText());
nF.setLabels();
System.out.println(nC.getName());At this point I am begging for help. I have been trying for days to figure this out, and I just feel like I am not getting anywhere.
ThanksSo, how do I invoke a method in a class from a different class?Demo:
public class Main {
public static void main(String [] args) {
Test1 t1 = new Test1();
Test2 t2 = new Test2();
int i = t1.method1();
String s = t2.method2(i);
System.out.println(s);
class Test1 {
public int method1() {
return 10;
class Test2 {
public String method2(int i) {
if (i == 10)
return "ten";
else
return "nothing";
}Output is "ten".
Edited by: newark on May 28, 2008 10:55 AM -
hi, i'm beginner in j2me...
I was wondering how to call to other form(class) in the current form...
For example,
public class A extends MIDlet implements CommandListener
public void commandAction(Command d,Displayable s)
if (d==*OKCommand*)
if press this OK command, it will be able to show another form declared in the different class...
How to make it able to call to other form/class(eg.classB)????
public class B
//form that will be shown after pressed command OK in class A
please help if you know...Thanks a lot..... =)you MUST have a reference to the other class or MIDlet in the current MIDlet ...
i think that i have answered to these kind of questions a few month ago.. you should use the 'search' engine to find the topic..
CLDC and MIDP forum is not a huge forum compare to Java Programming forum so it will be easy ! -
How to access form objects from different class?
Hello, I am new to java and i started with netbeans 6 beta,
when i create java form application from template i get 2 classes one ends with APP and one with VIEW,
i put for example jTextField1 with the form designer to the form and i can manipulate it's contents easily from within it's class (let's say it is MyAppView).
Question>
How can i access jTextField1 value from different class that i created in the same project?
please help. and sorry for such newbie question.
Thanks Mikehmm now it says
non static variable jTree1 can not be referenced from static context
My code in ClasWithFormObjects is
public static void setTreeModel (DefaultMutableTreeNode treemodel){
jTree1.setModel(new DefaultTreeModel(treemodel));
and in Class2 it is
ClasWithFormObjects.setTreeModel(model); -
Accessing a different class using ActionPerformed
hi
im trying to access a method in a different class using
public void actionPerformed (ActionEvent e) {
if(e.getSource() == AuthorCombo) {
ComboAction();
else if(e.getSource() == SearchButton){
SearchSystem();
}and then using
public class Book extends ViewPanel{
public void SearchSystem(){// this is used to get the information from
//the combo boxs whixh can latter show
//the data in the text area
tempBookNoList.clear();
for(int a=0; a<AuthorList.size(); a++) {
if(((String)AuthorCombo.getSelectedItem()
==AuthorList.get(a))
&&((String)BookCombo.getSelectedItem()
==BookList.get(a))) {
tempBookNoList.add((String)BookNoList.get(a));
String result = (String)tempBookNoList.get(a);
InfoArea.setText ((String)tempBookNoList.get(a));
} }//End neither random situation.to manipulate some data within the other class
i keep getting the error
.\ViewPanel.java:314: cannot resolve symbol
symbol : method SearchSystem ()
location: class ViewPanel
SearchSystem();
^
1 error
can anyone help me spot the problemin that case i do not know what could be the cause in this program
the only area i think it could be is when the SearchSystem method in the Book class gets using the Action Performed method in the Viewpanel method, shown below
public class Book extends ViewPanel{
public void SearchSystem(){// this is used to get the information from
//the combo boxs whixh can latter show
//the data in the text area
for(int a=0; a<AuthorList.size(); a++) {
if(((String)AuthorCombo.getSelectedItem()
==AuthorList.get(a))
&&((String)BookCombo.getSelectedItem()
==BookList.get(a))) {
InfoArea.setText((String)BookNoList.get(a));
}which is called using
public void actionPerformed (ActionEvent e) {
if(e.getSource() == AuthorCombo) {
ComboAction();
else if(e.getSource() == SearchButton){
theBook.SearchSystem();
}but i cant see this being a problem as it all compiles -
Updating Swing components from a different class
I would like to use the JTextArea component in a JFrame to display fast updating text from my application. My application is very simple. When the app launches the GUI is created then my application engine would start processing and displaying text data into the GUI. After reading about Thread safety when using Swing components I concluded it would not be a good idea for my app engine class to update the JTextArea class directly using methods such as .append(String).
I would be grateful for any suggestions on how I should approach updating Swing components from different classes.
Many Thanks in advance SeanHi
Why don't you just implement a basic callback method?
To do this the right way you should probably define a simple Interface that has a public method like updateProcessText(String s). Your swing class then implements this interface, basically forcing it to provide the public method you defined (this is no different than implementing ActionListener, which forces you to define actionPerformed). Secondly modify your processing class, so that it take's a class that implements the interface you just created, as one of the arguments in it's constructor. Lastly assign the argument from your construnctor to a private var - this will enable your processing class to have a handle to your swing class and update it as it pleases.
This might sound very complex, but it's really simple once you've done it once. -
How to Execute different classes using editplus
Consider a program like this
class abc
public static void main(String args[])
System.out.println("abc");
class bbc
public static void main(String args[])
System.out.println("bbc");
In this program there are two classes when i compile this code in editplus i wont get any error but if i want to execute only ABC class how to do that in editplus because in editplus we usually set the file name for JAVA execution
But here it is different SO,how to execute different classes in a program which is saved with arbitary name in EDIT PLUS..Try reading an editplus FAQ or posting to an editplus forum or even searching through help in editplus.
Maybe you are looking for
-
I have this report , where I have to bring the POS and forecast . I have a multi cube on POS and Forecast cube . Now I have to bring <b>52 weeks of POS Qty in the past</b> and <b>52 weeks Forecast Qty in the future</b> . My POS cube has 78 weeks data
-
Polynomial fitting for scatter plot
Hi all, I was wondering if there is any way to generate a polynomial fit to a scatter plot just like in excel. The data I am trying to fit has several y values for each x value. Thanks Krish Solved! Go to Solution.
-
HP LaserJet 4MV no longer prints from PDF on MacBook Air
Yes, I still use my Hewlett Packard LaserJet 4MV and with my MacBook Air with which I have been printing from Preview, Safari screen, email, AND from PDF's since I downloaded a patch from online 1-1/2 years ago. Inexplicably the HP LaserJet 4MV no l
-
HT4235 In trying to sync I get the message cannot find ipod! Any clues how to solve this?
I am tyring to sync my ipod but i am getting the message - Idpod cannot be synced becasue it cannot be found - I did the diagontics test and all is ok. Any clues?
-
How do i recover a security trust setting password?
i dont know what happend but the password for my computer security trust setting is not working now. how can i change the password?