A Java Swing Component Keeps Getting Disabled? - java

I am back with another problem :(
Let me show you guys the code:
JCheckBox pPec = new JCheckBox("Potion Effect");
pPec.setBounds(new Rectangle(50, 270, 140, 30));
pPec.setFont(fDisp);
List<String> pPeLl = new ArrayList<String>();
for (DPE dpe : DPE.values()){
pPeLl.add(dpe.toString());
}
String[] pPeL = pPeLl.toString().replace("[", "").replace("]", "").split(", ");
JComboBox<String> pPeE = new JComboBox<String>(pPeL);
pPeE.setBounds(new Rectangle(175, 270, 150, 30));
List<String> pPeNLl = new ArrayList<String>();
for (int i = 1; i <= 255; i++){
pPeNLl.add(Integer.toString(i));
}
String[] pPeNL = pPeNLl.toString().replace("[", "").replace("]", "").split(", ");
JComboBox<String> pPeN = new JComboBox<String>(pPeNL);
pPeN.setBounds(new Rectangle(175, 300, 73, 30));
JTextField pPeT = new JTextField();
((AbstractDocument)pPeT.getDocument()).setDocumentFilter(new NumberFilter());
pPeT.setBounds(new Rectangle(175+73+4, 300, 73, 30));
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerPotionEffect%%##")){
pPec.setSelected(true);
potionEffect = true;
break;
}else{
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
}
if (DFileLoader.getMethod(pathToSaveAs).size() <= 0){
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
}else{
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
pPec.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (pPec.isSelected()){
pPeE.setEnabled(true);
pPeN.setEnabled(true);
pPeT.setEnabled(true);
}else if (!pPec.isSelected()){
pPeE.setEnabled(false);
pPeN.setEnabled(false);
pPeT.setEnabled(false);
}
if (pPec.isSelected()) potionEffect = true;
else potionEffect = false;
}
});
pane.add(pPec);
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerPotionEffect%%##")){
String[] d = s.split("%%##");
String text;
if (d.length <= 1) text = "";
else text = d[3];
pPeE.setSelectedItem(d[1]);
pPeN.setSelectedItem(d[2]);
pPeT.setText(text);
}
}
}
pane.add(pPeN);
pane.add(pPeT);
pane.add(pPeE);
The DFileLoader.getMethod(String) returns a String List
What I am trying to do is that it loads the information from a file, and if the file starts with "playerPotionEffect%%##" (as shown after file.exists()), it sets the checkbox as selected. If not, it doesn't select it and it disables the other components shown in this piece of code. The checkbox selection works fine, it's just when I load the file, the 2 JComboBoxes and the JTextField are disabled, even though I want them to be enabled.
Can anyone help me? It might be really obvious where the problem is, and that I just haven't noticed. I have tried moving code around, but it still doesn't work.
the "pane" is a Container for the JFrame's content pane.
Also, I have it set to as you click on the checkbox, it enables and disables the other components. This works, and if I turned the checkbox off and on again, the components would be enabled. However, I just want it so that it is enabled on load when the box is checked.

Lol I suck!
To fix this, I have to enable the components in the loop as well before the break. Not all the strings start with playerPotionEffect
xD

Related

Loading images and data from a text file and appending to it (Java)

