pass and name variables - java

I'm a beginner of Java and trying to figure out building a JScrollPane. I have following codes so far but it's having a problem calling JScrollPane. Please help. Thanks in advance.
public class DemoTest {
public String sTEXT = null;
public JTextArea jTEXTAREA = null;
public JScrollPane jPANE = null;
public JFrame jFRAME = null;
public static void main(String[] args) {
DemoTest demo = new DemoTest();
}
public DemoTest() {
setText();
setPane();
setFrame();
}
public void setFrame() {
JFrame jFRAME = new JFrame("Demo");
jFRAME.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFRAME.setSize(350, 300);
jFRAME.setLocationRelativeTo(null);
jFRAME.setVisible(true);
jFRAME.add(jPANE); // **THIS SEEMS TO BE THE PROBLEM**
}
public void setPane() {
JScrollPane jPANE = new JScrollPane(jTEXTAREA);
}
public void setText() {
JTextArea jTEXTAREA = new JTextArea();
jTEXTAREA.setText("Hello World!");
jTEXTAREA.setEditable(false);
}
}

When you attempted to create the various Swing Objects, you were creating new local variables instead of assigning to the member variables (class level). Note that if you have a member variable and local variable of the same name, you may assign to the member variable by using this.VAR_NAME = ...;. For a better understanding of variable scope, read this Scope of Variables in Java post which explains the basics well.
public class DemoTest {
public String sTEXT = null;
public JTextArea jTEXTAREA = null;
public JScrollPane jPANE = null;
public JFrame jFRAME = null;
public static void main(String[] args) {
DemoTest demo = new DemoTest();
}
public DemoTest(){
setText();
setPane();
setFrame();
}
public void setFrame(){
jFRAME = new JFrame ("Demo");
jFRAME.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFRAME.setSize(350,300);
jFRAME.setLocationRelativeTo(null);
jFRAME.setVisible(true);
jFRAME.add(jPANE);
}
public void setPane(){
jPANE = new JScrollPane(jTEXTAREA);
}
public void setText(){
jTEXTAREA= new JTextArea();
jTEXTAREA.setText("Hello World!");
jTEXTAREA.setEditable(false);
}
}

Related

Where to put action listeners?

I'm a little confused about where the best class is for ActionListener instances in a small Swing application.
If I have a Controller, a MainFrame for the main JFrame and various JPanel containers such as LeftPanel, RightPanel etc, each with buttons, a list etc.
Where's the best place to put the action listeners? Should I have them in the same class as the components (as an inner class or class implementing action listener), in the MainFrame as this is the 'parent' of all the panels, or in the Controller, which really only has the main() method and a few other Swing details?
Each approach seems to have its pros and cons. I am trying to un-couple features from functionality but I'm finding it hard to work this out.
Or have I missed another (better) way?
One possible for the panels to communicate with each other is through the main frame. Each panel would have a reference to the main frame and the main frame provides all the operations such as reading data from the form, updating data to the form. Below is an example:
class UserForm extends JPanel {
private final MyApp app;
private final JTextField userNameField = new JTextField(20);
public UserForm(MyApp app){
this.app = app;
this.add(userNameField);
}
public String getUserName(){
return userNameField.getText();
}
public void setUserName(String name){
userNameField.setText(name);
}
}
class FormControl extends JPanel {
private final MyApp app;
private final JButton randNameButton = new JButton("Random");
private final JButton saveButton = new JButton("Save");
private final String[] names = {"john", "mike", "bill", "joe"};
private final Random r = new Random();
public FormControl(MyApp app){
this.app = app;
this.setLayout(new FlowLayout());
this.add(randNameButton);
this.add(saveButton);
randNameButton.addActionListener(e->app.setUserName(names[r.nextInt(4)]));
saveButton.addActionListener(e->app.save());
}
}
public class MyApp extends JFrame{
private final UserForm form = new UserForm(this);
private final FormControl control = new FormControl(this);
public MyApp(){
this.setTitle("Demo");
this.setSize(200, 100);
JPanel pane = new JPanel();
pane.setSize(200,100);
pane.setLayout(new BorderLayout());
pane.add(form, BorderLayout.NORTH);
pane.add(control, BorderLayout.SOUTH);
this.setContentPane(pane);
}
// all the operations are here.
public String getUserName(){
return form.getUserName();
}
public void setUserName(String userName){
form.setUserName(userName);
}
public void save(){
System.out.println("Saving");
System.out.println(getUserName());
System.out.println("Done saving.");
}
public static void main(String[] args) {
new MyApp().setVisible(true);
}
}
I would use lambda for action listener. See example below:
public class JavaApplication7 extends JFrame{
public JavaApplication7(){
this.setTitle("Demo");
this.setSize(100, 100);
JButton b = new JButton("Click");
b.addActionListener(e->{
System.out.println("hello");
System.out.println("from " + this.getTitle());
});
this.setContentPane(b);
}
public static void main(String[] args) {
new JavaApplication7().setVisible(true);
}
}

