This is my main class.
package pomsystem;
public class POMSystem {
public static void main(String[] args) {
new ItemList();
}
}
This is the second class frame that I want to navigate.
package pomsystem;
import java.awt.Button;
import java.awt.Color;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
class UI extends JFrame{
TextField txtID, txtItem, txtStock, txtSupplierID;
Label lblID, lblItem, lblStock, lblSupplierID;
Button btnSearch, btnClear, btnBack;
}
public class ItemList extends UI {
private String ID;
private int Stock;
public ItemList(String ID, int Stock) {
setSize(600, 400);
setLocation(380, 120);
setLayout(null);
setTitle("Item Entry");
setVisible(true);
setBackground(Color.LIGHT_GRAY);
}
}
It shown me a error with Constructor in class cannot be applied to given types, I know the error is from the parameters of second frame.
Is that any approach to solve the problem.
I'm new to Java OOP sorry.
You declared a custom constructor:
public ItemList(String ID, int Stock){
setSize(600,400);
setLocation(380,120);
setLayout(null);
setTitle("Item Entry");
setVisible(true);
setBackground(Color.LIGHT_GRAY);}
overwriting the standard empty Java Object constructor, which is:
public ItemList(){}
Just add the constructor without arguments again in your code as an alternative constructor:
public ItemList(){
setSize(600,400);
setLocation(380,120);
setLayout(null);
setTitle("Item Entry");
setVisible(true);
setBackground(Color.LIGHT_GRAY);}
}
Otherwise you could also call your custom constructor with values:
new ItemList("example", 0);
Related
I've been making a battleship program that I've been trying to get working with a GUI, but it doesn't want to work. The way in theory it should work is that the GUI starts, it outputs a question to a box(which works), and then the computer waits and executes nothing until you press the button after you've answered your answer to the question. The problem is, my method that waits until you've clicked the button to fetch the data in the text field doesn't do anything. I've written a similar piece of code which demonstrates my problem below.
Test.java (main class)
package taest;
import javax.swing.*;
public class Test {
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
#SuppressWarnings("unused")
JFrame frame = new Frame();
}
});
Frame.display.setText(getButtonClick());
}
public static String getButtonClick(){
while(true){
if (Frame.hasClicked){
break;
}
}
return Frame.text.getText();
}
}
Frame.java (Frame class)
package taest;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Frame extends JFrame{
JFrame panel = new JFrame("Something");
public static JTextArea text = new JTextArea();
JButton button = new JButton("Click");
public static JTextField display = new JTextField("NOthing");
static boolean hasClicked = false;
static String storage = "";
public Frame(){
setLayout(new BorderLayout());
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hasClicked = true;
storage = text.getText();
}
});
Container c = getContentPane();
c.add(display, BorderLayout.CENTER);
c.add(text, BorderLayout.PAGE_START);
c.add(button, BorderLayout.PAGE_END);
setVisible(true);
}
}
Static is not your friend and it's use should be greatly limited. It should NEVER be used to provide "easy" access to class fields for inter class communication
You need to turn the concept on it's head and possibly use some kind of Observer Pattern. This is where you have a class which is "observing" changes on your other class. When a change occurs the observed class notifies the observing class of the change. This decouples the responsibility as the observed class shouldn't care beyond notifying interested parties about something that happens
As a really primitive example...
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String args[]) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
#SuppressWarnings("unused")
JFrame frame = new Frame(new ViewController() {
#Override
public void messageChanged(View view, String msg) {
view.appendLog(msg);
}
});
}
});
}
public interface ViewController {
public void messageChanged(View view, String msg);
}
public interface View {
public void appendLog(String log);
}
public class Frame extends JFrame implements View {
// JFrame panel = new JFrame("Something");
private JTextArea text = new JTextArea(5, 5);
private JButton button = new JButton("Click");
private JTextField display = new JTextField("NOthing");
private String storage = "";
private ViewController viewController;
public Frame(ViewController controller) {
this.viewController = controller;
setLayout(new BorderLayout());
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
storage = text.getText();
viewController.messageChanged(Frame.this, storage);
}
});
System.out.println("display = " + display.hashCode());
System.out.println("text = " + text.hashCode());
Container c = getContentPane();
c.add(display, BorderLayout.CENTER);
c.add(text, BorderLayout.PAGE_START);
c.add(button, BorderLayout.PAGE_END);
setVisible(true);
}
#Override
public void appendLog(String log) {
display.setText(log);
}
}
}
You should also become farmiluar within the concept of Model–view–controller
You are mixing things up,
First things first, the difference between Classes and Objects. A class is a blueprint for an object, so an example of a class is Car. The blueprint of such an object however knows nothing about the state of a particular instance of that class, lets assume that you drive 100 km/u, then you have an instance of Car that stores that it is going at 100 km/u. Blueprints are classes, Objects are instances.
So, public class Car makes an blueprint for cars, and new Car() makes a specific instance of that blueprint in which you can store runtime information.
Now there is a way to tell Java that things belong to the blueprint, static. If a variable is static it is attached to the blueprint. So to keep up with the analogy of cars, a static variable for a car can be its wheelbase, thats something that is defined at compiletime (or in the car analogy at create time).
Back to your problem, you are mixing up classes and objects, what you want to do is have a BattleshipWindow of which instances exist. Of this BattleshipWindow an instance can be created with new, and then its properties can be changed.
Not exactly the answer you want probably, but I hope you now understand the difference between classes and objects, that will help you solve your problem.
i want to know how to set the color of a button (in example, but i will need to set every component color) with the apple look and feel.
I found an answer in stackoverflow that suggest to change to the standard look and feel, that works for me, but i prefer not to change because I like apple's one.
Is there any solution?
I know there is because I saw many apps written in java that have colored buttons and also that use particular styles or images as background.
Can you tell me a solution?
Extend the Jbutton class and in that override the repaint() method and call setBackground(COLOR.ORANGE), to change the button color.
Now use this class to create all your buttons. If you wish to change color of a specific button, call the setBackground(COLOR.ORANGE) method on that specific button. Hope this helps. Have a look at the code below
package solutions;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class VerifierTest extends JFrame {
private static final long serialVersionUID = 1L;
public VerifierTest() {
final JTextField tf = new JTextField("TextField1");
getContentPane().add(tf, BorderLayout.NORTH);
tf.setInputVerifier(new PassVerifier());
final JTextField tf2 = new JTextField("TextField2");
getContentPane().add(tf2, BorderLayout.SOUTH);
tf2.setInputVerifier(new PassVerifier());
final JButton b = new JButton("Button");
b.setBackground(Color.ORANGE);
b.setVerifyInputWhenFocusTarget(true);
getContentPane().add(b, BorderLayout.EAST);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!tf.getInputVerifier().verify(tf)) {
JOptionPane.showMessageDialog(tf.getParent(), "illegal value: " + tf.getText(), "Illegal Value",
JOptionPane.ERROR_MESSAGE);
}
if (b.isFocusOwner()) {
System.out.println("Button clicked");
}
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Frame frame = new VerifierTest();
frame.setSize(400, 200);
frame.setVisible(true);
}
class PassVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
final JTextField tf = (JTextField) input;
String pass = tf.getText();
if (pass.equals("Manish")) {
return true;
} else {
return false;
}
}
}
}
Comment the line "b.setBackground(Color.ORANGE);" and see the difference.
I tried to access a JInternalFrame in my JDesktopPane and use getAllFrames method.
I just want to access the JInternalFrame in the order that i added into the JDesktopPane.
for example, i add a,b,c
frames[0] contain a
frames[1] contain b
frames[2] contain c
But i found out that the content in the array will change in case that i change my selection.
Every time I change my selection.
The selected JInternalFrame in the array will move to the top one.
For example , I select b
The array will become
frames[0] contain b
frames[1] contain a
frames[2] contain c
Are there any other ways to get the internal frame in the order i add it into desktoppane??
package org.app;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
public class MainFrame extends JFrame{
private static final long serialVersionUID = 1L;
private JDesktopPane theDesktop;
private List<JInternalFrame> frameList=new ArrayList<>();
public MainFrame() {
super("Internal Frame Demo");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setJMenuBar(setMenubar());
theDesktop=new JDesktopPane();
this.add(theDesktop);
this.setVisible(true);
}
public JMenuBar setMenubar() {
JMenuBar bar=new JMenuBar();
JMenu addMenu=new JMenu("Add");
JMenuItem newFrame=new JMenuItem("Internal Frame");
newFrame.addActionListener(new MenuAction());
addMenu.add(newFrame);
bar.add(addMenu);
return bar;
}
public JInternalFrame addInternalFrame() {
JInternalFrame jif=new JInternalFrame("Internal frame",true,true,true,true);
jif.setSize(new Dimension(240, 300));
jif.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e){
frameList.remove(e.getInternalFrame());
System.out.println("from frame closing event");
}
});
jif.show();
return jif;
}
public JInternalFrame getInternalFrame(int index) {
return frameList.get(index);
}
class MenuAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JInternalFrame f=addInternalFrame();
theDesktop.add(f);
frameList.add(f);
System.out.println("from menu action");
}
}
public static void main(String[] args){
new MainFrame();
}
}
Please have a look at the following code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.text.*;
public class Form1 extends JFrame
{
private JTextPane textPane;
private JPanel south;
private JScrollPane scroll;
private String content;
public String documentType;
private DefaultStyledDocument document;
int start, end, offset1,length1;
private JButton button;
JFrame frame;
public Form1()
{
//Declaring the instance variables
textPane = new JTextPane();
textPane.setMinimumSize(new Dimension(100,100));
button = new JButton("Bold");
button.addActionListener(new StyledEditorKit.BoldAction());
button.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_B,KeyEvent.CTRL_MASK),"key");
button.getActionMap().put("key", new StyledEditorKit.BoldAction());
document = (DefaultStyledDocument) textPane.getDocument();
//Creating the main window
south = new JPanel();
south.setLayout(new FlowLayout());
south.add(button);
scroll = new JScrollPane(textPane);
getContentPane().add(scroll,"Center");
getContentPane().add(south,"South");
setSize(800,600);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class Action extends AbstractAction
{
public void actionPerformed(ActionEvent ae)
{
new StyledEditorKit.BoldAction();
}
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run() {
Form1 f = new Form1();
f.setVisible(true);
}
});
}
}
In here, user can enter any text, and when he select a text and click on "Bold" button, the text will be bold. However, I need to do it using CTRL+B also. As you can see, my attempt is not giving any response to that key event. I even tried adding it to a seperate class which extends AbstractAction, but still no good. How can I implement the CTRL+B here? Please help...
When key bindings don't work for me, the first place I look is the InputMap -- am I sure that I'm using the right one? Well, are you sure? The default one uses JComponent.WHEN_FOCUSED and thus only works if your component has the focus.
If you want it to work at other times, say when the bound component is visible and in a focused window but doesn't necessarily have the focus itself, perhaps you should try different condition parameters. Try using JComponent.WHEN_IN_FOCUSED_WINDOW to start with.
i.e.,
InputMap inputMap = myComponent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
Working in Java: I have a JFrame class, and separate classes for my two JPanels that are added to the JFrame. One of the JPanel classes has some buttons in it, which can interact with each other(when I click on one button, it can disable another button). However, I can't figure out how to get the button to call a method in the other JPanel (written in a separate class).
So, my program look like this:
JFrame
Jpanel1
Jpanel2 - This class has my buttons in it, I'm trying to get them to interact with the JPanel1 object.
Any tips appreciated, thanks!
One way to do this is to pass an instance of (to use your terminology) Jpanel1 into Jpanel2. This doesn't have to be done in the constructor, you can have a setConnectedPanel(JPanel) method, for example.
Here's some code that demonstrates what you want to do:
MyFrame.java
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MyFrame extends JFrame {
public MyFrame() {
ReactionPanel rp = new ReactionPanel();
ActionPanel ap = new ActionPanel(rp);
setLayout(new GridLayout(2, 1));
add(ap);
add(rp);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyFrame();
}
});
}
}
ActionPanel.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ActionPanel extends JPanel implements ActionListener {
private ReactionPanel rp;
private JButton button;
public ActionPanel(ReactionPanel rp) {
this.rp = rp;
button = new JButton("Click");
button.addActionListener(this);
this.add(button);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(button)) {
rp.react();
}
}
}
ReactionPanel.java
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ReactionPanel extends JPanel {
private JLabel label;
public ReactionPanel() {
label = new JLabel("PING");
this.add(label);
}
public void react() {
if(label.getText().equals("PING")) {
label.setText("PONG");
} else {
label.setText("PING");
}
}
}
As you can see, I tend to override all of my JFrames/JPanels when I write Swing GUIs as I find it easier and more flexible but YMMV.