i am coding a program using SWing in java, but this is my problem, when i press a button, I want that every time I press a button, I update a new image in the same position as the previous one, I try to do it in the action listener of the code, but the image is not updated and the one that was At the beginning, can someone help me in this? Thank you very much.
public MainWindow() {
initComponents();
setIconImage(Icono);
this.setLocationRelativeTo(null);
this.setResizable(false);
Imagen fondo=new Imagen();
this.add(fondo, BorderLayout.CENTER);
this.pack();
PracticeMode = new javax.swing.JDialog();
}
private void StartPracticeActionPerformed(java.awt.event.ActionEvent evt) {
ButtonsSelected(1);
StartGame Practice=new StartGame(OpcComboBox, numUnity, numTrys,
opcNotas, false);
PracticeBF.dispose();
PracticeMode.setIconImage(Icono);
PracticeMode.setBounds(460, 600, 460, 538);
PracticeMode.setVisible(true);
CirculodeQuintasBW BW=new CirculodeQuintasBW();
PracticeMode.add(BW, BorderLayout.CENTER);
PracticeMode.pack();
PracticeMode.setLocationRelativeTo(null);
PracticeMode.setResizable(false);
}
This is the Image that i want to refresh, it supossed to be another Image before of that, but each time i tried to refresh it doesnt work...
PracticeMode it supossed to be a JDialog, anybody can help me?.
private void D2ActionPerformed(java.awt.event.ActionEvent evt) {
CirculodeQuintasD D=new CirculodeQuintasD();
PracticeMode.add(D, BorderLayout.CENTER);
PracticeMode.validate();
PracticeMode.repaint();
PracticeMode.pack();
}
First of all variable names and method names should NOT start with an upper case character. Learn by example from reading your text book or tutorial and then follow the Java conventions and don't make up your own!
when i press a button, I want that every time I press a button, I update a new image in the same position as the previous one,
Add an JLabel containing an ImageIcon to your panel.
When you want to change the image you just use:
label.setIcon( new ImageIcon(...) );
For example read the section from the Swing tutorial on How to Use Combo Boxes. It does exactly what your want. It uses an ActionListener to change the image of a label. The only different is that the ActionEvent is generated by clicking on an item in the combobox instead of clicking on a button.
Related
We have a project for university which is a program to hold handouts and feedback for courseworks done.
What we've thought of is breaking the whole thing down into smaller pieces, for example:
You have a coursework which requires to write a program and a report on results etc.
So the user will create a new coursework by selecting the "code" and "report" options, since that's what is required. And then we need to create the respective tabs in the program so the user can input what is needed.
I have created all necessary forms and windows, It's just I'm not sure how to move on forward.
a) where should I put my code? should I have it on the "create" event?
b) how do I do this whole custom population thing?
Obviously, I'm not asking for the entire thing in code. I'm not even sure what to read and what to search for.
Following are some screenshots of the ui to help explain what I mean.
New project window
How the main window should be after creating a new projet. Notice the various tabs.
A form for report feedback
On your "Create" button click check for the checkbox.isSelected() and use the method below as:
if(reportCheckbox.isSelected()){
addonScreen(new reportFrame(),"Report Submission");
addonScreen(new reportFeedbackFrame(),"Report Feedback");
}
Use a desktop pane as a container...add your tabbed pane to it
public static JTabbedPane tabbedPane = new JTabbedPane();
jDesktopPane1.add(tabbedPane);
Use this method to add tabs to the layout at runtime
public static void addOnScreen(JInternalFrame inFrame, String title) {
//border for the internal frame
javax.swing.plaf.InternalFrameUI ifu = inFrame.getUI();
((javax.swing.plaf.basic.BasicInternalFrameUI) ifu).setNorthPane(null);
Border b1 = new LineBorder(new Color(114, 139, 173), 3, true) {
};
tabbedPane.setBounds(0, 0, jDesktopPane1.getWidth(), jDesktopPane1.getHeight());
inFrame.setLocation(0, 0);
inFrame.setSize(jDesktopPane1.getWidth(), jDesktopPane1.getHeight());
inFrame.setBorder(b1);
JPanel jp = new JPanel();
jp.setLayout(new GridLayout());
jp.setOpaque(true);
jp.add(inFrame);
tabbedPane.addTab(title, jp);
tabbedPane.setSelectedComponent(jp);
inFrame.requestFocusInWindow();
inFrame.setVisible(true);
tabbedPane.setVisible(true);
}
Hello I am fairly new to java programming and I am currently trying to work on a small game with a GUI, Right now I am stuck at an issue where I can only use a normal button with a card layout, unfortunately I want to use my own icon with the button and to do this I need to use a JButton. but for some reason when i use a JButton it does not get switched with the panels. I'm just wondering what I am doing wrong. I am programming as an applet with a IDE called Ready To Program.
{
CardLayout PanelLayout = new CardLayout ();
JPanel AppPanel = new JPanel (); //Main App Panel using cardlayout
JPanel StartPanel = new JPanel (); //Start Menu Panel
JPanel GamePanel = new JPanel (); //Running Game Panel
JButton StartBtn = new JButton ();
public void init ()
{
StartBtn.setIcon(new ImageIcon ("StartIcon.png"));
StartBtn.setBorder(BorderFactory.createEmptyBorder());
StartBtn.setContentAreaFilled(true);
StartPanel.add (StartBtn);
AppPanel.setLayout (PanelLayout);
AppPanel.add (StartPanel, "1");
AppPanel.add (GamePanel, "2");
PanelLayout.show (AppPanel, "1");
setLayout (new BorderLayout ());
add ("Center", AppPanel);
}
public boolean action (Event e, Object o)
{
if (e.target == StartBtn)
{
PanelLayout.show (AppPanel, "2");
}
return true;
}
}
Frist of all variable names should NOT start with an upper case character. I have never seen a tutorial or answer in any forum that uses an upper case character, so don't make up your own conventions. Learn by example.
I can only use a normal button with a card layout, unfortunately I want to use my own icon with the button and to do this I need to use a JButton.
A JButton is a normal button. What other kind of button are you referring to? It doesn't matter whether the button has text or Icon or both, it is still a button.
The button in your code doesn't work because you didn't add and ActionListener to the button.
Read the section from the Swing tutorial on How to Use Button for more information and examples. The tutorial also has a section on How to Write ActionListeners.
Your code has an action(...) method. I don't know if that is generated by the IDE or not, but basically the code in that method would be the code in your ActionListener.
add ("Center", AppPanel);
That is not the proper form of the method to add a component to a panel. First all don't use hardcoded literal strings, use the variables provided by the API:
add (appPanel, BorderLayout.CENTER);
I want to create this code :
The user enter a numerical value , if he entered character it will throw exception
the field will stop working then another frame show up and display error message
after the user close the new frame , everything return to the way it is
that means the field will work again !
I managed to make the field stop working but I didn't know if the user closed the new frame or not !
here is my try
public void keyReleased(KeyEvent event) {
try{
double l,h,w;
l=Double.parseDouble(input_length.getText());
w=Double.parseDouble("0"+input_width.getText());
h=Double.parseDouble("0"+input_width.getText());
}
catch(NumberFormatException a){
input_length.setEditable(false);
input_height.setEditable(false);
input_width.setEditable(false);
JFrame ErrorFrame = new JFrame("Error");
JPanel content = new JPanel(); ;
ErrorFrame.setContentPane(content);
ErrorFrame.setSize (350, 150);
ErrorFrame.setResizable (false);
ErrorFrame.setLocation (FRAME_X_ORIGIN, 250);
content.setLayout(new FlowLayout());
JLabel text = new JLabel(" ERROR ! please Enter number only ",JLabel.CENTER);
text.setFont(new Font("Arial", Font.PLAIN, 20));
text.setForeground(Color.red);
content.add(text);
ErrorFrame.setVisible(true);
setDefaultCloseOperation(ErrorFrame.EXIT_ON_CLOSE);
int op = ErrorFrame.getDefaultCloseOperation();
if(op == 1 ){
input_length.setEditable(true);
input_height.setEditable(true);
input_width.setEditable(true);}
}
}
1). Do not use new JFrame for error message - use JDialog Here is how
2). h=Double.parseDouble("0"+input_width.getText()); i think that you meant input_height.getText() here, not input_width.getText()
3). After showing your error dialog just clear your text fields - it is ok. When user will close it - he will see them empty.
If you would opt for a modal dialog to show the error message, there is no need to change the editable state of your fields.
Personally as a user I would become quite irritated if a dialog was shown each time I made a typo. For example changing the background color of the text field to red on invalid input, and disabling the OK button (or whatever mechanism you have as user to indicate you are finished editing) is more user-friendly IMO. You can even show a label indicating the errors in your panel, or a tooltip, ... .
I would also recommend a DocumentListener instead of a KeyListener if you want to react on updates of the text in the text field
An example on why I propose to opt for another mechanism to inform the user of the error:
I paste an invalid value in the textfield (e.g. 3x456) and a dialog pops up. Now I want to use my arrow keys to navigate to the error and correct it. This means I have to navigate 3 positions to the left to delete the x. If I use my arrow keys (which are keys as well) I will see this dialog 3 more times during the navigation.
I want to set the text on a JButton that is size 32x32 but it only shows "...". yeah I know you could see the text if you make the button bigger, but how do you make the text be shown on a 32x32 jbutton? The text is only 1 or 2 digits(characters), it is actually a counter. Thanks
The insets are probably crowding out the text...
try
button.setMargin(new Insets(1, 1, 1, 1));
edit: Also, use a smaller font.
edit2: you can also control the insets for all buttons:
UIManager.put("Button.margin", new Insets(1, 1, 1, 1));
I don't think you can, this is managed directly by the look'n'feel' that is used by Java. You could try by changing it to another one to see if there is one with different insets. You could try changing them by setting smaller insects programatically.
A more complex way would be to subclass the JButton class and provide a custom drawing implementation but I think you will lose all the other cool effect.
As per my idea , its quite simple to making GUI application easier.I am writing some code below it may help you .
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frm=new JFrame("Manoj Button Test");
frm.setVisible(true);
frm.setSize(500,500);
Container cnt=frm.getContentPane();
//You can add any text to the JButton
JButton btn=new JButton("Hello Button");
cnt.add(btn);
//2nd type of example
JButton btn2=new JButton();
int number_btntext=4;
btn2.setText(String.valueOf(number_btntext));
cnt.add(btn2);
}
In the above code I have set text to GUI JButton.
how to add and remove components(JButons , JTextField etc) at runtime in a Swing program (Java ) , without using NetBeans ? which Layout should I use ?
I want the user to enter Username & Password and , when he clicks on Submit button , the new screen with new components(JButtons , JTextField etc) should appear , I am unable to achieve the transition at runtime.
You want to use two different panels to achieve this result. It's not a good idea to use the same panel and remove all of the first components and add all of the second ones.
Make a LoginPanel class which lays out the username and password fields, labels, and submit button. Then, when the submit button is pressed, after the login is authenticated, hide the login panel and display a new panel with the layout you want for the next screen.
This sort of approach makes it much easier to maintain the two panels, and clearly separates their layouts and functionality from each other.
You can center this new frame over the existing panel using this code:
public static void centerFrameOverComponent(JFrame frame, JComponent component) {
Window parent = SwingUtilities.getWindowAncestor(component);
Rectangle frameRect = frame.getBounds();
Rectangle parentRect = parent.getBounds();
int x = (int) (parentRect.getCenterX() - frameRect.getWidth() / 2);
int y = (int) (parentRect.getCenterY() - frameRect.getHeight() / 2);
frame.setLocation(x, y);
}
Another approach is to call setVisible(false) on the specific component when you wish to hide it.
In cases where I have wanted to add/remove an entire sub panel, I have used the following:
panel.remove(subPanel);
panel.revalidate();
panel.repaint();
You want to call the last two methods whenever you add/remove components.
One approach would be to use CardLayout. Your login button handler would check the credentials and use show() to reveal the second pane.
Addendum: For security, consider using JPasswordField for the password; for convenience, consdier setLocationRelativeTo() for positioning the frame.
you could create a new class for exsample MyFrame thath extends JFrame, that rapresetns your new windows, in the constructor of that class you have to add at the contentpanel your all contolr....
in this way you can add a jbutton to your JFrame.
class MyFrame extends JFrame{
private JButton jb= new JButton("hello");
public MyFrame(){
setSize(new Dimension(300,180)); //set the MyFrame size
getContentPane().add(jb); //add your Component at ContentPane
}
}
after the login you could show your new frame in this way:
new MyFrame().setVisible(true);