Java - Jframe not displaying Buttons Labels or textfields

im new to java but when I try to create a new frame all I get is a new window open with a white background on and none of the buttons or text boxes or labels get added. I don't know what im doing wrong?
private static void MainGui(){
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle(name+ "'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
MainInterfaces Class
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
Your code doesn't compile because you have a lot of errors (you have no main method, private static void MainGui(){ makes no sense etc.). Try this code instead which compiles and opens the GUI fine for me, showing everything as you want to (the buttons, the labels, etc.):
1) Class MainGui.java
class MainGui{
public static void main(String[] args) {
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle("'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(MainGui.EXIT_ON_CLOSE);
}
}
2) Class MainInterfaces.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
I fixed it with one line of code. Just switch the "setVisible(true)" method to being inside the MainInterface class. However, make sure you put it as the last line of code inside the constructor, or it won't work. Basically, what was happening is that while the frame itself was being set to be true, the components were being added afterwards and were consequently not being shown. Putting "setVisible(true)" last makes sure all the components are added when you display the frame.
As a side note, you can add all methods you typed in the MainGUI class inside of MainInterface.
Here's MainGUI:
public class MainGUI
{
public static void main(String[] args)
{
new MainInterfaces();
}
}
Here's what MainInterfaces looks likes:
public class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces()
{
setTitle("(Name)'s Inbox");
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl); add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
}

jlabel and paintComponent in same jframe in java

the code down here only calls the class(class "oefen") whith the code that makes a jframe and a ball(using the painComponent method)and if you press the arrow keys it moves in that direction...it works fine but when i add the target(jlabel) to the jframe only the target shows and nothing else..please help me to put the target and ball in the same frame
public class theFrame implements KeyListener {
public static JFrame j = new JFrame();
public static ImageIcon tar = new ImageIcon("c://fruit//target.png");
public static JLabel target = new JLabel(tar);
public static JPanel p = new JPanel();
public static void main(String args[]){
j.setSize(500,600);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setVisible(true);
oefen o = new oefen();
j.add(o);
target.setLayout(null);
target.setSize(100,100);
target.setLocation(250,0);
j.add(target);
}
}
thanks
public class theFrame extends JComponent {
public static JFrame j = new JFrame();
public static ImageIcon tar = new ImageIcon("c://fruit//target.png");
public static JLabel target = new JLabel(tar);
public static JPanel p = new JPanel();
public static oefen o = new oefen();
public static void main(String args[]){
j.setSize(500,600);
j.setLayout(null);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setVisible(true);
target.setLayout(null);
target.setSize(0,0);
target.setLocation(0,0);
j.add(o);
j.add(target);
}
}
if i set the JFrame Layout to null notihng shows...the code above shows how i set the JFrameLayout cuz i don't know if its wrong.
please help
try setting the JFrames layout to null too, because you use absolute positioning.

JFrame not showing up

