I'm just getting into GUI programming, slowly learning.
However I'm having a problem right of the bat. I can't get the Fore/Background color to change in my window at all.
However when I add a label via JLabel and then use setFore/Back, they change colors just fine. Just not the whole window.
I thought .setForeground and .setBackground are supposed to change the color of the window?
import javax.swing.*;
import java.awt.*;
public class MyWindow {
public static void main(String args[])
{
Runnable init = new Runnable()
{
public void run()
{
JFrame myWindow = new JFrame("Hola!");
myWindow.setForeground(Color.YELLOW);
myWindow.setBackground(Color.YELLOW);
myWindow.setSize(400, 300);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setLayout(null);
myWindow.setVisible(true);
}
};
SwingUtilities.invokeLater(init);
}
}
First of all, do not use a null layout. Let the layout manager do its job. Second of all, you need to set the background of the content pane of the JFrame instance, as such
myWindow.getContentPane().setBackground(Color.YELLOW);
See also:
Using Top-Level Containers
you cannot color a frame. However you can color the ContentPane inside.
import javax.swing.*;
import java.awt.*;
public class MyWindow {
public static void main(String args[])
{
Runnable init = new Runnable()
{
public void run()
{
JFrame myWindow = new JFrame("Hola!");
myWindow.getContentPane().setBackground(Color.YELLOW);
myWindow.setSize(400, 300);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setLayout(null);
myWindow.setVisible(true);
}
};
SwingUtilities.invokeLater(init);
}
}
this should fix your problem...
tangina naman ang bobo naman neto, pokegooo
import javax.swing.;
import java.awt.;
public class MyWindow {
public static void main(String args[])
{
Runnable init = new Runnable()
{
public void run()
{
JFrame myWindow = new JFrame("Hola!");
myWindow.getContentPane().setBackground(Color.YELLOW);
myWindow.setSize(400, 300);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setLayout(null);
myWindow.setVisible(true);
}
};
SwingUtilities.invokeLater(init);
}
}
// tanga amputa aral ka muna dudong
// pakangkang
Related
Does anyone know why my image is not loading? I tried many things and so far nothing, first of all the folder "IMGFiles" is already like Source Folder.
package Main;
import javax.swing.*;
public class Menu extends JFrame {
public Menu()
{
ImageIcon imagem = new ImageIcon(Menu.class.getResource("/LiturgisGame/IMGFiles/LiturrgisLogoLoad.png"));
JLabel logo = new JLabel();
logo.setIcon(imagem);
}
public static void main(String[] args) {
//new Menu();
JFrame janela = new JFrame();
janela.setSize(816, 419);
janela.setUndecorated(true);
janela.setVisible(true);
janela.setLocationRelativeTo(null);
}
}
I'm assuming you are using UNIX (for the shape of the path you are using).
Here is an approach for you:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import com.apple.eawt.Application;
public class Menu extends JFrame {
public Menu(){ }
public static void main(String[] args) {
Application.getApplication().setDockIconImage(new ImageIcon("/LiturgisGame/IMGFiles/LiturrgisLogoLoad.png").getImage());
//new Menu();
JFrame janela = new JFrame();
janela.setSize(816, 419);
janela.setUndecorated(true);
janela.setVisible(true);
janela.setLocationRelativeTo(null);
}
}
Output:
This happens because you prepare the JLabel inside Menu constructor and you do not initiate any instance of Menu class. Also, you do not add the JLabel into the frame (content pane).
Check this sample:
public class Menu extends JFrame {
public Menu()
{
ImageIcon imagem = new ImageIcon(Menu.class.getResource("/LiturgisGame/IMGFiles/LiturrgisLogoLoad.png"));
JLabel logo = new JLabel();
logo.setIcon(imagem);
setSize(816, 419);
setUndecorated(true);
setLocationRelativeTo(null);
getContentPane().add(logo); //Add the label to the content pane
}
public static void main(String[] args) {
SwingUtilities.invokeLater(()->{
new Menu().setVisible(true);
});
}
}
I have written a Java XML Parser as an Applet. It is looking and functioning well enough in this form.
My Question, Is if I want to run this without a browser, how Would I properly wrap it to run as an executable?
GUI.java
--------------
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GUI extends JPanel implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private Parser xmlEditor;
private String startTimeValue;
private String endTimeValue;
public GUI(){
init();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new GUI();
}
});
}
public void init() {
this.setXmlEditor(new Parser("C:\\Users\\Administrator\\workspace\\XMLParser\\src\\test.xml"));
add(new Label("Start Time"));
startTimeValue = xmlEditor.getStartTimeValue();
endTimeValue = xmlEditor.getEndTimeValue();
startTime = new TextField(startTimeValue);
add(new Label("End Time"));
endTime = new TextField(endTimeValue);
save = new Button("save");
save.addActionListener(this);
add(startTime);
add(endTime);
add(save);
}
public void actionPerformed(ActionEvent e)
{
System.out.println(endTime.getText());
xmlEditor.updateStartTimeValue(startTime.getText());
xmlEditor.updateEndTimeValue(endTime.getText());
System.out.println(e);
System.exit(0);
}
public Parser getXmlEditor() {
return xmlEditor;
}
public void setXmlEditor(Parser xmlEditor) {
this.xmlEditor = xmlEditor;
}
TextField startTime, endTime;
Button save;
}
While trying things with Swing and JFRame etc, I am not getting properly layout, or am opening multiple windows. Can anyone provide assistance? The second Panel Keeps replacing the First. Id like to really try to learn how to place multiple components inside an executable jar is the goal.
SwingPaintDemo.java
import java.awt.Label;
import java.awt.TextField;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
public class SwingPaintDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
Parser myParser = new Parser("C:\\Users\\Administrator\\workspace\\XMLParser\\src\\test.xml");
JPanel top = new JPanel();
top.add(new Label("Start Time"));
TextField startTimeField = new TextField(myParser.getStartTimeValue());
top.add(startTimeField);
f.getContentPane().add(top);
JPanel bottom = new JPanel();
bottom.add(new Label("End Time"));
TextField endTimeField = new TextField(myParser.getEndTimeValue());
bottom.add(endTimeField);
f.getContentPane().add(bottom);
f.pack();
}
}
JFrame uses a BorderLayout by default, where as a JPanel uses a FlowLayout
Instead of rebuilding the UI in the JFrame, simply add an instance of GUI to it, since you've already defined the functionality in a JPanel, this makes it easily reusable.
public class SwingPaintDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new GUI());
f.pack();
f.setVisible(true);
}
}
FYI: You should never reference src in any path element, src won't exist once the program is built and packaged. This is also doubly concerning for applets, as applets run in a tight security model, which prevents them from accessing the file system by default.
Instead, you should be using Class#getResource or Class#getResourceAsStream, depending on your needs.
this.setXmlEditor(new Parser(getClass().getResource("/test.xml")));
for example. You may need to change your Parser to accept either a URL and/or InputStream as well
What is the correct way of disposing a frame which is created inside a Runnable object?
The code below returns a null pointer exception when the endDialog is called before the LoadingRunnable has completed its constructor.
How can the endDialog be executed after the constructor has finished?
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LoadingRunnable implements Runnable
{
private JFrame jFrame;
#Override
public void run()
{
jFrame = new JFrame("Window");
JPanel jPanel = new JPanel();
JLabel label = new JLabel("Loading...");
jPanel.add(label);
jFrame.setContentPane(jPanel);
jFrame.pack();
jFrame.setVisible(true);
}
public void endDialog()
{
jFrame.setVisible(false);
jFrame.dispose();
}
public static void main(String args[])
{
LoadingRunnable l = new LoadingRunnable();
SwingUtilities.invokeLater(l);
//work done here
l.endDialog();
}
};
You have a concurrency problem here because SwingUtilities.invokeLater() schedules your runnable class execution in the Event Dispatch Thread asynchronously while your main thread's flow still running, causing a NPE.
The correct way to dispose a frame is through events, just as Swing is designed to be used. For instance by clicking the "X" (close) button or by dispatching a WindowEvent:
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
You may want to take a look to this question too: Optional way to close a dialog window
In addition
If you just want to show something during your application start up, then you can use SplashScreen API instead of JFrame. See How to Create a Splash Screen for further details.
Based on your previous question and this new one, I'd suggest you read the whole Concurrency in Swing tutorial to understand about common concurrency problems in Swing and how to deal with them.
Ok found how:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Loading
{
private JFrame jFrame;
public void startDialog()
{
jFrame = new JFrame("Window");
JPanel jPanel = new JPanel();
JLabel label = new JLabel("Loading...");
jPanel.add(label);
jFrame.setContentPane(jPanel);
jFrame.pack();
jFrame.setVisible(true);
}
public void endDialog()
{
jFrame.setVisible(false);
jFrame.dispose();
}
public static void main(String args[])
{
final Loading l = new Loading();
for (int i = 0; i < 200; i++)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
l.startDialog();
}
});
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
l.endDialog();
}
});
}
}
};
I'm trying to update the main gui in a java swing application, so there is a runnable thread that keeps the main gui visible, but the problem is it is called in main, and main is a static function. I would like to say Element.SetTtext. But all calls that I want to update are not static. How can I update the lables,..etc in the Main GUI then?
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
new AGC().setVisible(true);
// code to update labels here
}
});
}
What I understood from your question is that you think static means non-changeable. This is not true with Java. In Java objects and components that never change are characterized as final.
Keep your main simple and small and make your loops and changes in doThings();
Here is a Timer in order to update the text of the JLabel:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Foo extends JFrame {
public Foo() {
jLabel1 = new JLabel("label 1");
jPanel1 = new JPanel();
jPanel1.add(jLabel1);
add(jPanel1);
pack();
// code to update whatever you like here
doThings();
}
private void doThings() {
// code to update whatever you like here
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
jLabel1.setText("foo " + (j++));
}
};
Timer timer = new Timer(500, actionListener);
timer.start();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Foo().setVisible(true);
}
});
}
private JLabel jLabel1;
private JPanel jPanel1;
private int j = 0;
}
little more clarity is required , when do u want to update the labels ? is it based on an event ?
You can always keep a global variable of the component you want to update and access it from the event handlers.
Can you please update your question with the code , so that it gives a better clarity ?
I am creating a colour chooser and need to modify one of the colour chooser panels.
What I wanted was, I want to enter input values via the RGB fields to set the colour,The problem is the RGB values seem to be disabled is there a method within the api to turn on the RGB inputs to take a value?
Seems fine here.
import javax.swing.*;
class ColorChooserTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new JColorChooser());
}
});
}
}
Is there anyway you can combine the RGB slider panel and the HSB panel?
Yes, apparently it is possible. Check this (very fragile, poorly laid out) example.
import java.awt.*;
import javax.swing.*;
import javax.swing.colorchooser.*;
import javax.swing.border.*;
class ColorChooserTest2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JColorChooser cc = new JColorChooser();
AbstractColorChooserPanel[] panels = cc.getChooserPanels();
JPanel p = new JPanel();
panels[1].setBorder(
new TitledBorder(panels[1].getDisplayName()));
p.add(panels[1]);
panels[2].setBorder(
new TitledBorder(panels[2].getDisplayName()));
p.add(panels[2]);
JPanel gui = new JPanel(new BorderLayout(2,2));
gui.add(p, BorderLayout.CENTER);
gui.add(cc.getPreviewPanel(), BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
});
}
}