Java how do I access text field - java

I'm relatively new to programming. Hoping someone can help. I have a button that creates a series of labels and text boxes within a frame once the user enters a number. I'm having trouble access the text boxes once they are created. Can someone point me in the right direction. Code snips below. Thanks.
method to create a label and text box.
public JTextField createPrizePanels(){
JLabel prizePanel = new JLabel("Enter Prize Here", SwingConstants.CENTER);
prizePanel.setVerticalAlignment(SwingConstants.TOP);
prizePanel.setFont(new Font("Arial", Font.BOLD, 14));
prizePanel.setForeground(Color.BLUE);
Border border = BorderFactory.createLineBorder(Color.GRAY, 1);
prizePanel.setBorder(border);
prizePanel.setOpaque(true);
prizePanel.setBackground(Color.LIGHT_GRAY);
prizePanel.setBounds(setBoundsX, setBoundsY, 120, 60);
prizeTextBox = new JTextField(50);
prizeTextBox.setBounds(setBoundsX + 5, setBoundsY + 20, 110, 30);
prizeTextBox.setFont(new Font("Arial", Font.BOLD, 12));
prizeTextBox.setOpaque(true);
prizeTextBox.setBackground(Color.WHITE);
prizeTextBox.setForeground(Color.BLACK);
prizeTextBox.setText("No Prize");
prizeTextBox.setHorizontalAlignment(JTextField.CENTER);
lp.add(prizePanel);
lp.add(prizeTextBox);
return prizeTextBox;
}
code that creates multiple text boxes bases on input from user.
JButton numberOfBallonsButton = new JButton("Set");
numberOfBallonsButton.setBounds(360,160,95, 0x1e);
numberOfBallonsButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
numberOfBallons = Integer.parseInt(numberOfBallonsTextBox.getText());
System.out.println(numberOfBallons);
lp.remove(numberOfBallonsButton);
for(int i = 0; i < numberOfBallons; i++ ){
createPrizePanels();
setBoundsX = setBoundsX +125;
if(setBoundsX > 450){
setBoundsX = 120;
setBoundsY = setBoundsY + 65;
}
}
lp.add(startGameButton);
}
});
Up to this point it works fine. However, the user needs to enter text into each text box and press another button. I'm not sure how to access each text field. Thanks in advance.

You are using local fields.you can create global field and the return value of createPrizePanels() is never used and for your case you don't know number of created textfield so you can use List as global field and when you create textfield add it to the list so you access it later from anywhere

Related

JPanel/JFrame Automatically resizing. JAVA

I so have made a GUI for a Chat that im currently working on. Its aaaaalmost done but the only thing is the automatically resizing when dragging the window. I can't find out why its happend and this was my last chance. So I really need help from you guys! Im kinda out of idea
The code is here:
ClientGUI(String host, int port) {
super("Chat Client");
defaultPort = port;
defaultHost = host;
// The CenterPanel which is the chat room
MessageText = new JTextArea("Welcome to the Chat room\n");
JPanel centerPanel = new JPanel();
MessageText.setWrapStyleWord(true);
MessageText.setLineWrap(true);
centerPanel.setLayout(null);
JScrollPane scrollPane = new JScrollPane(MessageText);
scrollPane.setBounds(0, 0, 584, 486);
getContentPane().add(scrollPane);
MessageText.setEditable(false);
getContentPane().add(centerPanel, BorderLayout.CENTER);
WriteMessage = new JTextField("Write your username here!");
WriteMessage.setBounds(0, 492, 584, 35);
centerPanel.add(WriteMessage);
WriteMessage.setColumns(234);
WriteMessage.setBackground(Color.WHITE);
// the 3 buttons
Login = new JButton("Login");
Login.setBounds(594, 338, 125, 35);
centerPanel.add(Login);
Logout = new JButton("Logout");
Logout.setBounds(594, 469, 125, 35);
centerPanel.add(Logout);
Logout.addActionListener(this);
Logout.setEnabled(false); // you have to login before being able to logout
Online = new JButton("Online");
Online.setBounds(594, 403, 125, 35);
centerPanel.add(Online);
Online.addActionListener(this);
Online.setEnabled(false); // you have to login before being able to Who is in
JLabel PortNumberText = new JLabel("Port Number: ");
PortNumberText.setBounds(594, 83, 144, 20);
centerPanel.add(PortNumberText);
PortNumber = new JTextField("" + port);
PortNumber.setBounds(594, 114, 129, 20);
centerPanel.add(PortNumber);
PortNumber.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel ServerText = new JLabel("Server Address: ");
ServerText.setBounds(594, 21, 240, 20);
centerPanel.add(ServerText);
// the two JTextField with default value for server address and port number
ServerAddress = new JTextField(host);
ServerAddress.setBounds(594, 52, 129, 20);
centerPanel.add(ServerAddress);
Login.addActionListener(this);
WriteMessage.requestFocus();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(760, 570);
setVisible(true);
}
A picture what I mean
Don't use a null layout. Don't use setBounds(). Swing was designed to be used with layout managers.
Resizing of components can only be done when you use a layout manager. Read the section from the Swing tutorial on Layout Manager for more information and examples. You can always use multiple panels each with a different layout manager to get your desired results.
Also follow Java naming conventions. Variable names should NOT start with an upper case character. Half the time your names are correct and half the time they are not. Be consistent!
You are using a Null-Layout (absolute positioning), and this means you have to take care of everything related to layout yourself. Better use a LayoutManager.
Alright so I just made a border layout all from start so I guess its all good, Thanks everyone for helping! Doesnt look that professional. So yeah, Might be some more updates later on :)

