I'm making a java proyect using eclipse and the windowbuilder plugin. After finishing the logic I've created an Application Window and execute the project, everything is fine. But now i want to modify the window, so i change the title for example. In the visual view, i can see these changes, but when i execute the application, there are no changes, it's always the same window. This is the code:
public class Application {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Application window = new Application();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Application() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("My Application");
}
}
I've just added one line so I don't know what could be wrong. I also want to know if this is the best way to make a gui application (using Application Window) or if there are better ways.
EDIT: I add some images to show which is the problem
Window when i execute:
Window in windowbuilder:
You can set title using two ways:
1.Set title using JFrame setTitle() method : frame.setTitle("My Application");
2.Set title using JFrame(String Title) constructor: frame = new JFrame("My Application");
According to my opinion both ways work to set title but still if you are struggling with first option, you can try second option. May be this code works for you.
private void initialize() {
frame = new JFrame("My Application");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
After setting changes, go frame.dispose()
and after that You can
frame.repaint();
frame.revalidate();
Please try this:
try {
Application window = new Application();
window.frame.setVisible(true);
window.frame.setTitle("My Application");
} catch (Exception e) {
e.printStackTrace();
And let me know the result.
Edit:
remove setTitle() from initialize method.
Edit:
If you are beginner you can try JavaFX. It is also simple as Java Swing but has some more potential, better design options and stuff. Its something I have tryed with when I was started Java learning.
I think that you should delete your swing and install it again. Because any solution is not working and there is no other reason not to. Just try to reinstall swing.
Related
Sorry for the very noob question, but I'm having a tremendously difficult time understanding Swing graphics and how to just, well, draw something for goodness sake.
First question is just a snippet question.
When we do this standard code in particular...
public static void main(String[] args) {
Jframe frame= new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new MyCustomJPanel());
frame.setSize(500,500);
frame.setVisible(true);
}
...we set the frame pane as a new JPanel object (of class MyCustomJPanel in this case), but we don't directly name that new MyCustomJPanel object...why don't we name it? And without naming it, how can we possibly ever reference that object again?
Second question...as I mentioned, I've been studying swing graphics now for a bit but I simply can't get my mind wrapped around it. Try as I might, I simply cannot conjure up a way to draw a line at runtime on my JPanel in my JFrame. Is there no way to do this? It seems unless the line is hard-coded at compile time in my JPanel's overridden paint(g) method, runtime addition simply can't be done (without resorting to BufferedDrawings or other more advanced topics)...as there's no way to dynamically throw new code into paint(g).
Thanks, and sorry for the noobness. Trying to (re)learn OOP and Java and having a roaringly difficult time of it.
Can't help all that much without seeing the whole code, but I've heard only bad things about IntelliJ's GUI builder. I use Eclipse's Window builder, but there is also Netbeans. Both are popular for Swing, and there is also JavaFX but that's a whole different story.
For your code, when creating your JFrame class, did you write it like:
public class MainFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setAlwaysOnTop(false);
frame.setMinimumSize(new Dimension(545, 693));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 545, 693);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
//Continue adding components here...
}
Your class extends JFrame, your main method instantiates the frame, and your MainFrame class is where you add your components.
I'm not very good at explaining stuff but hope this helps.
I am used to being able to create an instance of another class by running
Config con = new Config();
con.setVisible(true);
However, this appears not to work with the way the WindowBuilder plugin has set up the gui in Config. When the previous command is run, it creates an empty, tiny JFrame. The main method of Config contains just the following:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Config window = new Config();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
the constructor just calls an initialize method which contains the content creation:
public Config(){
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
//other configuration here
}
How can I call Config from another class to run and be visible?
Alright, found the answer. First, to stop the tiny useless frame from being displayed, do not set visible true from the initial class. Instead just run:
Config con = new Config();
Then, in the constructor of Config, after initializing everything, add
frame.setVisible(true);
ANSWER
After create a new object of that class.
WindowShow ws = new WindowsShow();
ws.frame.setVisible(true);
And it will go perfect
I am building a GUI using internalFrames. I have a menu with different options and I whenever I choose a new option I want it to create that specific frame. However, if that 'option frame' has been created already when I click the option a second time, then I just want that frame to come on top of the other frames (since they are the same size and will lie on top of each other).
This is some of my methods I use:
This method is created when I click a menuOption named: "Home"
protected void createFrameHome()
{
NewFrame frame = new NewFrame();
desktop.add(frame);
try {
frame.setSelected(true);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
This Method is created when I click a menuOption named "Travel"
protected void createFrameTravel()
{
NewFrame frame = new NewFrame();
frame.getContentPane().add(table, BorderLayout.NORTH);
desktop.add(frame);
try {
frame.setSelected(true);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
Frame create:
class NewFrame extends JInternalFrame {
public NewFrame() {
setSize(700, 500);
setVisible(true);
}
}
Now as you can see I create a new frame every time these methods are being called. I have tried different things to get it to work but none seems to work.. I have for example used a variable so it doesn't create a new frame, but then it doesn't do the frame.setSelected(true); part either.
Does anyone know a way around this? Can I somehow select the frame from before maybe?
Solved it by using a variable which was set to true if frame was created
I'm creating a small crypto app for the desktop using java.
I'm using JFrames (import javax.swing.JFrame) with Oracle
JDeveloper 11g under Linux.
I want to have a "welcome" form/frame where users can choose
their encryption method, and then on choosing the method,
I want to dynamically create the appropriate form for the
chosen encryption method and also destroy/free/dispose() of
the welcome form. When the user has finished their encrypting,
they should close the frame/form (either by clicking on the
x at the top right - or using the Exit button or by any
method) and the welcome frame should be dynamically recreated
and appear.
I've tried various things - btnEncode_actionPerformed(ActionEvent e)
then this.dispose() - and I've fiddled with this_windowClosed(WindowEvent e)
and dispose(), but nothing seems to work.
Even a workaround using setVisibl(true/false) would be acceptable at
this stage - this has been wrecking my head all day. It's very
easy to do in Delphi!
TIA and rgs,
Paul...
something like this usually does the trick: (Note I haven't tested this)
public class WelcomeMsg extends JFrame
.
.
.
public void btnContinue_actionPerformed(ActionEvent e)
{
this.dispose();
SwingUtilities.invokeLater(new Runnable(){ new JFrameAppropriateWindow(args) });
}
where btnContinue is the Continue button on your welcome form and JFrameAppropriateWindow is the next frame you would like to show depending on the user's choice. Args are any arguments you need to pass.
When you are ready, you can simply dispose the current frame and relaunch an instance of WelcomeMsg
I put together this simple example for creating and displaying a panel depending on a user choice.
public class Window extends JFrame {
public Window() {
this.setLayout(new BorderLayout());
JComboBox encryptionCombobox = new JComboBox();
encryptionCombobox.addItem("foo");
encryptionCombobox.addItem("bar");
//...
encryptionCombobox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// find choices and the correct panel
JPanel formPanel = new JPanel();
formPanel.setOpaque(true);
formPanel.setBackground(Color.RED);
//...
Window.this.add(formPanel, BorderLayout.CENTER);
Window.this.validate();
Window.this.repaint();
}
});
add(encryptionCombobox, BorderLayout.NORTH);
}
public static void main(String[] args) {
new Window().setVisible(true);
}
}
When I come to think about it, you should probably use a CardLayout instead, which allows you to switch between different panels (cards).
Ok, I have a Java program, that displays some tiles that are SVGs in a FlowLayout. It does this by being a class ScrabbleRack, and extending JPanel, then adding JSVGCanvas tiles to this panel.
Afterwards I created a frame and added the panel, this. (packed it and displayed it). On appearing, the panel does not display properly. It just displays the first tile and then in the space where the rest of the tiles should be displayed, there is whitearea.
But if I resize the frame by any amount, the image will render correctly.
public class ScrabbleRackGUI extends JPanel{
ScrabbleRack rack=new ScrabbleRack();
JSVGCanvas rackContentsImages[]=new JSVGCanvas[8];
public ScrabbleRackGUI() {
setLayout(new FlowLayout());
createComponents();
}
public void createComponents() {
//INITIALISE SOURCE IMAGES
initImages();
for (int i=0;i<rackContentsImages.length;i++){
this.add(rackContentsImages[i]);
}
}
private void initImages(){
File tempImages[]=new File[8];
for(int i=0;i<8;i++){
tempImages[i]= new File("./src/res/rackBackground.svg");
rackContentsImages[i]=new JSVGCanvas();
try {
rackContentsImages[i].setURI(tempImages[i].toURL().toString());
} catch (MalformedURLException ex) {
Logger.getLogger(ScrabbleBoardGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[])
{
JFrame frame = new JFrame("ScrabbleTest");
ScrabbleRackGUI rack= new ScrabbleRackGUI(1);
frame.add(rack);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(214,70);
frame.setVisible(true);
}
}
Any ideas on how I can get this panel to display properly, first time.
Or some hack that will resize it at the end of the program.
I used batik to render the SVGs in Java, for those who want to reproduce this problem.
You problem may be that the construction of your GUI is not being done on the EDT.
Your main should look something like:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyWindow window = new MyWindow();
MyWindow.setVisible(true);
}
});
}
and the rest of your code in your current main should be in the MyWindow constructor.
More detailed information can be found at http://leepoint.net/JavaBasics/gui/gui-commentary/guicom-main-thread.html (among other places)
This might be related to Batik issue 35922 reported here: https://issues.apache.org/bugzilla/show_bug.cgi?id=35922
If I understand that bug report correctly, you can workaround the problem by adding the JSVGCanvas instances (and the ScrabbleRackGUI instance) and calling pack() first, and then set the URIs on each JSVGCanvas.
First of all, you wrote:
ScrabbleRackGUI rack= new ScrabbleRackGUI(1);
and you don't have constructor that takes int.
Secondly, you're setting FlowLayout to JPanel component, and JPanel by default has FlowLayout as layout. better call super(); to get all the benefits of JPanel.
Try to run your application inside of Event Dispatching Thread (EDT), as others mentioned already.
SwingUtilities.invokeLater(new Runnable() {
// your code here
}
Also you should set your URI like this:
setURI(f.toURI().toURL().toString());
because f.toURL() is deprecated.
I hope it helps.