here I am trying to call overloaded constructor after some condition has met in my main() program , which is given by variable a. Code works fine when I am using only default constructor , but I need to call overloaded constructor at some point and it fails . folowing is code:
overloaded constructor :
public Paddle(int a){
if(a ==1){
ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle1));
image = ii.getImage();
}
else {
ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle2));
image = ii.getImage();
}
width = image.getWidth(null);
height = image.getHeight(null);
resetState();
}
// further initialization --
default constructor :
public Paddle(){
ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle));
image = ii.getImage();
width = image.getWidth(null);
height = image.getHeight(null);
System.out.println(height+" "+width);
resetState();
}
thanks for help in advance, further queries can be asked but I think this piece of code has some problem . Thank you
Answer
You are not setting the instance variable image in the overloaded constructor.
Correct Way
The way you are doing it is violating DRY ( Don't Repeat Yourself )!
The best way is to make the no arg constructor call the overloaded one and then set the instance variable image in one place.
public Paddle(final int i)
{
if (i==1) { this.image = one thing }
else
{ this.image = another thing }
}
public Paddle() { this(0); }
A better way would be to just pass in the resource to a single constructor and be done with it, without seeing all the code, this looks overly complicated.
Related
If it's not apparent by the question, I'm not very amazing at java yet. I'm just playing tonight with a few fundamentals that I would need to be comfortable with for a little idea I have, but have hit a problem. I may just be tired and missing something, if so I apologize.
This is the code in the Main.java class:
private int h,w;
public static void main(String args[]){
Main inst = new Main();
inst.Frame();
Second s = new Second();
}
public void Frame(){
this.h = 200;
this.w = 200;
}
public int getWidth(){
return w;
}
public int getHeight(){
return h;
}
It's a very basic program, just aiming to create two ints (h,w) and change their values in Frame(), and then using the two methods at the bottom return the 200 values in class 2.
This is second.java:
Second(){
this.Window();
}
public void Window(){
System.out.println("window()");
Main win = new Main();
int width = win.getWidth();
int height = win.getHeight();
System.out.println("width and height "+width+height);
}
The output in Window() simply gives two zeroes. this is countered by changing the values the moment they are created (Public int w=200,h=200), but this is not what I'm looking to do, as it needs to be changed at a further point.
Any ideas how to get the changes done in Frame() to appear in the Window ints? Thanks a lot :)
You're creating two independent instances of Main, each with their own h & w values. You change the values of the first instance, then print them from the second, unchanged instance.
You probably want to pass your Main instance as an argument to the Second constructor, so they can share the same data.
`Second(Main m){
this.Window(m);
}
public void Window(Main m){
System.out.println("window()");
Main win = m;
int width = win.getWidth();
int height = win.getHeight();
System.out.println("width and height"+width+height);
}`
You have a void method, not a constructor. Remove the void keyword.
I have been trying to figure out how to find the height and width of the screen in android. i have found a way to get it but I dont know how to call the getScreenWidth and getScreenHeight to put values into my int height and int width?
public class Player {
public int across;
public int upDown;
public static int getScreenWidth(Context c) {
DisplayMetrics dmetrics = new DisplayMetrics();
((Activity) c).getWindowManager().getDefaultDisplay()
.getMetrics(dmetrics);
return dmetrics.widthPixels;
}
// Get screen height
public static int getScreenHeight(Context c) {
DisplayMetrics dmetrics = new DisplayMetrics();
((Activity) c).getWindowManager().getDefaultDisplay()
.getMetrics(dmetrics);
return dmetrics.heightPixels;
}
public Player() {
int width = dmetrics.widthPixels;
int height = dmetrics.heightPixels;
int rectSide = 1000;
//across = startPosX;
//upDown = startPosY;
}
i am trying to get it by using int width = dmetric.widthPixels; but this obviously isnt the way to call the getScreenWidth. Im pretty bad at this stuff, so any help would be great.
You can refer to Here
or Here
for your answer.
Ps - sorry , I can't comment as I am a beginner so I wrote the answer which should rather be a comment.
I know, really what im asking is how do i call this get method i have created to set values for width and height? – Phill
If you are in an Activity when you wish to call these static methods you could call them this way:
int width = Player.getScreenWidth(this);
int height = Player.getScreenHeight(this);
If you're not in an activity you'll need to know one and pass it instead of this.
Also be aware that, because of the cast, if you pass something that is a Context but not an Activity it won't work and you won't know it until run time.
I'm working on a homework project for an intro to java course. To practice calling methods and organizing tasks, we have to create two balloon objects s1 and s2 and modify their colors and altitudes using methods in a separate java class.
I have everything working fine, but not exactly to the requirements of the assignment. The sheet lists the method declarations and they cannot be changed, only the code within them can.
The method that is used to change a balloon's color is to be created as public void setColor(). This doesn't make sense to me, though. I'm using public void setColor(String color) for now.
How can I change the color property of a balloon object without passing anything to the setColor method?
I totally agree with #RealSkeptic but as your question says that changing the color without passing any value it means you need to generate the color each time your could use the following code. I'm not sure do this code is what you need.
public void setColor()
{
int red,green,blue;
red = green = blue = 0;
Random random = new Random();
int high = 255, low = 0;
red = random.nextInt(high-low)+low;
green = random.nextInt(high-low)+low;
blue = random.nextInt(high-low)+low;
color = new Color(red,green,blue);
//set this color to your balloon
}
Well, you can't specify any particular color without a parameter in the method. You can hardcode so that the color changes.
class Baloon {
private String[] colors = {"blue", "red" , "green"};
private int index = 0;
private String currentColor = colors[index];
public void setColor(){
index ++;
if (index = colors.length)
index = 0;
currentColor = colors[index];
}
}
I have tp place a AutoCompleteField in one of my screen in Blackberry app. I have to show a place holder text to provide hint for user to enter the information.
Here is the below code of AutoCompleteField
BasicFilteredList filterList = new BasicFilteredList();
String[] address = { "T 115 Centro Galleria Shopping Centre, Cnr Old Collier and Walters Road Morley WA 1522",
"1423 SEAVIEW POINT POINT COOK VIC 2674",
"Lot 1498 Yarraman Road Wyndham Vale VIC 3795",
"Lot 3506 Witchmount Close Hillside VIC 4055",
"6 Paas Place Williamstown VIC 4233",
"Lot 99 14 James Close Sunbury VIC 4502",
"1 Charlotte Street Clayton South VIC 4779" };
filterList.addDataSet(1, address, "address", BasicFilteredList.COMPARISON_IGNORE_CASE);
AutoCompleteField autoCompleteField = new AutoCompleteField(filterList){
public void onSelect(Object selection, int SELECT_TRACKWHEEL_CLICK) {
ListField _list = getListField();
if (_list.getSelectedIndex() > -1) {
if(selectedText!=null){
BasicFilteredListResult result = (BasicFilteredListResult) selection;
selectedText.setText(result._object.toString());
}
}
}
};
add(autoCompleteField);
Anyone, please suggest me how could I implement the same.
Thanks.
You can use a similar technique to the one shown here for normal EditFields. Basically, you need to override the paint() method in an AutoCompleteField subclass. In paint(), you check and see if the field is empty, and if so, you manually draw the placeholder text you want.
The difference is that AutoCompleteField is a Manager with a BasicEditField inside of it. So, to draw the text properly, you need to figure out the x and y offsets of the edit field within the parent Manager (the AutoCompleteField).
So, replace your AutoCompleteField instance with an instance of this class:
private class CustomAutoCompleteField extends AutoCompleteField {
private int yOffset = 0;
private int xOffset = 0;
public CustomAutoCompleteField(BasicFilteredList filteredList) {
super(filteredList);
}
protected void paint(Graphics g) {
super.paint(g);
if (xOffset == 0) {
// initialize text offsets once
xOffset = getEditField().getContentLeft();
yOffset = getEditField().getContentTop();
}
String text = getEditField().getText();
if (text == null || text.length() == 0) {
int oldColor = g.getColor();
g.setColor(Color.GRAY);
g.drawText("enter text", xOffset, yOffset);
g.setColor(oldColor);
}
}
public void onSelect(Object selection, int SELECT_TRACKWHEEL_CLICK) {
ListField _list = getListField();
if (_list.getSelectedIndex() > -1) {
if(selectedText!=null){
BasicFilteredListResult result = (BasicFilteredListResult) selection;
selectedText.setText(result._object.toString());
}
}
}
}
I tested this on OS 5.0, with an instance that didn't have any margin or padding set. It's possible that with different layouts, you may need to adjust the logic for calculating the x and y offsets. But, the above code shows you the basic idea. Good luck.
Edit: the above code is presented with the caveat that your onSelect() method is clearly relying on code not shown. As is, the above code won't compile. I left onSelect() in there just to show that I'm essentially just replacing the anonymous class you originally had, and not doing anything different in your onSelect() method, as it's not directly related to the placeholder text issue.
I made some menu and it is to update conmmon variables (for text on grid) then the out-of-focus dialog must repaint the grid. Here is the screenshot:
The main control panel is always at top position and 'Data Display' panel is always sitting behind it. When press a button on front panel, Data Display must update its grid. Currently, the common variable 0.4 on the grid is updated by adding listener and works fine. But the grid itself is not repainting anymore. How can I repaint the out-of-focus dialog in real time?
Here is the code of the front panel:
public class MainDisplayForm extends javax.swing.JFrame {
Storage st = new Storage();
DisplayForm dF = new DisplayForm();
....
public MainDisplayForm() {
initComponents();
Btn_IncreaseGain.addActionListener(new ButtonListener_IncreaseGain());
}
....
} //MainDisplayForm ends here.
class ButtonListener_IncreaseGain implements ActionListener {
DisplayForm dF = new DisplayForm();
Storage st = new Storage();
ButtonListener_IncreaseGain()
{
}
public void actionPerformed(ActionEvent e) {
st.iGain = 20;
dF.revalidate();
dF.repaint();
System.out.println("Testing");
}
}//Listener ends here.
Here is code of Data Display:
public void paint(Graphics g)
{
g2 = (Graphics2D) g;
paintComponents(g2);
//added numbers are for adjustment.
int x = this.jPanel1.getX()+8;
int y = this.jPanel1.getY()+30;
int width = this.jPanel1.getWidth()+19;
int height = this.jPanel1.getHeight()+40;
//labelling voltages
label0.setText(st.zero);
label1.setText(st.v1);
label2.setText(st.v2);
label3.setText(st.v3);
label4.setText(st.v4);
label5.setText(st.v3);
label6.setText(st.v4);
g2.setColor(Color.darkGray);
for(int i=x; i<width; i=i+80)
{
g2.drawLine(i, y, i, height);
}
int j = 0;
for(int i=y; i<height; i=i+80)
{
j++;
//st.iGain
g2.setColor(Color.orange);
if(j==1)
{
double k1 = st.iGain * 0.4;
st.v1 = Double.toString(k1);
g2.drawString(st.v1, x+5, y+10);
}
if(j==2)
{
double k2 = st.iGain * 0.3;
st.v2 = Double.toString(k2);
g2.drawString(st.v2, x+5, y+90);
}
g2.setColor(Color.DARK_GRAY);
g2.drawLine(x, i, width, i);
....
} //grid info is not completed yet.
Thanks,
Focus isn't the issue and has nothing to do with your current problem. The solution is to change the properties of the data grid by updating fields it contains via setter methods and calling repaint on the JComponent (perhaps a JPanel, or some other component that derives ultimately from JComponent) held by the data grid. The paintComponent method of this component should use its class fields to update what it draws.
You almost never paint in the paint method of a JComponent and certainly you don't want to draw directly into a top-level window. You also probably don't want to set text of JLabels, JTextFields, or any other JTextComponent. from within paint/paintComponent.
I can't see why your code is not working and can only guess that the likely cause of your problem is in code not shown.
Edit 1:
Just guessing, but you may have a problem of references. I notice that your listener class creates new DisplayForm and Storage objects:
DisplayForm dF = new DisplayForm();
Storage st = new Storage();
There's a good possibility that these objects are not the ones being displayed, especially if you create these objects elsewhere and display them. Again I'm just guessing since I don't see the rest of your code, but perhaps you should to pass references for these objects into the DisplayForm via constructor or setter method parameters.
Edit 2:
e.g.,
public void setDisplayForm(DisplayForm dF) {
this.dF = dF;
}
// same for Storage
And in the main program:
public MainDisplayForm() {
initComponents();
ButtonListener_IncreaseGain btnListenerIncreaseGain = new ButtonListener_IncreaseGain();
btnListenerIncreaseGain.setDisplayForm(....);
btnListenerIncreaseGain.setStorage(....);
Btn_IncreaseGain.addActionListener(btnListenerIncreaseGain);
}