JXDatePicker make arrows in the JXMonthView bigger

I want to use this JXDatePicker component in a application that will work on a touch display. Because the default component is small, all the dates and the buttons are hard to click using a bad touch screen I wanted to make them bigger. So far I successfully made the result text field bigger (the one showing the selected date, by changing the font), make the pop-up bigger (the JXMonthView, also by changing its font), change the picture of the JXDatePicker with a bigger image, set the default date to be the current date, set the date format, etc. This is my code:
private void touch_screen_datepicker(JXDatePicker date_picker) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
JXMonthView monthView = date_picker.getMonthView();
date_picker.setDate(new Date());
date_picker.setFont(new Font(Font.DIALOG, Font.PLAIN, 50));
JButton btn_pick = (JButton) date_picker.getComponent(1);
btn_pick.setBackground(new Color(66, 147, 223));
Image image = toolkit.getImage("/home/adrrian/Image/calendar/" + "calendar image 4.png"); //Земање на сликата за мк знаме
ImageIcon icon = new ImageIcon(image); //Правење на икона
btn_pick.setIcon(icon); //Поставување на иконата
SimpleDateFormat longFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat shortFormat = new SimpleDateFormat("yy-MM-dd");
Date startDate = new Date(0);//01.01.1970
shortFormat.set2DigitYearStart(startDate);
DatePickerFormatter formatter = new DatePickerFormatter(
// invers sequence for parsing to satisfy the year parsing rules
new DateFormat[]{shortFormat, longFormat}) {
#Override
public String valueToString(Object value) throws ParseException {
if (value == null) {
return null;
}
return getFormats()[1].format(value);
}
};
DefaultFormatterFactory factory = new DefaultFormatterFactory(formatter);
date_picker.getEditor().setFormatterFactory(factory);
monthView.setFont(new Font(Font.DIALOG, Font.PLAIN, 50));
monthView.setFirstDayOfWeek(Calendar.MONDAY);
}
and this is an image of my final work:
My main problem is how to make the arrow that are changing the months (for example if I go back from this image to show September). I tried listing all of the components, like I did for the button, but still I didn't found anything. Also for better GUI I like to find that dark blue color (where the month is displayed), to make my button the same.
Hope someone can help me. Thanks in advance.
Toolkit toolkit = Toolkit.getDefaultToolkit();
JXMonthView monthView = date_picker.getMonthView();
/*EDITED*/
//1
date_picker.putClientProperty("JComponent.sizeVariant", "large");
monthView.putClientProperty("JComponent.sizeVariant", "large");
//2
date_picker.putClientProperty("JXComponent.sizeVariant", "large");
monthView.putClientProperty("JXComponent.sizeVariant", "large");
//3
date_picker.putClientProperty("JXDatePicker.sizeVariant", "large");
monthView.putClientProperty("JXMonthView.sizeVariant", "large");
//
date_picker.putClientProperty("JDatePicker.sizeVariant", "large");
monthView.putClientProperty("JMonthView.sizeVariant", "large");
SwingUtilities.updateComponentTreeUI(this);
SwingUtilities.updateComponentTreeUI(date_picker);
SwingUtilities.updateComponentTreeUI(monthView);
date_picker.updateUI();
monthView.updateUI();
/*EDITED*/
As #Vighanesh Gursale suggested I insterdet this lines and also did the frame.pack() before setVisible(true), but nothing changes.
I have made some code using nimbus look and feel, i know it is not exact that you want but it is pretty much helpful. Check this code. To perform same you need to find the key of your next and previous buttons key in my case it is Button.margin. Try to use the same key in your code if you are lucky it would work.
import javax.swing.*;
import java.awt.*;
public class Demo {
JFrame frame = new JFrame("");
JButton btn = new JButton("Example");
public Demo() {
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(btn);
frame.setVisible(true);
}
public static void main(String[] args) {
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
Insets insets = new Insets(50, 20, 50, 20); //change the size of button
UIManager.put("Button.margin", insets);
}
catch(Exception e)
{
e.printStackTrace();
}
Demo d = new Demo();
}
}
Also keep in mind to use default look and feel or any other look and feel.
This question is quite old but for everyone who is looking how it can be done
UIManager.put("JXMonthView.monthDownFileName", <PATH_TO_IMAGE>);
UIManager.put("JXMonthView.monthUpFileName", <PATH_TO_IMAGE>);
monthDownFileName refers to previous month
monthUpFileName refers to next month
this will change the image with other of your choice (and size)

