Custom view classes in IntelliJ IDEA - java

So I am building a Swing layout in IntelliJ IDEA using the layout manager GridLayoutManager(IntelliJ).
It's going ok, I can layout all my stuff etc but everything is in the same code file and considering I am using a JPanel with a JTabbedPane, I would like each pane of the tabbed pane to be represented in a separate class.
How is this possible?

There are a couple ways you could do this, either extending JPanel or creating another class which contains a JPanel
Inheritance Based Solution
public class MyCustomPanel extends JPanel {
// implement your custom behavior in here
}
Then in your where you create your JTabbedPane you'd have something like this:
private void init() {
JTabbedPane jtp = new JTabbedPane();
JPanel jp = new MyCustomPanel();
jtp.add(jp);
}
Although this works, extending JPanel may cause headaches in the long run. Another approache, which favors composition over inheritance might look something like this:
Composition Based Solution
public class MyCustomPanel {
private JPanel myPanel = new JPanel();
public MyCustomPanel() {
// add your customizations to myPanel
}
public JPanel getPanel() {
return myPanel;
}
}
and then where you create your JTabbedPane
private void init() {
JTabbedPane jtp = new JTabbedPane();
MyCustomPanel mp = new MyCustomPanel();
jtp.add(mp.getPanel());
}

Related

Setting an internal private panel opaque

Is there anyway i can set an internal private JPanel opaque? An example:
//Assuming I have no access rights to modify OuterPanel.java
class OuterPanel extends JPanel{
private JPanel internalPanel = new JPanel();
public OuterPanel(){
setLayout(new BorderLayout());
internalPanel.setOpaque(true);
add(internalPanel, BorderLayout.CENTER);
}
}
class MyClass{
private OuterPanel myPanel;
public MyClass(){
panel = new OuterPanel();
// is there anyway i can set myPanel's internalPanel to opaque(false)?
// assuming OuterPanel is a library and i have no way to modify it.
}
}
With the sample code above, assuming OuterPanel is a library class which I am unable to modify it's code, is there any way I could actually set it's internalPanel's opaque settings?
As mentioned by maloomeister. I used the following code to resolve this.
class OuterPanel extends JPanel{
private JPanel internalPanel = new JPanel();
public OuterPanel(){
setLayout(new BorderLayout());
internalPanel.setOpaque(true);
add(internalPanel, BorderLayout.CENTER);
}
}
class MyClass{
private OuterPanel myPanel;
public MyClass(){
panel = new OuterPanel();
setAllOpaque(panel.getComponents());
}
// This method is called recursively to set ALL JPanels
private void setAllOpaque(Component[] comp){
for (Component com : comp){
if (com instanceof JPanel){
JPanel p = (JPanel)com;
p.setOpaque(false);
setAllOpaque(p.getComponents());
}
}
}
}
I used recursion as this current example of OuterPanel is simple but my actual actual JPanel is actually a form filled with many different JPanels within it. This resolved it.
It might not be the most refined method, so if anyone has a better solution please do share! :)

How to change 'card' in Jframe cardlayout from Jpanel which belonging to card and its placed in another class?

