What's the problem? Non-static variable data cannot be referenced from a static context. I would like to load data from .dat file, but I don't know how can I do it? I tried it but it doesn't work because of the previous error message. Thank you for the helping.
public class StudentFrame extends JFrame {
private StudentData data;
private static String[] columnNames = {"A","B","C","D"};
private void initComponents() {
this.setLayout(new BorderLayout());
}
#SuppressWarnings("unchecked")
public StudentFrame() {
super("Hallgatói nyilvántartás");
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
data = new StudentData();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.dat"));
data.students = (List<Student>)ois.readObject();
ois.close();
} catch(Exception ex) {
ex.printStackTrace();
}
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students.dat"));
oos.writeObject(data.students);
oos.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
});
setMinimumSize(new Dimension(500, 200));
initComponents();
}
public static void main(String[] args) {
StudentFrame sf = new StudentFrame();
sf.setVisible(true);
sf.setLayout(new BorderLayout());
JTable table = new JTable(data,columnNames);//PROBLEM
table.setFillsViewportHeight(true);
/*Jscroll...*/
scrollPane.setViewportView(table);
sf.add(table.getTableHeader(), BorderLayout.PAGE_START);
sf.add(table, BorderLayout.CENTER);
sf.add(scrollPane, BorderLayout.LINE_END);
sf.setVisible(true);
}
}
Suggest restructuring your code and moving the contents of the main method into your StudentFrame class. There is no real reason to use static variables, make TableData a member variable of StudentFrame. Only instantiate StudentFrame from main method, set up the frame and display it. how the contents are displayed should be part of the StudentFrame class.
columnNames is fine as a static, as its a constant.
Your StudentFrame private member variables need public accessors and then you would reference them in main as JTable table = new JTable(sf.getData(), StudentFrame.getColumnNames());
Related
I want to transfer content from a text file into a JTextarea. I suppose my code just needs small adjustments but even through research. I am not able to find out, what is wrong. So far it is just displaying an empty JFrame instead of the text of the file.
this.setSize(this.width, this.height);
this.setVisible(true);
this.jScrollPane = new JScrollPane(this.jTextArea);
this.jPanel = new JPanel();
this.jPanel.setOpaque(true);
this.jTextArea.setVisible(true);
try {
this.jTextArea = new JTextArea();
this.jTextArea.read(new InputStreamReader(
getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")),
null);
} // catch
this.add(this.jScrollPane);
And the usage:
public static void main(String[] args) {
new TextFrame(new File("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name"), 500, 500);
}
You have 2 important issues in this code:
You are creating jScrollPane this.jScrollPane = new JScrollPane(this.jTextArea); before reading the file content using jTextArea
The method does not work read(new InputStreamReader(
getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")), null); Use the one in the following example.
You have to catch the exception to solve the problems
public class TextAreaDemo extends JFrame {
private JScrollPane jScrollPane;
private JTextArea jTextArea ;
private static final String FILE_PATH="/Users/user/IdeaProjects/StackOverflowIssues/file.txt";
public TextAreaDemo() {
try {
jTextArea = new JTextArea(24, 31);
jTextArea.read(new BufferedReader(new FileReader(FILE_PATH)), null);
} catch (Exception e){
e.printStackTrace();
}
jScrollPane = new JScrollPane(this.jTextArea);
this.add(this.jScrollPane);
this.setVisible(true);
this.setSize(400, 200);
}
public static void main(String[] args) {
TextAreaDemo textAreaDemo = new TextAreaDemo();
}
So if someone would take a look at the code below and give me hand I would owe you my life. So here's the issue, obviously I can get this to work if I were to put playerCreationSelectionin its own class, my questions is getting it to work, inside class superClass I cannot for the life of me move things around to make it work. Any help would be great, thanks everyone!
forgot to actually put what goes wrong! So what will happen is it says playerCreationSelection is not a symbol
public class superClass
{
public static void main(String[] args)
{
playerCreationSeletion gui = new playerCreationSeletion();
}
public class playerCreateSelection extends JFrame implements ActionListener
{
//create label
public JLabel playerCreatedLabel;
public void playerCreationSeletion()
{
setSize(WIDTH,HEIGHT);
WindowDestroyer listener = new WindowDestroyer();
addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setLayout(new FlowLayout());
//create button
JButton playerCreationButton = new JButton("Create New Player");
playerCreationButton.addActionListener(this);
contentPane.add(playerCreationButton);
//create label
playerCreatedLabel = new JLabel("Welcome New Player!");
playerCreatedLabel.setVisible(false);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
Container contentPane = getContentPane();
if(actionCommand.equals("Create New Player"))
{
contentPane.setBackground(Color.LIGHT_GRAY);
playerCreatedLabel.setVisible(true);
}
}
}
}
Well, you have a typo "playerCreationSeletion()". Also, You need to call an inner class constructor like this and use setVisible and setSize.
public static void main(String[] args) {
playerCreateSelection gui = new superClass().new playerCreateSelection();
gui.setSize(500, 500);
gui.setVisible(true);
}
Try that.
I'm writing an application where I need to get two String objects from the GUI to the nullObject class.
I'm relatively new to programming, and am trying my best to learn. If you have any tips on how to make this better, I'd be really thankful!
My GUI class:
package com.giuly.jsoncreate;
public class GUI {
private JFrame startFrame;
private JFrame chkFrame;
private JFrame osFrame;
private JFrame appVFrame;
private JPanel controlPanel;
private JButton nextPage;
private JButton cancel;
private JButton save;
public GUI() {
generateGUI();
}
public static void main(String[]args) {
GUI gui = new GUI();
}
public void generateGUI() {
//Creation of the First Frame
startFrame = new JFrame("JSCON Creator");
startFrame.setSize(1000, 700);
startFrame.setLayout(new FlowLayout());
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Panel Creation
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//Button Creation
cancel = new JButton("Cancel");
cancel.setSize(100, 100);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
nextPage = new JButton("Next");
nextPage.setSize(100, 100);
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFrame.setVisible(false);
showText();
}
});
startFrame.add(controlPanel);
startFrame.add(cancel);
startFrame.add(nextPage);
startFrame.setVisible(true);
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void showText() {
JFrame textFrame = new JFrame();
textFrame.setSize(1000, 700);
textFrame.setTitle("Text");
textFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel textPanel = new JPanel();
JLabel titleLabel = new JLabel("Title");
textPanel.add(titleLabel);
JLabel descrLabel = new JLabel("Description");
JTextField tfTitle = new JTextField("",15);
tfTitle.setForeground(Color.BLACK);
tfTitle.setBackground(Color.WHITE);
JTextField tfDescr = new JTextField("",30);
tfDescr.setForeground(Color.BLACK);
tfDescr.setBackground(Color.WHITE);
textPanel.add(tfTitle);
textPanel.add(descrLabel);
textPanel.add(tfDescr);
JButton buttonOK = new JButton("OK");
textPanel.add(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jsonTitle = tfTitle.getText();
String jsonDescr = tfDescr.getText();
System.exit(0);
}
});
textFrame.add(textPanel);
textFrame.setVisible(true);
}
I want to get the Strings jsonTitle and jsonDescr into another class, so I can store them. In the end I will have some Strings and I need to save them in a JSON file. I need a way to get those two Strings, what advice do you guys have?
Erick is correct with his answer. Just thought I should add additional info. If you declare jstonTitle and jsonDescr like your other fields using private you still will not be able to access these fields from another class. Coding up a getter for the fields along with declaring them at the top of GUI should solve your problem. Then just create an instance of GUI in your other class and call the method.
public String getJsonTitle(){
return this.jsonTitle;
}
You're declaring jstonTitle and jsonDescr inside the actionPerformed() method. That means that as soon as actionPerformed() exits you'll lose those variables. You need to declare them in an enclosing context. For example, you could make them fields on the GUI class. Still assign them in actionPerformed(), but declare them up at the top of GUI where you're declaring startFrame, chkFrame, etc.
That will give you the ability to access those values from anywhere within GUI.
Oh, BTW, get rid of System.exit(0);. (Have you actually tried to run your program?)
I'm new to Java GUI, and am having issues displaying an image. My intention is to display a large image and allow the user to click on regions of the image to indicate where certain features are located. Anyway, I'm getting a rough start because I can't even get the image to appear, despite reading Oracle's explanation and other solutions.
I've created a JFrame and used its setContentPane() method to add a JPanel and JLabel. I use the setIcon() method of the JLabel to add an image to it, or at least that's my intention...
Any advice is appreciated, especially if there's a better way of doing this. I'll be using OpenCV to process images, and plan to convert them to Java image (or BufferedImage) before displaying them.
Here is the code. I left out the libraries to save space.
public class Pathology {
public static void main(String[] args) {
PrimaryFrame primaryFrame = new PrimaryFrame();
primaryFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
primaryFrame.setSize(1500, 900);
primaryFrame.setVisible( true );
primaryFrame.setContentPane(primaryFrame.getGui());
try {
primaryFrame.setImage(ImageIO.read(new File("C:\\Users\\Benjamin\\Pictures\\Pathology\\C\\001.png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GUI Class:
public class PrimaryFrame extends JFrame{
//private JTextField textField1;
JPanel gui;
JLabel imageCanvas;
public PrimaryFrame() {
super( "Pathology-1" );
//setLayout(new FlowLayout());
//textField1 = new JTextField("Chup!", 50);
//add(textField1);
}
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui==null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5,5,5,5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300,100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
}
Would you laugh at me if I'd tell you that you just have to put the primaryFrame.setVisible( true ); to the end of the main method? :)
For furture understanding, you don't have to call frame.setVisible(true) every time you want to add/update something in the frame (in an ActionListener, for example). Instead you can call frame.revalidate() and frame.repaint(). (Where frame can be replaced with the particular panel)
You need to setVisible(true) after the call to setImage():
primaryFrame.setImage(ImageIO.read(new
File("C:\\Users\\Benjamin\\Pictures\\Pathology\\C\\001.png")));
because any update to the GUI after setVisible() will not be shown.
That's it and the code should be like this:
public class Pathology {
public static void main(String[] args) {
PrimaryFrame primaryFrame = new PrimaryFrame();
primaryFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
primaryFrame.setSize(1500, 900);
primaryFrame.setContentPane(primaryFrame.getGui());
try {
primaryFrame.setImage(ImageIO.read(new File(
"C:\\Users\\Benjamin\\Pictures\\Pathology\\C\\001.png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
primaryFrame.setVisible( true );
}
}
I have the following class that draws a Label. (I have only given part of the code here). Everyhting works fine, the label gets displayed.
Now, i have another class called Caller Class. I have a method in that where i will use to change the value of this label. how can i do that
public class MyClass{
private JLabel label;
MyClass(){
run();
}
public void editTheLabelsValue (String text) {
label.setText(text);
frame.repaint();
}
run(){
.... // there were more code here, i removed it as it's not relevant to the problem
label = new JLabel("Whooo");
label.setBounds(0, 0, 50, 100);
frame.getContentPane().add(label);
.....
}
later on, i will be using the following class to change the text of the above label. How can i do this.
public class Caller {
void methodA(){
MyClass mc = new MyClass();
mc.editTheLabelsValue("Hello");
}
}
1.) When the methodA() is executed, the text Hello is not getting displayed on the Label field. it still remains as Whooo. How can i correct this. I want the label text to be Hello once that method has been executed.
The immeditate problem I can see is to appears that you are either using a null layout or your don't understand how layout managers work.
The following code updates the label from the main class in a sub class via a setText method call. This method is called every second
public class PaintMyLabel {
private int counter = 0;
public static void main(String[] args) {
new PaintMyLabel();
}
public PaintMyLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final MasterPane master = new MasterPane();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(master);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
master.setText("Now updated " + counter + " times");
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
});
}
public class MasterPane extends JPanel {
private JLabel label;
public MasterPane() {
label = new JLabel("Original text");
setLayout(new GridBagLayout());
add(label);
}
public void setText(String text) {
label.setText(text);
}
}
}
If you're using a null layout, then stop it. Just don't. There are only a very small number of times you would ever use a null layout and I suspect this isn't one of them.