how to make JTable display all records form database

My problem is when i run the program the data displayed at the JTable but not all records are displayed although i have a scroll Pane and aJtable inside it,when i run it provides a scroll but for the firs few records ,the jtable have a textfield to provide searching in table using rowSorter ,although jtable doesn't show all records when i search for a record that is not viewed i gets it.this is an image describing the problem.please how can i fix that.
this is the link i have no permission to attache an image here
http://www.megafileupload.com/en/file/561971/Untitled-jpg.html
this is piece of code where i initialize these component
table2 = new JTable(tableModel);
table2.setFont(new Font("Tahoma", Font.PLAIN, 16));
table2.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 14));
scrollPane_1.setColumnHeaderView(table2.getTableHeader());
table2.setBackground(new Color(210, 180, 140));
table2.setBorder(new LineBorder(new Color(105, 105, 105)));
table2.setForeground(new Color(0, 0, 0));
sorter2 = new TableRowSorter<TableModel>(table2.getModel());
table2.setRowSorter(sorter2);
JViewport vp2 = new JViewport();
vp2.setBackground(new Color(210, 105, 30));
vp2.setForeground(new Color(0, 0, 0));
scrollPane_1.setViewportView(vp2);
vp2.add(table2);
this is the method that fill the table
table2Data = new Vector<>();
Iterator<SellBean> buyIt = boughtedList.iterator();
while (buyIt.hasNext()) {
SellBean buyBean = buyIt.next();
Vector rec = new Vector<>();
rec.add(buyBean.getPRODUCT_ID());
rec.add(buyBean.getPRODUCT_NAME());
// System.out.println(buyBean.getPRODUCT_NAME());
rec.add(buyBean.getQUANTITY());
rec.add(buyBean.getBUY_PRICE());
rec.add(buyBean.getSELL_PRICE());
rec.add(buyBean.getPROFIT());
rec.add(buyBean.getBUY_DATE());
rec.add(buyBean.getRETURNED());
table2Data.add(rec);
}
tm2.setDataVector(table2Data, table2ColNames);
for (int i = 0; i < table2.getColumnCount(); i++) {
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
table2.getColumnModel().getColumn(i)
.setCellRenderer(centerRenderer);
}
for (int i = 0; i < table2.getRowCount(); i++) {
table2.setRowHeight(i, 28);
}
table2.getColumnModel().getColumn(0).setPreferredWidth(25);
}
i hope it is clear now
Maybe you have problems with the scrollpane (like: no scrollbars visible).
Are your sure you are using it correct?
this looks strange to me:
You create a ViewPort and put this as View?!
JViewport vp2 = new JViewport();
scrollPane_1.setViewportView(vp2);
vp2.add(table2);
why not just set the Table as ViewportView (as the name implies?)
just:
scrollPane_1.setViewportView(table2);
Edit: Info about the ViewPort:
The "viewport" or "porthole" through which you see the underlying information. When you scroll, what moves is the viewport. It is like peering through a camera's viewfinder. Moving the viewfinder upwards brings new things into view at the top of the picture and loses things that were at the bottom.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JViewport.html