I've created a platform game where each type of game object is assigned to specific rgb values so I can create levels by drawing them out in paint and loading the image. Right now I have the first two levels already loaded and I am able to get the path of the 3rd level through a textfield input and load a custom 3rd level. Each level needs a path to the png image of the level, and the number of coins needed to progress to the next level. I want to have every level load up from one text file where each line maybe has the level number, the image path, and the # of coins. I'm making it to be customizable so that the user can add or change levels simply by adding these parameters through 3 textfields in my customize menu. This way also my designer can help create levels and by reading from the text file I imagine there will be a lot less code in the long run when there are 20+ levels. Any ideas on how I can load from and append to this file? Here's what I'm working with right now:
public static BufferedImageLoader loader = new BufferedImageLoader();
public Handler(Camera cam){
this.cam = cam;
level1 = loader.loadImage("/level1.png");
level2 = loader.loadImage("/level2.png");
}
public void changeLevel(){
clearLevel();
cam.setX(0);
Player.coinCount = 0;
if(Game.LEVEL == 1){
Player.maxCoins = 4;
LoadImageLevel(level1);
}
if(Game.LEVEL == 2){
LoadImageLevel(level2);
Player.maxCoins = 11;
}
if(Game.LEVEL == 3){
System.out.println(Data.levelPath);
try{
level3 = loader.loadImage(Data.levelPath);
LoadImageLevel(level3);
} catch (Exception e) {
e.printStackTrace();
System.out.println("error loading custom level");
}
}
}
public Menu(Game game, Handler handler){
this.handler = handler;
pathField = new JTextField(10);
levelField = new JTextField(10);
coinField = new JTextField(10);
if(Game.gameState == STATE.Menu){
int selection = JOptionPane.showConfirmDialog(
null, getPanel(), "Input Form : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.PLAIN_MESSAGE);
if(selection == JOptionPane.OK_OPTION) {
Data.levelPath = pathField.getText();
Data.level = levelField.getText();
Data.coinAmount = Double.valueOf(coinField.getText());
System.out.println(Data.levelPath + Data.level + Data.coinAmount);
}
}
private JPanel getPanel(){
JPanel basePanel = new JPanel();
basePanel.setOpaque(true);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
centerPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
JLabel mLabel1 = new JLabel("Enter path: (e.g., /level1.png) ");
JLabel mLabel2 = new JLabel("Enter which level to load the image in: ");
JLabel mLabel3 = new JLabel("Enter the amount of coins you must collect");
centerPanel.add(mLabel1);
centerPanel.add(pathField);
centerPanel.add(mLabel2);
centerPanel.add(levelField);
centerPanel.add(mLabel3);
centerPanel.add(coinField);
basePanel.add(centerPanel);
return basePanel;
}
Any ideas or suggestions are appreciated!
It's actually just....
Given a value of the input.getText() as 1#path#20, It have level number, the image path, and the number of coins separated by # token.
public static String [] separateFields(String input, String separator){
String[] separatedValues = input.split("#");
return separatedValues;
}
Call the function, define the arguments.
// input is textfield.getText() , and the value of input is 1#path#20
String [] result= separateFields(input, "#");
Then you get
int level = Integer.parseInt(result[0]); // level
String aPath = result[1]; // path
int numCoins = Integer.parseInt(result[2]); // number of coins

How to determine the correct position of an Image inside of a CTabItem

I add some CTabItems with Images to a CTabFolder:
CTabFolder tabFolder = new CTabFolder(someSection, SWT.BORDER);
ImageDescriptor deleteImageDesc = sharedImages.getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE);
Image deleteImage = deleteImageDesc.createImage();
CTabItem tabItem = new CTabItem(tabFolder, SWT.NONE);
tabItem.setImage(deleteImage);
// add more tabs...
Then I want to create a ToolTip which appears if user moves mouse over a deleteImage.
ToolTip deleteToolTip = new ToolTip(getShell(), SWT.BALOON);
deleteToolTip.setMessage("Delete");
tabFolder.addMouseTrackListener(new MouseTrackAdapter()
{
#Override
public void mouseHover(MouseEvent e)
{
toolTip.setLocation(tabFolder.toDisplay(e.x, e.y));
toolTip.setVisible(doesAnyOfTabImagesContainPoint(mousePosition));
}
});
To implement method doesAnyOfTabImagesContainPoint I need to determine the position of every deleteImage. Since CTabItem isn't a Control I cannot use method toDisplay. I try to solve this by manually determining the position of deleteImage relative to tabFolder. It would help because the mouse position held by MouseEvent is also relative to tabFolder.
private boolean doesAnyOfTabImagesContainPoint(Point p)
{
for (CTabItem tabItem : tabFolder.getItems())
{
Image i = tabItem.getImage();
Rectangle tabItemBounds = tabItem.getBounds();
Rectangle imageBounds = i.getBounds();
imageBounds.x += tabItemBounds.x;
imageBounds.y += tabItemBounds.y;
if (imageBounds.contains(p))
return true;
}
return false;
}
The requirement for working this properly is that Rectangle returned by i.getBounds() has correct location relative to tabItem. However it returns (0, 0, 16, 16) which cannot be right.
A dirty way to fix this would be to just add some constants:
imageBounds.x += bsTabBounds.x + 4;
imageBounds.y += bsTabBounds.y + 3;
But I am wondering if there's better way. I'm trying to investigate how CTabFolder positions images of the tabs but without success by now. Any help would be appreciated. Thanks in advance.
edit: for testing purposes here's the extracted image which i get from ISharedImages modified to see its border:
Give the code below a shot. It's based on my answer here.
public static void main(String[] args)
{
Display display = Display.getDefault();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final TabFolder folder = new TabFolder(shell, SWT.NONE);
TabItem item = new TabItem(folder, SWT.NONE);
item.setImage(display.getSystemImage(SWT.ICON_ERROR));
item.setText("Text");
folder.addListener(SWT.MouseMove, event -> {
TabFolder curFolder = (TabFolder) event.widget;
Point eventLocation = new Point(event.x, event.y);
TabItem theItem = curFolder.getItem(eventLocation);
if (theItem == null)
return;
Image image = theItem.getImage();
if (eventLocation.x >= curFolder.getClientArea().x + theItem.getBounds().x + image.getBounds().x
&& eventLocation.x <= curFolder.getClientArea().x + theItem.getBounds().x + image.getBounds().x + image.getBounds().width
&& eventLocation.y >= theItem.getBounds().y + image.getBounds().y
&& eventLocation.y <= theItem.getBounds().y + image.getBounds().y + image.getBounds().height)
{
System.out.println("show tooltip");
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
}
I've tested it on Windows 7 and it seems to be working fine.

Printing all content of a JList as output

I have a JList in my GUI, which uses an ArrayList as data:
ArrayList Cruise = new ArrayList();
Cruise.add("Scottish to Greek Waters");
Cruise.add("Greek to Scottish Waters");
JScrollPane scrollPane = new JScrollPane();
CruiseList = new JList(Cruise.toArray());
CruiseList.setPreferredSize(new Dimension(200, 200));
scrollPane.setViewportView(CruiseList);
CruiseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
CruiseList.setSelectedIndex(0);
CruiseList.setVisibleRowCount(6);
listPanel.add(scrollPane);
Frame1.setVisible(true);
I have a button - List all Cruises, which once clicked on should display this as output:
"Scottish to Greek Waters"
"Greek to Scottish Waters"
However, upon clicking the button, it only displays the selected list option as output.
This is what I have so far:
listallCruises.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String AllCruises = CruiseList.getSelectedValue().toString();
System.out.print("All Cruises:\n" + AllCruises + CruiseList.getModel() + "\n");
}
});
How do I print out all element in the list upon clicking the button?
You are outputting just the selected value because that's the method you are calling, getSelectedValue().
To display ALL the values, you have to get the model and iterate through the values, like so:
int size = CruiseList.getModel().getSize();
StringBuilder allCruises = new StringBuilder("All cruises:");
for(int i = 0; i < size; i++) {
allCruises.append("\n").append(CruiseList.getModel().getElementAt(i));
}
System.out.print(allCruises);

Image as a variable in JLabel, to be used in if-else

I'm a newbie so please be patient
What I want
I have a JPanel on which I have a JButton, a JLabel and a JTextArea. Upon pressing JButton, an image has to be printed inside the JLabel (and some text in JTextArea). This certain image (and text) is determined by if-else statements. Conditions of if-else are based on an integer variable R.
Basically its a survey like question-answer thing I'm trying to make. I use the R to record answers from user. When a user clicks a choice, the value of R gets updated.
Its working fine for the text, but not the image.
For text, I use a String variable yourphone. If the value of R in the end is eg 120, then yourphone gets updated to a string eg. Xperia Z.
I want a similar variable I can use for image, so that the picture of Xperia Z is displayed when the user clicks JButton.
Total value of R is used in if-else statements.
Structure
I initiate variables like this
int R=0;
String yourphone;
ImageIcon imageresult;
My JPanel which is meant to display result
final JPanel result = new JPanel();
result.setBackground(Color.BLACK);
getContentPane().add(result, "name_17130054294139");
result.setLayout(null);
final JTextArea txtrphoneresult = new JTextArea();
txtrphoneresult.setBackground(Color.BLACK);
txtrphoneresult.setForeground(Color.YELLOW);
txtrphoneresult.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtrphoneresult.setBounds(448, 515, 469, 121);
result.add(txtrphoneresult);
JLabel resultlabel = new JLabel(imageresult);
resultlabel.setBounds(292, 122, 782, 346);
result.add(resultlabel);
JButton btnShowResult = new JButton("Show Result");
btnShowResult.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnShowResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(R==1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
ImageIcon imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R==5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
ImageIcon imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
txtrphoneresult.setText(yourphone);
}
});
btnShowResult.setBounds(618, 48, 130, 32);
result.add(btnShowResult);
Problem
The image is not displayed at all.
If there is any other possible way to achieve this, please guide.
At first you create your imageresult inside if-else and it's not visible for all method. And you doesn't add your image to JLabel.
Make resultlabel as clas member or final variable.
Change your code in next way:
public void actionPerformed(ActionEvent e) {
ImageIcon imageresult = null;
if(R==1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R==5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
resultlabel.setIcon(imageresult)
txtrphoneresult.setText(yourphone);
}
Declare ImageIcon imageresult before the if statement and call
resultlabel.setIcon(imageresult)
after txtrphoneresult.setText(yourphone);
BTW: Don't use null layout/setBounds(). Read about layouts and choose proper one.
where do you set icon for your label.
you mising this line
resultlabel.setIcon(imageresult);
Make resultLabel final and change action performed:
public void actionPerformed(ActionEvent e)
{
ImageIcon imageresult = null;
if(R == 1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R == 5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
txtrphoneresult.setText(yourphone);
resultlabel.setIcon(imageresult);
}
The image is not displayed because you are not "giving" it to you JLabel. You can do it by using the setIcon() method.
You also have a problem with variable declaration. Unlike PHP and some other programming languages, in Java a variable only exists within the brackets (and sub-brackets) {} it has been declared in (despite there are some exceptions). For example :
public void myMethod() {
float b = 5f;
if (true) {
int a = 6;
if (true) {
// a exists, you can do whatever you like with it
// b exists, you can do whatever you like with it
}
// a exists you can do whatever you like with it
// b exists, you can do whatever you like with it
} // a is "destroyed"
// a doesn't exists
// b still exists
} // b is "destroyed"
// Neither a or b exists
You are in the exact same case with the declaration of your variable imageresult.

"Unexpected type" error

I'm having a problem compiling my Java program:
\Desktop\Java Programming\JFrameWithPanel.java:79: unexpected type
required: variable
found : value
if(serviceTerms.isSelected() = false)
^
1 error
What is causing this error?
public class JFrameWithPanel extends JFrame implements ActionListener, ItemListener
{
int packageIndex;
double price;
double[] prices = {49.99, 39.99, 34.99, 99.99};
DecimalFormat money = new DecimalFormat("$0.00");
JLabel priceLabel = new JLabel("Total Price: "+price);
JButton button = new JButton("Check Price");
JComboBox packageChoice = new JComboBox();
JPanel pane = new JPanel();
TextField text = new TextField(5);
JButton accept = new JButton("Accept");
JButton decline = new JButton("Decline");
JCheckBox serviceTerms = new JCheckBox("I Agree to the Terms of Service.", false);
JTextArea termsOfService = new JTextArea("This is a text area", 5, 10);
public JFrameWithPanel()
{
super("JFrame with Panel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane.add(packageChoice);
setContentPane(pane);
setSize(250,250);
setVisible(true);
packageChoice.addItem("A+ Certification");
packageChoice.addItem("Network+ Certification ");
packageChoice.addItem("Security+ Certifictation");
packageChoice.addItem("CIT Full Test Package");
pane.add(button);
button.addActionListener(this);
pane.add(text);
text.setEditable(false);
text.setBackground(Color.WHITE);
text.addActionListener(this);
pane.add(termsOfService);
termsOfService.setEditable(false);
termsOfService.setBackground(Color.lightGray);
pane.add(serviceTerms);
serviceTerms.addItemListener(this);
pane.add(accept);
accept.addActionListener(this);
pane.add(decline);
decline.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
packageIndex = packageChoice.getSelectedIndex();
price = prices[packageIndex];
text.setText("$"+price);
Object source = e.getSource();
if(source == accept)
{
if(serviceTerms.isSelected() = false) // line 79
{
JOptionPane.showMessageDialog(null,"Please accept the terms of service.");
}
else
{
JOptionPane.showMessageDialog(null,"Thanks.");
}
}
}
You have an (illegal) assignment instead of a comparison. Surely you mean:
if (serviceTerms.isSelected() == false)
Of course the preferential, and more readable, way to write this condition is:
if (!serviceTerms.isSelected())
The problem is that you are using the assignment operator =. What you should be using is the equality operator == like the following:
if(serviceTerms.isSelected() == false) // line 79
{
JOptionPane.showMessageDialog(null,"Please accept the terms of service.");
}
Or, to totally bypass this mistake, you should skip comparing to false and use the ! (not) operator like so.
if(!serviceTerms.isSelected()) // line 79
{
JOptionPane.showMessageDialog(null,"Please accept the terms of service.");
}
I feel this way reads better.
If not, service terms is selected
That reads more like a sentence than:
If service terms is selected equals false

Categories