I have to create a Swing applet for a school assignment, and was given a link (http://java.sun.com/docs/books/tutorial/uiswing/components/index.html) to look at various Swing tutorials and use one of them to create a unique Java applet. I chose to follow the code for the How To Use Radio Buttons tutorial. I read through the code and typed it up while changing things so that they would match my pictures. The code I have is
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OSButtons extends JPanel implements ActionListener {
static String windowsString = "Windows";
static String linuxString = "Linux";
static String macString = "Mac";
JLabel picture;
public OSButtons() {
super(new BorderLayout());
JRadioButton windowsButton = new JRadioButton(windowsString);
windowsButton.setMnemonic(KeyEvent.VK_W);
windowsButton.setActionCommand(windowsString);
windowsButton.setSelected(true);
JRadioButton linuxButton = new JRadioButton(linuxString);
linuxButton.setMnemonic(KeyEvent.VK_L);
linuxButton.setActionCommand(linuxString);
JRadioButton macButton = new JRadioButton(macString);
macButton.setMnemonic(KeyEvent.VK_M);
macButton.setActionCommand(macString);
ButtonGroup group = new ButtonGroup();
group.add(windowsButton);
group.add(linuxButton);
group.add(macButton);
windowsButton.addActionListener(this);
linuxButton.addActionListener(this);
macButton.addActionListener(this);
picture = new JLabel(createImageIcon("images/" + windowsString + ".gif"));
picture.setPreferredSize(new Dimension(200, 150));
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(windowsButton);
radioPanel.add(linuxButton);
radioPanel.add(macButton);
add(radioPanel, BorderLayout.LINE_START);
add(picture, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
public void actionPerformed(ActionEvent e) {
picture.setIcon(createImageIcon("images/" + e.getActionCommand() + ".gif"));
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = OSButtons.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("OSButtons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new RadioButtonDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I hope that's readable. Anyways, I compiled the code and it came up with these errors:
I really have no idea how to proceed from here as far as fixing these, this assignment was kind of thrown onto me and I had to research Swing, SWT, and AWT completely on my own. Any help that could be offered would be greatly appreciated.
Change...
picture = newJLabel(createImageIcon("images/"+ windowsString + ".gif"));
to...
picture = new JLabel(createImageIcon("images/"+ windowsString + ".gif"));
Change
radiopanel.add(macButton);
to...
radioPanel.add(macButton);
Java is case sensitve, variable names case must match
This...
JComponent newContentPane = new RadioButtonDemo();
I suspect is a copy/paste error. You change the class name of the original code, but forgot to change any references to it.
Try...
JComponent newContentPane = new OSButtons();
Instead
Update
Okay. Let's assume that you have your source files in C:\Users\Keith\Desktop\components.
At the command prompt your would compile them by using something like...
C:\> cd C:\Users\Keith\Desktop
C:\Users\Keith\Desktop> javac components.OSButtons.java
C:\Users\Keith\Desktop> java components.OSButtons
There is a direct coalition between the package name and the expected directory of the class files.
Related
I have a probably easy to solve problem. I used Intellij Idea to build a GUI form. Now I am trying to change the imageIcon of the imageLabel JLabel.
I don't really understand why but when I use the JLabel.setIcon() it neither throws an exception nor displays the image. I have no idea what is wrong with it. It seems like a very simple command.
( I added ico.getImage().flush(); line because when I was searching around people said you have to flush the image before displaying it. I don't actually know what that line does.)
Thanks for any help.
public class App
{
private JPanel mainPanel;
private JPanel imagePanel;
private JPanel optionsPanel;
private JPanel palletesPanel;
private JPanel buttonsPanel;
private JPanel originalPalletePanel;
private JPanel newPalletePanel;
private JLabel originalPalleteLabel;
private JLabel newPalleteLabel;
private JPanel leftButtonsPanel;
private JPanel rightButtonsPanel;
private JButton previewButton;
private JButton revertButton;
private JButton convertImageButton;
private JButton matchPalleteButton;
private JLabel originalPalleteImageLabel;
private JLabel newPalleteImageLabel;
private JLabel imageLabel;
public static void main(String[] args)
{
App app = new App();
JFrame frame = new JFrame("Pixel Pigeon");
frame.setContentPane(new App().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
pigeon pigey = new pigeon();
try
{
app.loadImage(frame, app);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
private void loadImage(JFrame frame, App app) throws IOException
{
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION)
{
BufferedImage img = ImageIO.read(chooser.getSelectedFile());
ImageIcon ico = new ImageIcon(img);
ico.getImage().flush();
app.imageLabel.setIcon(ico);
}
}
}
There were a lot of problems with that short section of code. After removing the many redundant components, the reference to a class not in evidence, fixing the two instances of NullPointerException, removing the call to flush the image, and fixing the problem with the new creation of an App() that already existed, it 'works'. But it is still so bad I'd recommend tossing the lot out and starting again with reference to the JavaDocs for investigating things random people recommend, and the Java Tutorial for the basics of GUI development.
So here is the 'fixed' code: It will load an image, but the GUI then needs to be stretched to make the image visible.
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.ImageIO;
public class App {
private JPanel mainPanel = new JPanel();
private JLabel imageLabel = new JLabel();
public static void main(String[] args) {
App app = new App();
JFrame frame = new JFrame("Pixel Pigeon");
app.mainPanel.add(app.imageLabel);
frame.setContentPane(app.mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
try {
app.loadImage(frame, app);
}
catch(java.io.IOException e) {
e.printStackTrace();
}
}
private void loadImage(JFrame frame, App app) throws IOException {
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
BufferedImage img = ImageIO.read(chooser.getSelectedFile());
ImageIcon ico = new ImageIcon(img);
app.imageLabel.setIcon(ico);
}
}
}
I'm trying to add an image to a JFrame and set its location, I don't know why it just does not add into it, maybe I don't understand how the JFrame class works since a normal text JLabel adds into the JFrame simply without any trouble and a JLabel containing an image simply does not add in.
I would appreciate if someone would explain the error in the code, and maybe even give me a short explanation of why my way does not work. Thanks!
import java.awt.*;
import javax.swing.*;
public class Walk {
public static void main(String[] args) {
JFrame f = new JFrame("Study");
f.setSize(3000,1000);
f.getContentPane().setBackground(Color.white);
f.getContentPane().add(new JLabel("test", JLabel.CENTER) );
JLabel l = new JLabel(new ImageIcon("C:\\Users\\leguy\\OneDrive\\Desktop\\Stuff\\stillsp"));
l.setBounds(100, 100, 100, 100);
l.setVisible(true);
f.add(l);
f.setVisible(true);
}
}
are you using a gui class or you are writing its code into a main class
what is in your code is that you are writing its code so easy way is to just drag and drop try this link for normal jframes gui eclipse gui
about the picture into jframe is easy one all what you have to do is
1. create a label by setting its size as you want on the jframe by dragging and dropping only
2. follow the pictures
then you browser for your picture you want
select the picture and its done
Hope it helps
Make sure the path to your image is valid. All I did was point to a valid image on my PC and the code practically worked. There were a few things added and organized below.
import java.awt.Color;
import javax.swing.*;
public class Walk {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { // Safety first...
#Override
public void run() {
String path = "C:\\Path\\To\\Image.png"; // Make sure it's correct
JFrame frame = new JFrame("Study");
JLabel label = new JLabel(new ImageIcon(path));
frame.setSize(3000, 1000);
frame.getContentPane().setBackground(Color.white);
frame.getContentPane().add(new JLabel("test", JLabel.CENTER));
label.setBounds(100, 100, 100, 100);
label.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
frame.pack(); // Pack the frame's components.
frame.setVisible(true);
}
});
}
}
To make sure both labels show up, provide a layout and add them accordingly.
import java.awt.*;
import javax.swing.*;
public class Walk {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
String path = "C:\\Path\\To\\Image.png"; // Make sure it's correct
JFrame frame = new JFrame("Study");
Container container = frame.getContentPane();
JLabel imageLbl = new JLabel(new ImageIcon(path));
JLabel textLbl = new JLabel("test");
frame.setLayout(new BorderLayout());
frame.setSize(3000, 1000);
imageLbl.setBounds(100, 100, 100, 100);
imageLbl.setVisible(true);
container.setBackground(Color.WHITE);
container.add(textLbl, BorderLayout.NORTH);
container.add(imageLbl, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
I have a text game which has buttons. When a button is clicked, text appears. My text appears inside a jPanel, which is inside a jScrollPane. I would like my jPanel to automatically make more vertical space for my lines of text to be added. I have been doing it by hand but it is a lot more time consuming. Is there anyway to do this, or maybe pack a jPanel somehow. I am pretty new to this so if any extra information is needed for you to help me out feel free to ask. Thanks.
I would use a component that can do this automatically -- a JTextArea. It will automatically enlarge as more text is added.
If you need more specific help or a code example, please post your own small compilable and runnable test example program, and I can try to modify it.
You state:
I don't want to use a JTextArea because I don't want the user to be able to highlight or delete any of the text that was there in the first place.
No problem. Just make the JTextArea non-focusable and non-editable.
I have been using jLabels which are equal to "" and when a button is pressed, that jLabel is given a new value.
Try something like this:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class AddNewLines extends JPanel {
private JTextArea textArea = new JTextArea(10, 15);
private JButton addLineBtn = new JButton(new AddLineAction("Add Line", KeyEvent.VK_A));
public AddNewLines() {
textArea.setEditable(false);
textArea.setFocusable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setOpaque(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollPane);
add(addLineBtn);
}
class AddLineAction extends AbstractAction {
private int count = 0;
public AddLineAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (count != 0) {
textArea.append("\n");
}
textArea.append("Line of Text: " + count);
count++;
}
}
private static void createAndShowGui() {
AddNewLines mainPanel = new AddNewLines();
JFrame frame = new JFrame("Add New Lines");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
So Im trying to create 3 panels. The first panel has the layout set (e.g. the radio buttons and next button) I`m now adding two new panels which have different background colors. But when I execute the code I get an error of Null point exception. How do I fix that?
Here is the code:
import java.awt.Color;import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.CardLayout;
import javax.swing.*;
public class Wizard {
private JLabel lblPicture;
private JRadioButton btLdap, btKerbegos, btSpnego, btSaml2;
private JButton btNext;
private JPanel panel;
private JPanel panelFirst;
private JPanel panelSecond;
CardLayout c1 = new CardLayout();
public static void main(String[] args) {
new Wizard();
}
public Wizard() {
JFrame frame = new JFrame("Wizard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,360);
frame.setVisible(true);
MyPanel();
RadioButtons();
Button();
Image();
groupButton();
panel.setLayout(c1);
panelFirst.setBackground(Color.BLUE);
panelSecond.setBackground(Color.GREEN);
panel.add(panelFirst,"1");
panel.add(panelSecond,"2");
c1.show(panel,"panel");
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public void MyPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void RadioButtons() {
btLdap = new JRadioButton ("Ldap");
btLdap.setBounds(60,85,100,20);
panel.add(btLdap);
btKerbegos = new JRadioButton ("Kerbegos");
btKerbegos.setBounds(60,115,100,20);
panel.add(btKerbegos);
btSpnego =new JRadioButton("Spnego");
btSpnego.setBounds(60,145,100,20);
panel.add(btSpnego);
btSaml2 = new JRadioButton("Saml2");
btSaml2.setBounds(60,175,100,20);
panel.add(btSaml2);
}
public void Button() {
btNext = new JButton ("Next");
btNext.setBounds(400,260,100,20);
panel.add(btNext);
btNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
c1.show(panel, "2");
}
});
}
public void Image() {
ImageIcon image = new ImageIcon("image.jpg");
lblPicture = new JLabel(image);
lblPicture.setBounds(200,20, 330, 270);
panel.add(lblPicture);
}
private void groupButton() {
ButtonGroup bg1 = new ButtonGroup( );
bg1.add(btLdap);
bg1.add(btKerbegos);
bg1.add(btSpnego);
bg1.add(btSaml2);
}
}
When I go to run your code I get the null pointer exception you mentioned:
Exception in thread "main" java.lang.NullPointerException
at Wizard.<init>(Wizard.java:35)
at Wizard.main(Wizard.java:20)
So, I looked up the line that produced it, in the constructor for Wizard:
panelFirst.setBackground(Color.BLUE);
I see you are setting a property on panelFirst, which is an instance data member of the Wizard class.
I don't see anywhere where you declared panelFirst = new JPanel();, which is what created your NullPointerException. It also looks like you haven't initialized many of the other variables as well (for instance, panel is the only JPanel I see that has been initialized).
Please look up the constructors for JPanel in the Java API and see how you want to create them for your app. You may also consider using an IDE to generate the GUI code for you.
JPanel API (as of jdk 1.7): http://docs.oracle.com/javase/7/docs/api/javax/swing/JPanel.html
Thanks
panelFirst and panelSecond objects are never created.
panelFirst and panelSecond variable is null it is not declared.
before setting background of panel you need to create it:
panelFirst= new JPanel();
same thing with panelSecond:
panelSecond = new JPanel();
When you have a null pointer exception (also known as NPE): you should try to find an uninitialized variable. When a variable is declared but not initialized its pointer is pointing to null (i.e it is a null pointer!)
I have this method to print and set the material properties of a Solid Object in a class called MaterialProperties, which has printMaterial & setMaterial methods.
public void Btn3_callback ( ) throws Exception {
Model model = session.GetCurrentModel();
if (model == null) {
mesg = "No Model Selected!!";
//TextField.Area("No Model Selected!!");
System.exit(0);
}
else {
Solid solid= (Solid) model;
String newMaterial="copper";//user input for new Material name
printMaterial(solid);//printMaterial print the Material properties of the Solid object
setMaterial(solid,newMaterial);//setMaterial sets the Material properties of the Solid object to the material entered
}
}
I need to get the user input for newMaterial instead of hard coding it. What I need to do is to display all the Material types avaialable, so that the user can just select the material required. So I tried to do this using JFrame. Here's the code I have:
public class MaterialWindow {
JFrame frame = new JFrame("Material Selection");
public MaterialWindow(){
// Directory path here
String path = "W:\\materials";
JFrame frame = new JFrame("Material Selection");
JPanel panel = new JPanel(new GridLayout(0, 4));
ButtonGroup bg = new ButtonGroup();
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
JRadioButton button;
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".mtl") || files.endsWith(".MTL"))
{
button = new JRadioButton(files);
panel.add(first,BorderLayout.CENTER);
panel.revalidate();
bg.add(button);
first.addActionListener(new MyAction());
}
}
}
frame.add(panel, BorderLayout.NORTH);
frame.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
frame.setSize(1000, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
String newMaterial =e.getActionCommand();
String[] split = newMaterial.split("\\.");
newMaterial = split[0];
newMaterial.trim();
//set the newMaterial for btn3_callback OR call the setMaterial method of MaterialPropeties class
frame.dispose();
}
}
}
Now the problem is how can I use the newMaterial string selected from the radio button to newMaterial in my Btn3_callback() function? When I create a getString() method for newMaterial in the class MyAction and use that it Btn3_callback it always returns null;
Is there any way I can do this? Or any different way I can implement the idea?
Thanks
Use a JOptionPane instead of the frame. Put a list (JList ..or JComboBox) of options in the option pane and query the component once returned (the pane is closed), for the selected object.
E.G. using JComboBox
The GUI should be created and altered on the EDT (batteries not included).
import java.io.File;
import javax.swing.*;
public class QuickTest {
public static void main(String[] args) throws Exception {
File[] files = new File(System.getProperty("user.home")).listFiles();
JFrame f = new JFrame("Faux J-Link");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JEditorPane jep = new JEditorPane();
f.add(new JScrollPane(jep));
f.setSize(600,400);
f.setLocationByPlatform(true);
f.setVisible(true);
JComboBox choices = new JComboBox(files);
int result = JOptionPane.showConfirmDialog(f, choices);
if (result==JOptionPane.OK_OPTION) {
System.out.println("OK");
File file = files[choices.getSelectedIndex()];
jep.setPage(file.toURI().toURL());
}
}
}