I have written a jframe with cardlayout as in the following code :
public class Gui extends JFrame {
private static CardLayout cardlayout = new CardLayout();
private static JPanel cards = new JPanel(cardlayout);
public Gui() {
cards.setLayout(cardlayout);
CasaPanel card =new CasaPanel();
cards.add(card,"casa");
InCash card_1 = new InCash();
cards.add(card_1,"in");
OutCash card_2 = new OutCash();
cards.add(card_2,"out");
setLayout(new BorderLayout());
add(cards, BorderLayout.CENTER);
}
public static void showCard(String name)
{
cardlayout.show(cards, name);
}
i'm trying to call method to change card (ShowCard) from one of the JPanel(CasaPanel) , which is itself a 'card'. I want change a 'card' after clicking a button in a JPanel(CasaPanel) which is in another class. How to do this?I mean i know how to add button and listener but i don't know if is it possible to call a method in JFrame from a Jpanel class belonging to that frame ? How to refer to method in JFrame from other classes? I looked at this question but i really don't want put all code in one class.
Your "card" is added to the panel which uses the CardLayout. If you want to change cards then you just need access to the layout mananger. So from your panel you can use the getParent() method to get the parent panel and then use the getLayout() method to get the CardLayout.
So the code in the ActionListener might be something like:
JPanel parent = (JPanel)getParent();
CardLayout layout = parent.getLayout();
layout.show(panel, "...");
Also, then general design on your class is wrong. You should NOT be using static methods. Read the section from the Swing tutorial on How to Use CardLayout for working examples and a better way to structure your code.

Swing - scroll JFrame content without using scrollbars

I have following problem. Is there a way to scroll Jframe content without using scrollbars, just to do it programatically in code. I have Japplet inside and I can't find a way to scroll its content without showing scrolls. Whole scrolling action should be performed not on user action, but when my thread wants to do so. Waiting for help, thanks.
I can't find any way to do that. I was trying to add my component (Applet) to Jscrollpane and that to jframe, but it causes situation, when only white screen is displayed.
JFrame class:
public class SimulationFrame extends JFrame {
private SimulationWindow simulationWindow;
public SimulationFrame() throws HeadlessException {
super(PropertiesHelper.getWindowTitle());
simulationWindow = new SimulationWindow();
JScrollPane scrollPane = new JScrollPane(simulationWindow);
this.getContentPane().add(scrollPane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
}
JComponent:
public SimulationWindow() {
setLayout(new BorderLayout());
graph = GraphHelper.provideGraphInstance();
Dimension layoutSize = new Dimension(PropertiesHelper.getGraphHolderWidth(),
PropertiesHelper.getGraphHolderHeight());
graphLayout = new StaticLayout<Checkpoint, Route>(graph, new CheckpointPositionTransformer());
graphLayout.setSize(layoutSize);
visualizationViewer = new VisualizationViewer<Checkpoint, Route>(graphLayout, new Dimension(
PropertiesHelper.getWindowWidth(), PropertiesHelper.getWindowHeight()));
visualizationViewer.getRenderContext().setVertexLabelTransformer(new CheckpointLabelTransformer());
visualizationViewer.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
visualizationViewer.getRenderContext().setVertexFillPaintTransformer(new CheckpointColorTransformer());
visualizationViewer.getRenderContext().setEdgeDrawPaintTransformer(new RouteColorTransformer());
visualizationViewer.getRenderContext().setEdgeLabelTransformer(new RouteLabelTransformer());
final ImageIcon mapBackground = createMapBackground();
if (mapBackground != null) {
mapBackgroundImagePaintable = new BackgroundImagePaintable(visualizationViewer, mapBackground);
visualizationViewer.addPreRenderPaintable(mapBackgroundImagePaintable);
}
add(visualizationViewer);
scrollRectToVisible(new Rectangle(1000,100));
}
VisualizationViewer is a class that extends JPanel. Placing scrollRectToVisible in this constructor didn't works.
Any tips? Perhaps this implementation is wrong, where Jcomponent contains Jpanel itself?
Use method
public void scrollRectToVisible(Rectangle aRect)
of the JComponent added in JScrollPane

Should I add components to a JFrame or to its contentPane?

When I learned creating Java GUI:s in my first Java course, I was taught to create my windows as JFrame instances, and then add a JPanel to each JFrame and finally add all the GUI components to the JPanel:
class Example extends JFrame {
Example() {
JPanel panel = new JPanel();
this.add(panel);
// Create components here and add them to panel
// Perhaps also change the layoutmanager of panel
this.pack();
this.setVisibility(true);
}
public static void main(String[] args) {
new Example();
}
}
I always though "well, this smells a little; I don't like creating an extra object just to be a container," but I didn't know any other way to do it so I just went on with it. Until recently, when I stumbled over this "pattern":
class AnotherExample extends JFrame {
AnotherExample() {
Container pane = this.getContentPane();
// Add components to and change layout of pane instead
this.pack();
this.setVisibility(true);
}
public static void main(String[] args) {
new AnotherExample();
}
}
Still being quite new to Java, I feel better about the second approach just because it doesn't involve creating a JPanel just to wrap the other components. But what are the real differences between the approaches, except from that? Does any one of them have any great benefits over the other?
I prefer to create a JPanel (which, being a Swing container, can have a border) and set it as the content pane.
To get a JComponent out of the content pane requires casting, which has an even worse smell than creating an extra component.

Creating an Outlook style user interface in Java?

I'm looking to create an Outlook style UI in a Java desktop app, with a list of contexts or nodes in a lefthand pane, and the selected context in a pane on the right. How do I go about this?
I'm looking for a bit more detail than 'use a JFrame'. A tutorial or walk through would be good, or some skeleton code, or a framework/library that provides this kind of thing out of the box.
Thanks.
Edit
My (edited) code so far:
UIPanel
public class UIPanel extends javax.swing.JPanel {
private final JSplitPane splitPane;
public UIPanel() {
super(new BorderLayout());
initComponents();
JPanel contextPnl = new ContextPanel();
JPanel treePnl = new NodePanel(contextPnl);
this.splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true, new JScrollPane(treePnl), new JScrollPane(contextPnl));
add(splitPane, BorderLayout.CENTER);
//not sure I need these?
splitPane.setVisible(true);
treePnl.setVisible(true);
contextPnl.setVisible(true);
}
NodePanel
public class NodePanel extends javax.swing.JPanel {
JPanel _contextPanel;
public NodePanel(JPanel contextPanel) {
initComponents();
_contextPanel = contextPanel;
initialise();
}
private void initialise(){
nodeTree.addTreeSelectionListener(getTreeListener());
}
private TreeSelectionListener getTreeListener(){
return new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
nodeTree.getLastSelectedPathComponent();
// if nothing is selected
if (node == null)
return;
// get selected node
Object nodeInfo = node.getUserObject();
CardLayout layout = (CardLayout) _contextPanel.getLayout();
//layout.show(_contextPanel, "test"); //show context for selected node
}
};
}
ContextPanel
public class ContextPanel extends javax.swing.JPanel {
JPanel _cards;
final static String CONTEXT1 = "Context 1";
final static String CONTEXT2 = "Context 2";
JPanel _context1;
JPanel _context2;
public ContextPanel() {
initComponents();
intialiseContexts();
}
public void updateContext(String contextName){
//TODO
}
private void intialiseContexts(){
_context1 = new NodeContext();
_context2 = new NodeContext();
_cards = new JPanel(new CardLayout());
_cards.add(_context1, CONTEXT1);
_cards.add(_context2, CONTEXT2);
}
The key concept here is to define a JSplitPane as your top-level Component with a horizontal split. The left-hand side of the split pane becomes your "tree" view while the right-side is the context panel.
The trick is to use CardLayout for your context panel and to register a TreeSelectionListener with the tree panel's JTree so that whenever a tree node is selected, the CardLayout's show method is called in order to update what the context panel is currently showing. You will also need to add the various Components to the context panel in order for this approach to work.
public class UIPanel extends JPanel {
private static final String BLANK_CARD = "blank";
private final JSplitPane splitPane;
public UIPanel() {
super(new BorderLayout());
JPanel treePnl = createTreePanel();
JPanel contextPnl = createContextPanel();
this.splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true, new JScrollPane(treePnl), new JScrollPane(contextPnl));
add(splitPane, BorderLayout.CENTER);
}
}
EDIT: Example Usage
public class Main {
public static void main(String[] args) {
// Kick off code to build and display UI on Event Dispatch Thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("UIPanel Example");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// Add UIPanel to JFrame. Using CENTER layout means it will occupy all
// available space.
frame.add(new UIPanel(), BorderLayout.CENTER);
// Explicitly set frame size. Could use pack() instead.
frame.setSize(800, 600);
// Center frame on the primary display.
frame.setLocationRelativeTo(null);
// Finally make frame visible.
frame.setVisible(true);
}
});
}
}
Additional Advice
I can see you've created separate classes for your NodePanel and ContextPanel. Given the simplicity of these classes and how tightly coupled they are it probably makes more sense to embed all the UI components directly within UIPanel and have utility methods that build the two sub-panels. If you do keep with NodePanel and ContextPanel try to make them package private rather than public.
The CardLayout approach works well if you have a small(ish) number of nodes and you know them in advance (and hence can add their corresponding Components to the CardLayout in advance). If not, you should consider your context panel simply using BorderLayout and, whenever you click on a node you simply add the relevant node component to the BorderLayout.CENTER position of the NodePanel and call panel.revalidate() to cause it to perform its layout again. The reason I've used CardLayout in the past is that it means my nodes only need to remember one piece of information: The card name. However, now I think of it I don't see any real disadvantage with this other approach - In fact it's probably more flexible.
You might want to look at using a platform like eclipse as a starting point. It provides a very rich environment for creating these applications so you do not have to start everything from scratch. The online guides and help are very good and there are several books on the subject.

Categories

Resources