Refresh data on JLabel - Java SWING

I'm trying to Refresh my data on JLabel Text.
My data on "mod.getAllPlaneteByUser(u).getQte_or()" get data from my DataBase.
The component "lblRefresh" is just a JLabel listener.
--> Initialization :
JLabel lblRessOr = new JLabel();
lblRessOr.setText(Integer.toString(mod.getAllPlaneteByUser(u).getQte_or()));
--> Add By default on my contentPane :
lblRessOr.setForeground(Color.RED);
lblRessOr.setFont(new Font("Lucida Grande", Font.BOLD, 16));
lblRessOr.setBounds(225, 141, 73, 16);
contentPane.add(lblRessOr);
--> Use on my MouseListener :
if(e.getSource() == lblRefresh){
lblRefresh.setText(Integer.toString(mod.getAllPlaneteByUser(u).getQte_or()));
lblRefresh.repaint();
}
Anybody know how i can refresh my data ?
If you are attempting to change the text in the lblRessOr Jlabel you would place the below code in your listener block.
if(e.getSource().equals(lblRefresh)){
lblRessOr.setText(Integer.toString(mod.getAllPlaneteByUser(u).getQte_or()));
}

Java Swing JSlider

In my game im currently working on a basic main menu and im looking for a few things.
Currently the only way to see which Jslider is which is by hovering over it.. any suggestions?
When i change the JSlider brightness or the JSlider audio it doesnt actualy update until i switch tabs and return.
When i close the game and reopen it the settings return to default. how to create a variable to preserve settings?
all code is here https://github.com/FeatheredOrcian/Kingdomcraft.git
if you would rather just see the class that the code is partaining to https://github.com/FeatheredOrcian/Kingdomcraft/blob/master/Kingdomcraft/src/com/pointlight/kingdomcraft/render/Render.java
thx
I'd suggest you add a JLabel next to your slider
You need to update the setToolTipText in your statechangelistener. Whenever the state changes, you want you need to let your slider know that it's tooltiptext has changed.
You want to use something like Preferences. Preferences API Overview
*As MadProgrammer mentioned in the comments. Avoid using setBounds, setSize or setLocation. Please review Layout Managers. The only reason I kept them in the below code is so you could see how to implement the suggestions to the 3 questions you asked.
Below is an example of the code changes that I mentioned above. Good luck!
settings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
remove(createWorld);
remove(addServer);
repaint();
// Get stored preferences and specific default values if they
// do not exist
final Preferences prefs = Preferences.userNodeForPackage(Render.class);
soundLevel = prefs.getInt("SOUND_LEVEL", 50);
lightLevel = prefs.getInt("LIGHT_LEVEL", 50);
// Add sound label
JLabel soundLabel = new JLabel("Sound: ");
soundLabel.setBounds(170, 110, 150, 35);
soundLabel.setForeground(Color.white);
add(soundLabel);
add(sound);
sound.setBounds(210, 110, 150, 35);
sound.setMinimum(0);
sound.setMaximum(100);
sound.setValueIsAdjusting(true);
sound.setValue(soundLevel);
sound.setToolTipText("Audio: " + soundLevel + "%");
sound.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
soundLevel = sound.getValue();
// Update tooltip value
sound.setToolTipText("Audio: " + soundLevel + "%");
// Save sound value in pref
prefs.putInt("SOUND_LEVEL", soundLevel);
}
});
// Add light label
JLabel lightLabel = new JLabel("Light: ");
lightLabel.setBounds(370, 110, 150, 35);
lightLabel.setForeground(Color.white);
add(lightLabel);
add(light);
light.setBounds(405, 110, 150, 35);
light.setMinimum(0);
light.setMaximum(100);
light.setValueIsAdjusting(true);
light.setValue(lightLevel);
light.setToolTipText("Brightness: " + lightLevel + "%");
light.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
lightLevel = light.getValue();
// Update tooltip value
light.setToolTipText("Brightness: " + lightLevel + "%");
// Save light value in pref
prefs.putInt("LIGHT_LEVEL", lightLevel);
}
});
}
});

Categories

Resources