I have one class called TabBuilder which I use to create the interface of my application, but I'm going through a weird problem. If I try to run the code as it's below it will draw the mainScreen but if I request the SearchScreen from the BarMenu it doesn't show up. If I try to execute only SearchScreen by itself (calling its builder) within the public static void main (String[] args) MainString it wont show up too. but If go to the request event and tip TabBuilder tb = new TabBuilder(); tb.requestTab();the screen will show up as it should be. So, what might be wrong? Thanks in advance
MainScreen:
public class MainScreen{
public MainScreen()
{
TabBuilder tb = new TabBuilder();
tb.mainTab();
}
}
SearchScreen:
public class SearchScreen{
public void SearchScreen(){
TabBuilder tb = new TabBuilder();
tb.requestTab();
}
}
TabBuilder:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TabBuilder implements ActionListener {
JTabbedPane tabbedPane = new JTabbedPane();
JMenuItem close, request;
protected JTextField txtrequest = new JTextField();
JButton btrequest = new JButton();
protected JFrame requestFrame = new JFrame();
public void TabBuilder(){
}
public void mainTab(){
JMenuBar bar;
JMenu file, register;
JFrame mainFrame = new JFrame();
bar= new JMenuBar();
file= new JMenu("File");
register= new JMenu("Request");
close= new JMenuItem("Close");
close.addActionListener(this);
request= new JMenuItem("Request Query");
request.addActionListener(this);
bar.add(file);
bar.add(register);
file.add(close);
register.add(request);
mainFrame.setExtendedState(mainFrame.getExtendedState() | mainFrame.MAXIMIZED_BOTH); // Maximized Window or setSize(getMaximumSize());
mainFrame.setTitle("SHST");
mainFrame.setJMenuBar(bar);
mainFrame.setDefaultCloseOperation(0);
mainFrame.setVisible(true);
WindowListener J=new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
};
mainFrame.addWindowListener(J);
}
public void requestTab(){
JLabel lbrequest;
JPanel requestPane;
btrequest= new JButton("request");
lbrequest= new JLabel("Type Keywords in english to be requested below:");
txtrequest= new JTextField();
requestPane=new JPanel();
requestPane.setBackground(Color.gray);
requestPane.add(lbrequest);
requestPane.add(txtrequest);
requestPane.add(btrequest);
requestPane.setLayout(new GridLayout(3,3));
btrequest.setEnabled(true);
requestFrame.add(requestPane);
requestFrame.setTitle("SHST");
requestFrame.setSize(400, 400);
requestFrame.setVisible(true);
requestFrame.setDefaultCloseOperation(1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==request){
TabBuilder tb = new TabBuilder();
tb.requestTab();
}
}
public static void main (String[] args){
MainScreen m = new MainScreen();
}
}
The constructor of SearchScreen was settled as void. That caused nothing to return as object when calling the constructor. Newbie failure but simple solution.

Need help to fix ComboBox programming error

I'm a kinda newbie actually and just self-studying. I really want to learn how to use JComboBox properly. I have created a simple program but it took me forever to fix it.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SampleButtonKo {
JComboBox combo;
public void ComboBox1() {
String course[] = {
"PM1", "PM2", "PM3", "PM4"
};
JFrame frame = new JFrame("Mang Inasal Ordering System");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
panel.add(combo);
frame.add(panel);
combo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String str = (String) combo.getSelectedItem();
System.out.print("You have chosen " + str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
JComboBox = new JComboBox();
}
}
You forgot a name for the variable
Instead of
JComboBox = new JComboBox();
try
JComboBox j = new JComboBox();
^
But perhaps, as iTech suggests, you want to create an instance of your class.
new SampleButtonKo();
There are obvious few errors in your code, you need to have the constructor named exactly as your class with no return type. Second, in your main you should create an instance of your class not the JComboBox
public class SampleButtonKo{
JComboBox combo;
public SampleButtonKo(){
// Copy your code from "ComboBox1" here
}
public static void main(String[] args) {
new SampleButtonKo();
}
}

Categories

Resources